File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.976.2.6: download - view: text, annotated - select for diffs
Mon Jan 5 16:29:24 2009 UTC (15 years, 6 months ago) by raeburn
Branches: version_2_8_X
CVS tags: version_2_8_0, version_2_7_99_1
Diff to branchpoint 1.976: preferred, unified
- Backport 1.983.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.976.2.6 2009/01/05 16:29:24 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=shift;
  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 ($key=~/^\Q$delthis\E/) { 
  539: 		delete($env{$key});
  540: 		delete($disk_env{$key});
  541: 	    }
  542: 	}
  543: 	untie(%disk_env);
  544:     }
  545:     return 'ok';
  546: }
  547: 
  548: sub get_env_multiple {
  549:     my ($name) = @_;
  550:     my @values;
  551:     if (defined($env{$name})) {
  552:         # exists is it an array
  553:         if (ref($env{$name})) {
  554:             @values=@{ $env{$name} };
  555:         } else {
  556:             $values[0]=$env{$name};
  557:         }
  558:     }
  559:     return(@values);
  560: }
  561: 
  562: # ------------------------------------------------------------------- Locking
  563: 
  564: sub set_lock {
  565:     my ($text)=@_;
  566:     $locknum++;
  567:     my $id=$$.'-'.$locknum;
  568:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  569:              'session.lock.'.$id => $text});
  570:     return $id;
  571: }
  572: 
  573: sub get_locks {
  574:     my $num=0;
  575:     my %texts=();
  576:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  577:        if ($lock=~/\w/) {
  578:           $num++;
  579:           $texts{$lock}=$env{'session.lock.'.$lock};
  580:        }
  581:    }
  582:    return ($num,%texts);
  583: }
  584: 
  585: sub remove_lock {
  586:     my ($id)=@_;
  587:     my $newlocks='';
  588:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  589:        if (($lock=~/\w/) && ($lock ne $id)) {
  590:           $newlocks.=','.$lock;
  591:        }
  592:     }
  593:     &appenv({'session.locks' => $newlocks});
  594:     &delenv('session.lock.'.$id);
  595: }
  596: 
  597: sub remove_all_locks {
  598:     my $activelocks=$env{'session.locks'};
  599:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  600:        if ($lock=~/\w/) {
  601:           &remove_lock($lock);
  602:        }
  603:     }
  604: }
  605: 
  606: 
  607: # ------------------------------------------ Find out current server userload
  608: sub userload {
  609:     my $numusers=0;
  610:     {
  611: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  612: 	my $filename;
  613: 	my $curtime=time;
  614: 	while ($filename=readdir(LONIDS)) {
  615: 	    next if ($filename eq '.' || $filename eq '..');
  616: 	    next if ($filename =~ /publicuser_\d+\.id/);
  617: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  618: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  619: 	}
  620: 	closedir(LONIDS);
  621:     }
  622:     my $userloadpercent=0;
  623:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  624:     if ($maxuserload) {
  625: 	$userloadpercent=100*$numusers/$maxuserload;
  626:     }
  627:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  628:     return $userloadpercent;
  629: }
  630: 
  631: # ------------------------------------------ Fight off request when overloaded
  632: 
  633: sub overloaderror {
  634:     my ($r,$checkserver)=@_;
  635:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  636:     my $loadavg;
  637:     if ($checkserver eq $perlvar{'lonHostID'}) {
  638:        open(my $loadfile,'/proc/loadavg');
  639:        $loadavg=<$loadfile>;
  640:        $loadavg =~ s/\s.*//g;
  641:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  642:        close($loadfile);
  643:     } else {
  644:        $loadavg=&reply('load',$checkserver);
  645:     }
  646:     my $overload=$loadavg-100;
  647:     if ($overload>0) {
  648: 	$r->err_headers_out->{'Retry-After'}=$overload;
  649:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  650:         return 413;
  651:     }    
  652:     return '';
  653: }
  654: 
  655: # ------------------------------ Find server with least workload from spare.tab
  656: 
  657: sub spareserver {
  658:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  659:     my $spare_server;
  660:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  661:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  662:                                                      :  $userloadpercent;
  663:     
  664:     foreach my $try_server (@{ $spareid{'primary'} }) {
  665: 	($spare_server, $lowest_load) =
  666: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  667:     }
  668: 
  669:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  670: 
  671:     if (!$found_server) {
  672: 	foreach my $try_server (@{ $spareid{'default'} }) {
  673: 	    ($spare_server, $lowest_load) =
  674: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  675: 	}
  676:     }
  677: 
  678:     if (!$want_server_name) {
  679:         my $protocol = 'http';
  680:         if ($protocol{$spare_server} eq 'https') {
  681:             $protocol = $protocol{$spare_server};
  682:         }
  683: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  684:     }
  685:     return $spare_server;
  686: }
  687: 
  688: sub compare_server_load {
  689:     my ($try_server, $spare_server, $lowest_load) = @_;
  690: 
  691:     my $loadans     = &reply('load',    $try_server);
  692:     my $userloadans = &reply('userload',$try_server);
  693: 
  694:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  695: 	next; #didn't get a number from the server
  696:     }
  697: 
  698:     my $load;
  699:     if ($loadans =~ /\d/) {
  700: 	if ($userloadans =~ /\d/) {
  701: 	    #both are numbers, pick the bigger one
  702: 	    $load = ($loadans > $userloadans) ? $loadans 
  703: 		                              : $userloadans;
  704: 	} else {
  705: 	    $load = $loadans;
  706: 	}
  707:     } else {
  708: 	$load = $userloadans;
  709:     }
  710: 
  711:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  712: 	$spare_server = $try_server;
  713: 	$lowest_load  = $load;
  714:     }
  715:     return ($spare_server,$lowest_load);
  716: }
  717: 
  718: # --------------------------- ask offload servers if user already has a session
  719: sub find_existing_session {
  720:     my ($udom,$uname) = @_;
  721:     foreach my $try_server (@{ $spareid{'primary'} },
  722: 			    @{ $spareid{'default'} }) {
  723: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  724:     }
  725:     return;
  726: }
  727: 
  728: # -------------------------------- ask if server already has a session for user
  729: sub has_user_session {
  730:     my ($lonid,$udom,$uname) = @_;
  731:     my $result = &reply(join(':','userhassession',
  732: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  733:     return 1 if ($result eq 'ok');
  734: 
  735:     return 0;
  736: }
  737: 
  738: # --------------------------------------------- Try to change a user's password
  739: 
  740: sub changepass {
  741:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  742:     $currentpass = &escape($currentpass);
  743:     $newpass     = &escape($newpass);
  744:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  745: 		       $server);
  746:     if (! $answer) {
  747: 	&logthis("No reply on password change request to $server ".
  748: 		 "by $uname in domain $udom.");
  749:     } elsif ($answer =~ "^ok") {
  750:         &logthis("$uname in $udom successfully changed their password ".
  751: 		 "on $server.");
  752:     } elsif ($answer =~ "^pwchange_failure") {
  753: 	&logthis("$uname in $udom was unable to change their password ".
  754: 		 "on $server.  The action was blocked by either lcpasswd ".
  755: 		 "or pwchange");
  756:     } elsif ($answer =~ "^non_authorized") {
  757:         &logthis("$uname in $udom did not get their password correct when ".
  758: 		 "attempting to change it on $server.");
  759:     } elsif ($answer =~ "^auth_mode_error") {
  760:         &logthis("$uname in $udom attempted to change their password despite ".
  761: 		 "not being locally or internally authenticated on $server.");
  762:     } elsif ($answer =~ "^unknown_user") {
  763:         &logthis("$uname in $udom attempted to change their password ".
  764: 		 "on $server but were unable to because $server is not ".
  765: 		 "their home server.");
  766:     } elsif ($answer =~ "^refused") {
  767: 	&logthis("$server refused to change $uname in $udom password because ".
  768: 		 "it was sent an unencrypted request to change the password.");
  769:     }
  770:     return $answer;
  771: }
  772: 
  773: # ----------------------- Try to determine user's current authentication scheme
  774: 
  775: sub queryauthenticate {
  776:     my ($uname,$udom)=@_;
  777:     my $uhome=&homeserver($uname,$udom);
  778:     if (!$uhome) {
  779: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  780: 	return 'no_host';
  781:     }
  782:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  783:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  784: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  785:     }
  786:     return $answer;
  787: }
  788: 
  789: # --------- Try to authenticate user from domain's lib servers (first this one)
  790: 
  791: sub authenticate {
  792:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  793:     $upass=&escape($upass);
  794:     $uname= &LONCAPA::clean_username($uname);
  795:     my $uhome=&homeserver($uname,$udom,1);
  796:     my $newhome;
  797:     if ((!$uhome) || ($uhome eq 'no_host')) {
  798: # Maybe the machine was offline and only re-appeared again recently?
  799:         &reconlonc();
  800: # One more
  801: 	$uhome=&homeserver($uname,$udom,1);
  802:         if (($uhome eq 'no_host') && $checkdefauth) {
  803:             if (defined(&domain($udom,'primary'))) {
  804:                 $newhome=&domain($udom,'primary');
  805:             }
  806:             if ($newhome ne '') {
  807:                 $uhome = $newhome;
  808:             }
  809:         }
  810: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  811: 	    &logthis("User $uname at $udom is unknown in authenticate");
  812: 	    return 'no_host';
  813:         }
  814:     }
  815:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  816:     if ($answer eq 'authorized') {
  817:         if ($newhome) {
  818:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  819:             return 'no_account_on_host'; 
  820:         } else {
  821:             &logthis("User $uname at $udom authorized by $uhome");
  822:             return $uhome;
  823:         }
  824:     }
  825:     if ($answer eq 'non_authorized') {
  826: 	&logthis("User $uname at $udom rejected by $uhome");
  827: 	return 'no_host'; 
  828:     }
  829:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  830:     return 'no_host';
  831: }
  832: 
  833: # ---------------------- Find the homebase for a user from domain's lib servers
  834: 
  835: my %homecache;
  836: sub homeserver {
  837:     my ($uname,$udom,$ignoreBadCache)=@_;
  838:     my $index="$uname:$udom";
  839: 
  840:     if (exists($homecache{$index})) { return $homecache{$index}; }
  841: 
  842:     my %servers = &get_servers($udom,'library');
  843:     foreach my $tryserver (keys(%servers)) {
  844:         next if ($ignoreBadCache ne 'true' && 
  845: 		 exists($badServerCache{$tryserver}));
  846: 
  847: 	my $answer=reply("home:$udom:$uname",$tryserver);
  848: 	if ($answer eq 'found') {
  849: 	    delete($badServerCache{$tryserver}); 
  850: 	    return $homecache{$index}=$tryserver;
  851: 	} elsif ($answer eq 'no_host') {
  852: 	    $badServerCache{$tryserver}=1;
  853: 	}
  854:     }    
  855:     return 'no_host';
  856: }
  857: 
  858: # ------------------------------------- Find the usernames behind a list of IDs
  859: 
  860: sub idget {
  861:     my ($udom,@ids)=@_;
  862:     my %returnhash=();
  863:     
  864:     my %servers = &get_servers($udom,'library');
  865:     foreach my $tryserver (keys(%servers)) {
  866: 	my $idlist=join('&',@ids);
  867: 	$idlist=~tr/A-Z/a-z/; 
  868: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  869: 	my @answer=();
  870: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  871: 	    @answer=split(/\&/,$reply);
  872: 	}                    ;
  873: 	my $i;
  874: 	for ($i=0;$i<=$#ids;$i++) {
  875: 	    if ($answer[$i]) {
  876: 		$returnhash{$ids[$i]}=$answer[$i];
  877: 	    } 
  878: 	}
  879:     } 
  880:     return %returnhash;
  881: }
  882: 
  883: # ------------------------------------- Find the IDs behind a list of usernames
  884: 
  885: sub idrget {
  886:     my ($udom,@unames)=@_;
  887:     my %returnhash=();
  888:     foreach my $uname (@unames) {
  889:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  890:     }
  891:     return %returnhash;
  892: }
  893: 
  894: # ------------------------------- Store away a list of names and associated IDs
  895: 
  896: sub idput {
  897:     my ($udom,%ids)=@_;
  898:     my %servers=();
  899:     foreach my $uname (keys(%ids)) {
  900: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  901:         my $uhom=&homeserver($uname,$udom);
  902:         if ($uhom ne 'no_host') {
  903:             my $id=&escape($ids{$uname});
  904:             $id=~tr/A-Z/a-z/;
  905:             my $esc_unam=&escape($uname);
  906: 	    if ($servers{$uhom}) {
  907: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  908:             } else {
  909:                 $servers{$uhom}=$id.'='.$esc_unam;
  910:             }
  911:         }
  912:     }
  913:     foreach my $server (keys(%servers)) {
  914:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  915:     }
  916: }
  917: 
  918: # ------------------------------------------- get items from domain db files   
  919: 
  920: sub get_dom {
  921:     my ($namespace,$storearr,$udom,$uhome)=@_;
  922:     my $items='';
  923:     foreach my $item (@$storearr) {
  924:         $items.=&escape($item).'&';
  925:     }
  926:     $items=~s/\&$//;
  927:     if (!$udom) {
  928:         $udom=$env{'user.domain'};
  929:         if (defined(&domain($udom,'primary'))) {
  930:             $uhome=&domain($udom,'primary');
  931:         } else {
  932:             undef($uhome);
  933:         }
  934:     } else {
  935:         if (!$uhome) {
  936:             if (defined(&domain($udom,'primary'))) {
  937:                 $uhome=&domain($udom,'primary');
  938:             }
  939:         }
  940:     }
  941:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  942:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  943:         my %returnhash;
  944:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  945:             return %returnhash;
  946:         }
  947:         my @pairs=split(/\&/,$rep);
  948:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  949:             return @pairs;
  950:         }
  951:         my $i=0;
  952:         foreach my $item (@$storearr) {
  953:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  954:             $i++;
  955:         }
  956:         return %returnhash;
  957:     } else {
  958:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  959:     }
  960: }
  961: 
  962: # -------------------------------------------- put items in domain db files 
  963: 
  964: sub put_dom {
  965:     my ($namespace,$storehash,$udom,$uhome)=@_;
  966:     if (!$udom) {
  967:         $udom=$env{'user.domain'};
  968:         if (defined(&domain($udom,'primary'))) {
  969:             $uhome=&domain($udom,'primary');
  970:         } else {
  971:             undef($uhome);
  972:         }
  973:     } else {
  974:         if (!$uhome) {
  975:             if (defined(&domain($udom,'primary'))) {
  976:                 $uhome=&domain($udom,'primary');
  977:             }
  978:         }
  979:     } 
  980:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  981:         my $items='';
  982:         foreach my $item (keys(%$storehash)) {
  983:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  984:         }
  985:         $items=~s/\&$//;
  986:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  987:     } else {
  988:         &logthis("put_dom failed - no homeserver and/or domain");
  989:     }
  990: }
  991: 
  992: sub retrieve_inst_usertypes {
  993:     my ($udom) = @_;
  994:     my (%returnhash,@order);
  995:     if (defined(&domain($udom,'primary'))) {
  996:         my $uhome=&domain($udom,'primary');
  997:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  998:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
  999:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1000:             return (\%returnhash,\@order);
 1001:         }
 1002:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1003:         my @pairs=split(/\&/,$hashitems);
 1004:         foreach my $item (@pairs) {
 1005:             my ($key,$value)=split(/=/,$item,2);
 1006:             $key = &unescape($key);
 1007:             next if ($key =~ /^error: 2 /);
 1008:             $returnhash{$key}=&thaw_unescape($value);
 1009:         }
 1010:         my @esc_order = split(/\&/,$orderitems);
 1011:         foreach my $item (@esc_order) {
 1012:             push(@order,&unescape($item));
 1013:         }
 1014:     } else {
 1015:         &logthis("get_dom failed - no primary domain server for $udom");
 1016:     }
 1017:     return (\%returnhash,\@order);
 1018: }
 1019: 
 1020: sub is_domainimage {
 1021:     my ($url) = @_;
 1022:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1023:         if (&domain($1) ne '') {
 1024:             return '1';
 1025:         }
 1026:     }
 1027:     return;
 1028: }
 1029: 
 1030: sub inst_directory_query {
 1031:     my ($srch) = @_;
 1032:     my $udom = $srch->{'srchdomain'};
 1033:     my %results;
 1034:     my $homeserver = &domain($udom,'primary');
 1035:     my $outcome;
 1036:     if ($homeserver ne '') {
 1037: 	my $queryid=&reply("querysend:instdirsearch:".
 1038: 			   &escape($srch->{'srchby'}).':'.
 1039: 			   &escape($srch->{'srchterm'}).':'.
 1040: 			   &escape($srch->{'srchtype'}),$homeserver);
 1041: 	my $host=&hostname($homeserver);
 1042: 	if ($queryid !~/^\Q$host\E\_/) {
 1043: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1044: 	    return;
 1045: 	}
 1046: 	my $response = &get_query_reply($queryid);
 1047: 	my $maxtries = 5;
 1048: 	my $tries = 1;
 1049: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1050: 	    $response = &get_query_reply($queryid);
 1051: 	    $tries ++;
 1052: 	}
 1053: 
 1054:         if (!&error($response) && $response ne 'refused') {
 1055:             if ($response eq 'unavailable') {
 1056:                 $outcome = $response;
 1057:             } else {
 1058:                 $outcome = 'ok';
 1059:                 my @matches = split(/\n/,$response);
 1060:                 foreach my $match (@matches) {
 1061:                     my ($key,$value) = split(/=/,$match);
 1062:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1063:                 }
 1064:             }
 1065:         }
 1066:     }
 1067:     return ($outcome,%results);
 1068: }
 1069: 
 1070: sub usersearch {
 1071:     my ($srch) = @_;
 1072:     my $dom = $srch->{'srchdomain'};
 1073:     my %results;
 1074:     my %libserv = &all_library();
 1075:     my $query = 'usersearch';
 1076:     foreach my $tryserver (keys(%libserv)) {
 1077:         if (&host_domain($tryserver) eq $dom) {
 1078:             my $host=&hostname($tryserver);
 1079:             my $queryid=
 1080:                 &reply("querysend:".&escape($query).':'.
 1081:                        &escape($srch->{'srchby'}).':'.
 1082:                        &escape($srch->{'srchtype'}).':'.
 1083:                        &escape($srch->{'srchterm'}),$tryserver);
 1084:             if ($queryid !~/^\Q$host\E\_/) {
 1085:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1086:                 next;
 1087:             }
 1088:             my $reply = &get_query_reply($queryid);
 1089:             my $maxtries = 1;
 1090:             my $tries = 1;
 1091:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1092:                 $reply = &get_query_reply($queryid);
 1093:                 $tries ++;
 1094:             }
 1095:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1096:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1097:             } else {
 1098:                 my @matches;
 1099:                 if ($reply =~ /\n/) {
 1100:                     @matches = split(/\n/,$reply);
 1101:                 } else {
 1102:                     @matches = split(/\&/,$reply);
 1103:                 }
 1104:                 foreach my $match (@matches) {
 1105:                     my ($uname,$udom,%userhash);
 1106:                     foreach my $entry (split(/:/,$match)) {
 1107:                         my ($key,$value) =
 1108:                             map {&unescape($_);} split(/=/,$entry);
 1109:                         $userhash{$key} = $value;
 1110:                         if ($key eq 'username') {
 1111:                             $uname = $value;
 1112:                         } elsif ($key eq 'domain') {
 1113:                             $udom = $value;
 1114:                         }
 1115:                     }
 1116:                     $results{$uname.':'.$udom} = \%userhash;
 1117:                 }
 1118:             }
 1119:         }
 1120:     }
 1121:     return %results;
 1122: }
 1123: 
 1124: sub get_instuser {
 1125:     my ($udom,$uname,$id) = @_;
 1126:     my $homeserver = &domain($udom,'primary');
 1127:     my ($outcome,%results);
 1128:     if ($homeserver ne '') {
 1129:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1130:                            &escape($id).':'.&escape($udom),$homeserver);
 1131:         my $host=&hostname($homeserver);
 1132:         if ($queryid !~/^\Q$host\E\_/) {
 1133:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1134:             return;
 1135:         }
 1136:         my $response = &get_query_reply($queryid);
 1137:         my $maxtries = 5;
 1138:         my $tries = 1;
 1139:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1140:             $response = &get_query_reply($queryid);
 1141:             $tries ++;
 1142:         }
 1143:         if (!&error($response) && $response ne 'refused') {
 1144:             if ($response eq 'unavailable') {
 1145:                 $outcome = $response;
 1146:             } else {
 1147:                 $outcome = 'ok';
 1148:                 my @matches = split(/\n/,$response);
 1149:                 foreach my $match (@matches) {
 1150:                     my ($key,$value) = split(/=/,$match);
 1151:                     $results{&unescape($key)} = &thaw_unescape($value);
 1152:                 }
 1153:             }
 1154:         }
 1155:     }
 1156:     my %userinfo;
 1157:     if (ref($results{$uname}) eq 'HASH') {
 1158:         %userinfo = %{$results{$uname}};
 1159:     } 
 1160:     return ($outcome,%userinfo);
 1161: }
 1162: 
 1163: sub inst_rulecheck {
 1164:     my ($udom,$uname,$id,$item,$rules) = @_;
 1165:     my %returnhash;
 1166:     if ($udom ne '') {
 1167:         if (ref($rules) eq 'ARRAY') {
 1168:             @{$rules} = map {&escape($_);} (@{$rules});
 1169:             my $rulestr = join(':',@{$rules});
 1170:             my $homeserver=&domain($udom,'primary');
 1171:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1172:                 my $response;
 1173:                 if ($item eq 'username') {                
 1174:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1175:                                               ':'.&escape($uname).':'.$rulestr,
 1176:                                               $homeserver));
 1177:                 } elsif ($item eq 'id') {
 1178:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1179:                                               ':'.&escape($id).':'.$rulestr,
 1180:                                               $homeserver));
 1181:                 } elsif ($item eq 'selfcreate') {
 1182:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1183:                                                &escape($udom).':'.&escape($uname).
 1184:                                               ':'.$rulestr,$homeserver));
 1185:                 }
 1186:                 if ($response ne 'refused') {
 1187:                     my @pairs=split(/\&/,$response);
 1188:                     foreach my $item (@pairs) {
 1189:                         my ($key,$value)=split(/=/,$item,2);
 1190:                         $key = &unescape($key);
 1191:                         next if ($key =~ /^error: 2 /);
 1192:                         $returnhash{$key}=&thaw_unescape($value);
 1193:                     }
 1194:                 }
 1195:             }
 1196:         }
 1197:     }
 1198:     return %returnhash;
 1199: }
 1200: 
 1201: sub inst_userrules {
 1202:     my ($udom,$check) = @_;
 1203:     my (%ruleshash,@ruleorder);
 1204:     if ($udom ne '') {
 1205:         my $homeserver=&domain($udom,'primary');
 1206:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1207:             my $response;
 1208:             if ($check eq 'id') {
 1209:                 $response=&reply('instidrules:'.&escape($udom),
 1210:                                  $homeserver);
 1211:             } elsif ($check eq 'email') {
 1212:                 $response=&reply('instemailrules:'.&escape($udom),
 1213:                                  $homeserver);
 1214:             } else {
 1215:                 $response=&reply('instuserrules:'.&escape($udom),
 1216:                                  $homeserver);
 1217:             }
 1218:             if (($response ne 'refused') && ($response ne 'error') && 
 1219:                 ($response ne 'unknown_cmd') && 
 1220:                 ($response ne 'no_such_host')) {
 1221:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1222:                 my @pairs=split(/\&/,$hashitems);
 1223:                 foreach my $item (@pairs) {
 1224:                     my ($key,$value)=split(/=/,$item,2);
 1225:                     $key = &unescape($key);
 1226:                     next if ($key =~ /^error: 2 /);
 1227:                     $ruleshash{$key}=&thaw_unescape($value);
 1228:                 }
 1229:                 my @esc_order = split(/\&/,$orderitems);
 1230:                 foreach my $item (@esc_order) {
 1231:                     push(@ruleorder,&unescape($item));
 1232:                 }
 1233:             }
 1234:         }
 1235:     }
 1236:     return (\%ruleshash,\@ruleorder);
 1237: }
 1238: 
 1239: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1240: 
 1241: sub get_domain_defaults {
 1242:     my ($domain) = @_;
 1243:     my $cachetime = 60*60*24;
 1244:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1245:     if (defined($cached)) {
 1246:         if (ref($result) eq 'HASH') {
 1247:             return %{$result};
 1248:         }
 1249:     }
 1250:     my %domdefaults;
 1251:     my %domconfig =
 1252:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1253:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1254:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1255:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1256:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1257:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1258:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1259:     } else {
 1260:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1261:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1262:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1263:     }
 1264:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1265:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1266:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1267:         } else {
 1268:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1269:         } 
 1270:         my @usertools = ('aboutme','blog','portfolio');
 1271:         foreach my $item (@usertools) {
 1272:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1273:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1274:             }
 1275:         }
 1276:     }
 1277:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1278:                                   $cachetime);
 1279:     return %domdefaults;
 1280: }
 1281: 
 1282: # --------------------------------------------------- Assign a key to a student
 1283: 
 1284: sub assign_access_key {
 1285: #
 1286: # a valid key looks like uname:udom#comments
 1287: # comments are being appended
 1288: #
 1289:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1290:     $kdom=
 1291:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1292:     $knum=
 1293:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1294:     $cdom=
 1295:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1296:     $cnum=
 1297:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1298:     $udom=$env{'user.name'} unless (defined($udom));
 1299:     $uname=$env{'user.domain'} unless (defined($uname));
 1300:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1301:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1302:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1303:                                                   # assigned to this person
 1304:                                                   # - this should not happen,
 1305:                                                   # unless something went wrong
 1306:                                                   # the first time around
 1307: # ready to assign
 1308:         $logentry=$1.'; '.$logentry;
 1309:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1310:                                                  $kdom,$knum) eq 'ok') {
 1311: # key now belongs to user
 1312: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1313:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1314:                 &appenv({'environment.'.$envkey => $ckey});
 1315:                 return 'ok';
 1316:             } else {
 1317:                 return 
 1318:   'error: Count not permanently assign key, will need to be re-entered later.';
 1319: 	    }
 1320:         } else {
 1321:             return 'error: Could not assign key, try again later.';
 1322:         }
 1323:     } elsif (!$existing{$ckey}) {
 1324: # the key does not exist
 1325: 	return 'error: The key does not exist';
 1326:     } else {
 1327: # the key is somebody else's
 1328: 	return 'error: The key is already in use';
 1329:     }
 1330: }
 1331: 
 1332: # ------------------------------------------ put an additional comment on a key
 1333: 
 1334: sub comment_access_key {
 1335: #
 1336: # a valid key looks like uname:udom#comments
 1337: # comments are being appended
 1338: #
 1339:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1340:     $cdom=
 1341:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1342:     $cnum=
 1343:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1344:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1345:     if ($existing{$ckey}) {
 1346:         $existing{$ckey}.='; '.$logentry;
 1347: # ready to assign
 1348:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1349:                                                  $cdom,$cnum) eq 'ok') {
 1350: 	    return 'ok';
 1351:         } else {
 1352: 	    return 'error: Count not store comment.';
 1353:         }
 1354:     } else {
 1355: # the key does not exist
 1356: 	return 'error: The key does not exist';
 1357:     }
 1358: }
 1359: 
 1360: # ------------------------------------------------------ Generate a set of keys
 1361: 
 1362: sub generate_access_keys {
 1363:     my ($number,$cdom,$cnum,$logentry)=@_;
 1364:     $cdom=
 1365:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1366:     $cnum=
 1367:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1368:     unless (&allowed('mky',$cdom)) { return 0; }
 1369:     unless (($cdom) && ($cnum)) { return 0; }
 1370:     if ($number>10000) { return 0; }
 1371:     sleep(2); # make sure don't get same seed twice
 1372:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1373:     my $total=0;
 1374:     for (my $i=1;$i<=$number;$i++) {
 1375:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1376:                   sprintf("%lx",int(100000*rand)).'-'.
 1377:                   sprintf("%lx",int(100000*rand));
 1378:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1379:        $newkey=~s/0/h/g; # and also 0 and O
 1380:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1381:        if ($existing{$newkey}) {
 1382:            $i--;
 1383:        } else {
 1384: 	  if (&put('accesskeys',
 1385:               { $newkey => '# generated '.localtime().
 1386:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1387:                            '; '.$logentry },
 1388: 		   $cdom,$cnum) eq 'ok') {
 1389:               $total++;
 1390: 	  }
 1391:        }
 1392:     }
 1393:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1394:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1395:     return $total;
 1396: }
 1397: 
 1398: # ------------------------------------------------------- Validate an accesskey
 1399: 
 1400: sub validate_access_key {
 1401:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1402:     $cdom=
 1403:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1404:     $cnum=
 1405:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1406:     $udom=$env{'user.domain'} unless (defined($udom));
 1407:     $uname=$env{'user.name'} unless (defined($uname));
 1408:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1409:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1410: }
 1411: 
 1412: # ------------------------------------- Find the section of student in a course
 1413: sub devalidate_getsection_cache {
 1414:     my ($udom,$unam,$courseid)=@_;
 1415:     my $hashid="$udom:$unam:$courseid";
 1416:     &devalidate_cache_new('getsection',$hashid);
 1417: }
 1418: 
 1419: sub courseid_to_courseurl {
 1420:     my ($courseid) = @_;
 1421:     #already url style courseid
 1422:     return $courseid if ($courseid =~ m{^/});
 1423: 
 1424:     if (exists($env{'course.'.$courseid.'.num'})) {
 1425: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1426: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1427: 	return "/$cdom/$cnum";
 1428:     }
 1429: 
 1430:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1431:     if (exists($courseinfo{'num'})) {
 1432: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1433:     }
 1434: 
 1435:     return undef;
 1436: }
 1437: 
 1438: sub getsection {
 1439:     my ($udom,$unam,$courseid)=@_;
 1440:     my $cachetime=1800;
 1441: 
 1442:     my $hashid="$udom:$unam:$courseid";
 1443:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1444:     if (defined($cached)) { return $result; }
 1445: 
 1446:     my %Pending; 
 1447:     my %Expired;
 1448:     #
 1449:     # Each role can either have not started yet (pending), be active, 
 1450:     #    or have expired.
 1451:     #
 1452:     # If there is an active role, we are done.
 1453:     #
 1454:     # If there is more than one role which has not started yet, 
 1455:     #     choose the one which will start sooner
 1456:     # If there is one role which has not started yet, return it.
 1457:     #
 1458:     # If there is more than one expired role, choose the one which ended last.
 1459:     # If there is a role which has expired, return it.
 1460:     #
 1461:     $courseid = &courseid_to_courseurl($courseid);
 1462:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1463:     foreach my $key (keys(%roleshash)) {
 1464:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1465:         my $section=$1;
 1466:         if ($key eq $courseid.'_st') { $section=''; }
 1467:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1468:         my $now=time;
 1469:         if (defined($end) && $end && ($now > $end)) {
 1470:             $Expired{$end}=$section;
 1471:             next;
 1472:         }
 1473:         if (defined($start) && $start && ($now < $start)) {
 1474:             $Pending{$start}=$section;
 1475:             next;
 1476:         }
 1477:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1478:     }
 1479:     #
 1480:     # Presumedly there will be few matching roles from the above
 1481:     # loop and the sorting time will be negligible.
 1482:     if (scalar(keys(%Pending))) {
 1483:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1484:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1485:     } 
 1486:     if (scalar(keys(%Expired))) {
 1487:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1488:         my $time = pop(@sorted);
 1489:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1490:     }
 1491:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1492: }
 1493: 
 1494: sub save_cache {
 1495:     &purge_remembered();
 1496:     #&Apache::loncommon::validate_page();
 1497:     undef(%env);
 1498:     undef($env_loaded);
 1499: }
 1500: 
 1501: my $to_remember=-1;
 1502: my %remembered;
 1503: my %accessed;
 1504: my $kicks=0;
 1505: my $hits=0;
 1506: sub make_key {
 1507:     my ($name,$id) = @_;
 1508:     if (length($id) > 65 
 1509: 	&& length(&escape($id)) > 200) {
 1510: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1511:     }
 1512:     return &escape($name.':'.$id);
 1513: }
 1514: 
 1515: sub devalidate_cache_new {
 1516:     my ($name,$id,$debug) = @_;
 1517:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1518:     $id=&make_key($name,$id);
 1519:     $memcache->delete($id);
 1520:     delete($remembered{$id});
 1521:     delete($accessed{$id});
 1522: }
 1523: 
 1524: sub is_cached_new {
 1525:     my ($name,$id,$debug) = @_;
 1526:     $id=&make_key($name,$id);
 1527:     if (exists($remembered{$id})) {
 1528: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1529: 	$accessed{$id}=[&gettimeofday()];
 1530: 	$hits++;
 1531: 	return ($remembered{$id},1);
 1532:     }
 1533:     my $value = $memcache->get($id);
 1534:     if (!(defined($value))) {
 1535: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1536: 	return (undef,undef);
 1537:     }
 1538:     if ($value eq '__undef__') {
 1539: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1540: 	$value=undef;
 1541:     }
 1542:     &make_room($id,$value,$debug);
 1543:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1544:     return ($value,1);
 1545: }
 1546: 
 1547: sub do_cache_new {
 1548:     my ($name,$id,$value,$time,$debug) = @_;
 1549:     $id=&make_key($name,$id);
 1550:     my $setvalue=$value;
 1551:     if (!defined($setvalue)) {
 1552: 	$setvalue='__undef__';
 1553:     }
 1554:     if (!defined($time) ) {
 1555: 	$time=600;
 1556:     }
 1557:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1558:     my $result = $memcache->set($id,$setvalue,$time);
 1559:     if (! $result) {
 1560: 	&logthis("caching of id -> $id  failed");
 1561: 	$memcache->disconnect_all();
 1562:     }
 1563:     # need to make a copy of $value
 1564:     &make_room($id,$value,$debug);
 1565:     return $value;
 1566: }
 1567: 
 1568: sub make_room {
 1569:     my ($id,$value,$debug)=@_;
 1570: 
 1571:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1572:                                     : $value;
 1573:     if ($to_remember<0) { return; }
 1574:     $accessed{$id}=[&gettimeofday()];
 1575:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1576:     my $to_kick;
 1577:     my $max_time=0;
 1578:     foreach my $other (keys(%accessed)) {
 1579: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1580: 	    $to_kick=$other;
 1581: 	    $max_time=&tv_interval($accessed{$other});
 1582: 	}
 1583:     }
 1584:     delete($remembered{$to_kick});
 1585:     delete($accessed{$to_kick});
 1586:     $kicks++;
 1587:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1588:     return;
 1589: }
 1590: 
 1591: sub purge_remembered {
 1592:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1593:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1594:     undef(%remembered);
 1595:     undef(%accessed);
 1596: }
 1597: # ------------------------------------- Read an entry from a user's environment
 1598: 
 1599: sub userenvironment {
 1600:     my ($udom,$unam,@what)=@_;
 1601:     my $items;
 1602:     foreach my $item (@what) {
 1603:         $items.=&escape($item).'&';
 1604:     }
 1605:     $items=~s/\&$//;
 1606:     my %returnhash=();
 1607:     my @answer=split(/\&/,
 1608:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1609:                       &homeserver($unam,$udom)));
 1610:     my $i;
 1611:     for ($i=0;$i<=$#what;$i++) {
 1612: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1613:     }
 1614:     return %returnhash;
 1615: }
 1616: 
 1617: # ---------------------------------------------------------- Get a studentphoto
 1618: sub studentphoto {
 1619:     my ($udom,$unam,$ext) = @_;
 1620:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1621:     if (defined($env{'request.course.id'})) {
 1622:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1623:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1624:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1625:             } else {
 1626:                 my ($result,$perm_reqd)=
 1627: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1628:                 if ($result eq 'ok') {
 1629:                     if (!($perm_reqd eq 'yes')) {
 1630:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1631:                     }
 1632:                 }
 1633:             }
 1634:         }
 1635:     } else {
 1636:         my ($result,$perm_reqd) = 
 1637: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1638:         if ($result eq 'ok') {
 1639:             if (!($perm_reqd eq 'yes')) {
 1640:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1641:             }
 1642:         }
 1643:     }
 1644:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1645: }
 1646: 
 1647: sub retrievestudentphoto {
 1648:     my ($udom,$unam,$ext,$type) = @_;
 1649:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1650:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1651:     if ($ret eq 'ok') {
 1652:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1653:         if ($type eq 'thumbnail') {
 1654:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1655:         }
 1656:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1657:         return $tokenurl;
 1658:     } else {
 1659:         if ($type eq 'thumbnail') {
 1660:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1661:         } else { 
 1662:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1663:         }
 1664:     }
 1665: }
 1666: 
 1667: # -------------------------------------------------------------------- New chat
 1668: 
 1669: sub chatsend {
 1670:     my ($newentry,$anon,$group)=@_;
 1671:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1672:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1673:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1674:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1675: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1676: 		   &escape($newentry)).':'.$group,$chome);
 1677: }
 1678: 
 1679: # ------------------------------------------ Find current version of a resource
 1680: 
 1681: sub getversion {
 1682:     my $fname=&clutter(shift);
 1683:     unless ($fname=~/^\/res\//) { return -1; }
 1684:     return &currentversion(&filelocation('',$fname));
 1685: }
 1686: 
 1687: sub currentversion {
 1688:     my $fname=shift;
 1689:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1690:     if (defined($cached)) { return $result; }
 1691:     my $author=$fname;
 1692:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1693:     my ($udom,$uname)=split(/\//,$author);
 1694:     my $home=homeserver($uname,$udom);
 1695:     if ($home eq 'no_host') { 
 1696:         return -1; 
 1697:     }
 1698:     my $answer=reply("currentversion:$fname",$home);
 1699:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1700: 	return -1;
 1701:     }
 1702:     return &do_cache_new('resversion',$fname,$answer,600);
 1703: }
 1704: 
 1705: # ----------------------------- Subscribe to a resource, return URL if possible
 1706: 
 1707: sub subscribe {
 1708:     my $fname=shift;
 1709:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1710:     $fname=~s/[\n\r]//g;
 1711:     my $author=$fname;
 1712:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1713:     my ($udom,$uname)=split(/\//,$author);
 1714:     my $home=homeserver($uname,$udom);
 1715:     if ($home eq 'no_host') {
 1716:         return 'not_found';
 1717:     }
 1718:     my $answer=reply("sub:$fname",$home);
 1719:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1720: 	$answer.=' by '.$home;
 1721:     }
 1722:     return $answer;
 1723: }
 1724:     
 1725: # -------------------------------------------------------------- Replicate file
 1726: 
 1727: sub repcopy {
 1728:     my $filename=shift;
 1729:     $filename=~s/\/+/\//g;
 1730:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1731:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1732:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1733: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1734: 	return &repcopy_userfile($filename);
 1735:     }
 1736:     $filename=~s/[\n\r]//g;
 1737:     my $transname="$filename.in.transfer";
 1738: # FIXME: this should flock
 1739:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1740:     my $remoteurl=subscribe($filename);
 1741:     if ($remoteurl =~ /^con_lost by/) {
 1742: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1743:            return 'unavailable';
 1744:     } elsif ($remoteurl eq 'not_found') {
 1745: 	   #&logthis("Subscribe returned not_found: $filename");
 1746: 	   return 'not_found';
 1747:     } elsif ($remoteurl =~ /^rejected by/) {
 1748: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1749:            return 'forbidden';
 1750:     } elsif ($remoteurl eq 'directory') {
 1751:            return 'ok';
 1752:     } else {
 1753:         my $author=$filename;
 1754:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1755:         my ($udom,$uname)=split(/\//,$author);
 1756:         my $home=homeserver($uname,$udom);
 1757:         unless ($home eq $perlvar{'lonHostID'}) {
 1758:            my @parts=split(/\//,$filename);
 1759:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1760:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1761:                &logthis("Malconfiguration for replication: $filename");
 1762: 	       return 'bad_request';
 1763:            }
 1764:            my $count;
 1765:            for ($count=5;$count<$#parts;$count++) {
 1766:                $path.="/$parts[$count]";
 1767:                if ((-e $path)!=1) {
 1768: 		   mkdir($path,0777);
 1769:                }
 1770:            }
 1771:            my $ua=new LWP::UserAgent;
 1772:            my $request=new HTTP::Request('GET',"$remoteurl");
 1773:            my $response=$ua->request($request,$transname);
 1774:            if ($response->is_error()) {
 1775: 	       unlink($transname);
 1776:                my $message=$response->status_line;
 1777:                &logthis("<font color=\"blue\">WARNING:"
 1778:                        ." LWP get: $message: $filename</font>");
 1779:                return 'unavailable';
 1780:            } else {
 1781: 	       if ($remoteurl!~/\.meta$/) {
 1782:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1783:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1784:                   if ($mresponse->is_error()) {
 1785: 		      unlink($filename.'.meta');
 1786:                       &logthis(
 1787:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1788:                   }
 1789: 	       }
 1790:                rename($transname,$filename);
 1791:                return 'ok';
 1792:            }
 1793:        }
 1794:     }
 1795: }
 1796: 
 1797: # ------------------------------------------------ Get server side include body
 1798: sub ssi_body {
 1799:     my ($filelink,%form)=@_;
 1800:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1801:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1802:     }
 1803:     my $output='';
 1804:     my $response;
 1805:     if ($filelink=~/^https?\:/) {
 1806:        ($output,$response)=&externalssi($filelink);
 1807:     } else {
 1808:        ($output,$response)=&ssi($filelink,%form);
 1809:     }
 1810:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1811:     $output=~s/^.*?\<body[^\>]*\>//si;
 1812:     $output=~s/\<\/body\s*\>.*?$//si;
 1813:     if (wantarray) {
 1814:         return ($output, $response);
 1815:     } else {
 1816:         return $output;
 1817:     }
 1818: }
 1819: 
 1820: # --------------------------------------------------------- Server Side Include
 1821: 
 1822: sub absolute_url {
 1823:     my ($host_name) = @_;
 1824:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1825:     if ($host_name eq '') {
 1826: 	$host_name = $ENV{'SERVER_NAME'};
 1827:     }
 1828:     return $protocol.$host_name;
 1829: }
 1830: 
 1831: #
 1832: #   Server side include.
 1833: # Parameters:
 1834: #  fn     Possibly encrypted resource name/id.
 1835: #  form   Hash that describes how the rendering should be done
 1836: #         and other things.
 1837: # Returns:
 1838: #   Scalar context: The content of the response.
 1839: #   Array context:  2 element list of the content and the full response object.
 1840: #     
 1841: sub ssi {
 1842: 
 1843:     my ($fn,%form)=@_;
 1844:     my $ua=new LWP::UserAgent;
 1845:     my $request;
 1846: 
 1847:     $form{'no_update_last_known'}=1;
 1848:     &Apache::lonenc::check_encrypt(\$fn);
 1849:     if (%form) {
 1850:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1851:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1852:     } else {
 1853:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1854:     }
 1855: 
 1856:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1857:     my $response=$ua->request($request);
 1858: 
 1859:     if (wantarray) {
 1860: 	return ($response->content, $response);
 1861:     } else {
 1862: 	return $response->content;
 1863:     }
 1864: }
 1865: 
 1866: sub externalssi {
 1867:     my ($url)=@_;
 1868:     my $ua=new LWP::UserAgent;
 1869:     my $request=new HTTP::Request('GET',$url);
 1870:     my $response=$ua->request($request);
 1871:     if (wantarray) {
 1872:         return ($response->content, $response);
 1873:     } else {
 1874:         return $response->content;
 1875:     }
 1876: }
 1877: 
 1878: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1879: 
 1880: sub allowuploaded {
 1881:     my ($srcurl,$url)=@_;
 1882:     $url=&clutter(&declutter($url));
 1883:     my $dir=$url;
 1884:     $dir=~s/\/[^\/]+$//;
 1885:     my %httpref=();
 1886:     my $httpurl=&hreflocation('',$url);
 1887:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1888:     &Apache::lonnet::appenv(\%httpref);
 1889: }
 1890: 
 1891: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1892: # input: action, courseID, current domain, intended
 1893: #        path to file, source of file, instruction to parse file for objects,
 1894: #        ref to hash for embedded objects,
 1895: #        ref to hash for codebase of java objects.
 1896: #
 1897: # output: url to file (if action was uploaddoc), 
 1898: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1899: #
 1900: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1901: # course.
 1902: #
 1903: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1904: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1905: #          course's home server.
 1906: #
 1907: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1908: #          be copied from $source (current location) to 
 1909: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1910: #         and will then be copied to
 1911: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1912: #         course's home server.
 1913: #
 1914: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1915: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1916: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1917: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1918: #         in course's home server.
 1919: #
 1920: 
 1921: sub process_coursefile {
 1922:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1923:     my $fetchresult;
 1924:     my $home=&homeserver($docuname,$docudom);
 1925:     if ($action eq 'propagate') {
 1926:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1927: 			     $home);
 1928:     } else {
 1929:         my $fpath = '';
 1930:         my $fname = $file;
 1931:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1932:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1933:         my $filepath = &build_filepath($fpath);
 1934:         if ($action eq 'copy') {
 1935:             if ($source eq '') {
 1936:                 $fetchresult = 'no source file';
 1937:                 return $fetchresult;
 1938:             } else {
 1939:                 my $destination = $filepath.'/'.$fname;
 1940:                 rename($source,$destination);
 1941:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1942:                                  $home);
 1943:             }
 1944:         } elsif ($action eq 'uploaddoc') {
 1945:             open(my $fh,'>'.$filepath.'/'.$fname);
 1946:             print $fh $env{'form.'.$source};
 1947:             close($fh);
 1948:             if ($parser eq 'parse') {
 1949:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1950:                 unless ($parse_result eq 'ok') {
 1951:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1952:                 }
 1953:             }
 1954:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1955:                                  $home);
 1956:             if ($fetchresult eq 'ok') {
 1957:                 return '/uploaded/'.$fpath.'/'.$fname;
 1958:             } else {
 1959:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1960:                         ' to host '.$home.': '.$fetchresult);
 1961:                 return '/adm/notfound.html';
 1962:             }
 1963:         }
 1964:     }
 1965:     unless ( $fetchresult eq 'ok') {
 1966:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1967:              ' to host '.$home.': '.$fetchresult);
 1968:     }
 1969:     return $fetchresult;
 1970: }
 1971: 
 1972: sub build_filepath {
 1973:     my ($fpath) = @_;
 1974:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1975:     unless ($fpath eq '') {
 1976:         my @parts=split('/',$fpath);
 1977:         foreach my $part (@parts) {
 1978:             $filepath.= '/'.$part;
 1979:             if ((-e $filepath)!=1) {
 1980:                 mkdir($filepath,0777);
 1981:             }
 1982:         }
 1983:     }
 1984:     return $filepath;
 1985: }
 1986: 
 1987: sub store_edited_file {
 1988:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1989:     my $file = $primary_url;
 1990:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1991:     my $fpath = '';
 1992:     my $fname = $file;
 1993:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1994:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1995:     my $filepath = &build_filepath($fpath);
 1996:     open(my $fh,'>'.$filepath.'/'.$fname);
 1997:     print $fh $content;
 1998:     close($fh);
 1999:     my $home=&homeserver($docuname,$docudom);
 2000:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2001: 			  $home);
 2002:     if ($$fetchresult eq 'ok') {
 2003:         return '/uploaded/'.$fpath.'/'.$fname;
 2004:     } else {
 2005:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2006: 		 ' to host '.$home.': '.$$fetchresult);
 2007:         return '/adm/notfound.html';
 2008:     }
 2009: }
 2010: 
 2011: sub clean_filename {
 2012:     my ($fname,$args)=@_;
 2013: # Replace Windows backslashes by forward slashes
 2014:     $fname=~s/\\/\//g;
 2015:     if (!$args->{'keep_path'}) {
 2016:         # Get rid of everything but the actual filename
 2017: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2018:     }
 2019: # Replace spaces by underscores
 2020:     $fname=~s/\s+/\_/g;
 2021: # Replace all other weird characters by nothing
 2022:     $fname=~s{[^/\w\.\-]}{}g;
 2023: # Replace all .\d. sequences with _\d. so they no longer look like version
 2024: # numbers
 2025:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2026:     return $fname;
 2027: }
 2028: 
 2029: # --------------- Take an uploaded file and put it into the userfiles directory
 2030: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2031: #                    the desired filenam is in $env{"form.$formname.filename"}
 2032: #        $coursedoc - if true up to the current course
 2033: #                     if false
 2034: #        $subdir - directory in userfile to store the file into
 2035: #        $parser - instruction to parse file for objects ($parser = parse)    
 2036: #        $allfiles - reference to hash for embedded objects
 2037: #        $codebase - reference to hash for codebase of java objects
 2038: #        $desuname - username for permanent storage of uploaded file
 2039: #        $dsetudom - domain for permanaent storage of uploaded file
 2040: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2041: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2042: # 
 2043: # output: url of file in userspace, or error: <message> 
 2044: #             or /adm/notfound.html if failure to upload occurse
 2045: 
 2046: 
 2047: sub userfileupload {
 2048:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2049:         $destudom,$thumbwidth,$thumbheight)=@_;
 2050:     if (!defined($subdir)) { $subdir='unknown'; }
 2051:     my $fname=$env{'form.'.$formname.'.filename'};
 2052:     $fname=&clean_filename($fname);
 2053: # See if there is anything left
 2054:     unless ($fname) { return 'error: no uploaded file'; }
 2055:     chop($env{'form.'.$formname});
 2056:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2057:         my $now = time;
 2058:         my $filepath = 'tmp/helprequests/'.$now;
 2059:         my @parts=split(/\//,$filepath);
 2060:         my $fullpath = $perlvar{'lonDaemons'};
 2061:         for (my $i=0;$i<@parts;$i++) {
 2062:             $fullpath .= '/'.$parts[$i];
 2063:             if ((-e $fullpath)!=1) {
 2064:                 mkdir($fullpath,0777);
 2065:             }
 2066:         }
 2067:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2068:         print $fh $env{'form.'.$formname};
 2069:         close($fh);
 2070:         return $fullpath.'/'.$fname;
 2071:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2072:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2073:                        '_'.$env{'user.domain'}.'/pending';
 2074:         my @parts=split(/\//,$filepath);
 2075:         my $fullpath = $perlvar{'lonDaemons'};
 2076:         for (my $i=0;$i<@parts;$i++) {
 2077:             $fullpath .= '/'.$parts[$i];
 2078:             if ((-e $fullpath)!=1) {
 2079:                 mkdir($fullpath,0777);
 2080:             }
 2081:         }
 2082:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2083:         print $fh $env{'form.'.$formname};
 2084:         close($fh);
 2085:         return $fullpath.'/'.$fname;
 2086:     }
 2087:     
 2088: # Create the directory if not present
 2089:     $fname="$subdir/$fname";
 2090:     if ($coursedoc) {
 2091: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2092: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2093:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2094:             return &finishuserfileupload($docuname,$docudom,
 2095: 					 $formname,$fname,$parser,$allfiles,
 2096: 					 $codebase,$thumbwidth,$thumbheight);
 2097:         } else {
 2098:             $fname=$env{'form.folder'}.'/'.$fname;
 2099:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2100: 				       $fname,$formname,$parser,
 2101: 				       $allfiles,$codebase);
 2102:         }
 2103:     } elsif (defined($destuname)) {
 2104:         my $docuname=$destuname;
 2105:         my $docudom=$destudom;
 2106: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2107: 				     $parser,$allfiles,$codebase,
 2108:                                      $thumbwidth,$thumbheight);
 2109:         
 2110:     } else {
 2111:         my $docuname=$env{'user.name'};
 2112:         my $docudom=$env{'user.domain'};
 2113:         if (exists($env{'form.group'})) {
 2114:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2115:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2116:         }
 2117: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2118: 				     $parser,$allfiles,$codebase,
 2119:                                      $thumbwidth,$thumbheight);
 2120:     }
 2121: }
 2122: 
 2123: sub finishuserfileupload {
 2124:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2125:         $thumbwidth,$thumbheight) = @_;
 2126:     my $path=$docudom.'/'.$docuname.'/';
 2127:     my $filepath=$perlvar{'lonDocRoot'};
 2128:     my ($fnamepath,$file,$fetchthumb);
 2129:     $file=$fname;
 2130:     if ($fname=~m|/|) {
 2131:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2132: 	$path.=$fnamepath.'/';
 2133:     }
 2134:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2135:     my $count;
 2136:     for ($count=4;$count<=$#parts;$count++) {
 2137:         $filepath.="/$parts[$count]";
 2138:         if ((-e $filepath)!=1) {
 2139: 	    mkdir($filepath,0777);
 2140:         }
 2141:     }
 2142: # Save the file
 2143:     {
 2144: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2145: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2146: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2147: 	    return '/adm/notfound.html';
 2148: 	}
 2149: 	if (!print FH ($env{'form.'.$formname})) {
 2150: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2151: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2152: 	    return '/adm/notfound.html';
 2153: 	}
 2154: 	close(FH);
 2155:     }
 2156:     if ($parser eq 'parse') {
 2157:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2158: 						   $codebase);
 2159:         unless ($parse_result eq 'ok') {
 2160:             &logthis('Failed to parse '.$filepath.$file.
 2161: 		     ' for embedded media: '.$parse_result); 
 2162:         }
 2163:     }
 2164:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2165:         my $input = $filepath.'/'.$file;
 2166:         my $output = $filepath.'/'.'tn-'.$file;
 2167:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2168:         system("convert -sample $thumbsize $input $output");
 2169:         if (-e $filepath.'/'.'tn-'.$file) {
 2170:             $fetchthumb  = 1; 
 2171:         }
 2172:     }
 2173:  
 2174: # Notify homeserver to grep it
 2175: #
 2176:     my $docuhome=&homeserver($docuname,$docudom);
 2177:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2178:     if ($fetchresult eq 'ok') {
 2179:         if ($fetchthumb) {
 2180:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2181:             if ($thumbresult ne 'ok') {
 2182:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2183:                          $docuhome.': '.$thumbresult);
 2184:             }
 2185:         }
 2186: #
 2187: # Return the URL to it
 2188:         return '/uploaded/'.$path.$file;
 2189:     } else {
 2190:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2191: 		 ': '.$fetchresult);
 2192:         return '/adm/notfound.html';
 2193:     }
 2194: }
 2195: 
 2196: sub extract_embedded_items {
 2197:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2198:     my @state = ();
 2199:     my %javafiles = (
 2200:                       codebase => '',
 2201:                       code => '',
 2202:                       archive => ''
 2203:                     );
 2204:     my %mediafiles = (
 2205:                       src => '',
 2206:                       movie => '',
 2207:                      );
 2208:     my $p;
 2209:     if ($content) {
 2210:         $p = HTML::LCParser->new($content);
 2211:     } else {
 2212:         $p = HTML::LCParser->new($fullpath);
 2213:     }
 2214:     while (my $t=$p->get_token()) {
 2215: 	if ($t->[0] eq 'S') {
 2216: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2217: 	    push(@state, $tagname);
 2218:             if (lc($tagname) eq 'allow') {
 2219:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2220:             }
 2221: 	    if (lc($tagname) eq 'img') {
 2222: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2223: 	    }
 2224: 	    if (lc($tagname) eq 'a') {
 2225: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2226: 	    }
 2227:             if (lc($tagname) eq 'script') {
 2228:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2229:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2230:                 } else {
 2231:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2232:                 }
 2233:             }
 2234:             if (lc($tagname) eq 'link') {
 2235:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2236:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2237:                 }
 2238:             }
 2239: 	    if (lc($tagname) eq 'object' ||
 2240: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2241: 		foreach my $item (keys(%javafiles)) {
 2242: 		    $javafiles{$item} = '';
 2243: 		}
 2244: 	    }
 2245: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2246: 		my $name = lc($attr->{'name'});
 2247: 		foreach my $item (keys(%javafiles)) {
 2248: 		    if ($name eq $item) {
 2249: 			$javafiles{$item} = $attr->{'value'};
 2250: 			last;
 2251: 		    }
 2252: 		}
 2253: 		foreach my $item (keys(%mediafiles)) {
 2254: 		    if ($name eq $item) {
 2255: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2256: 			last;
 2257: 		    }
 2258: 		}
 2259: 	    }
 2260: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2261: 		foreach my $item (keys(%javafiles)) {
 2262: 		    if ($attr->{$item}) {
 2263: 			$javafiles{$item} = $attr->{$item};
 2264: 			last;
 2265: 		    }
 2266: 		}
 2267: 		foreach my $item (keys(%mediafiles)) {
 2268: 		    if ($attr->{$item}) {
 2269: 			&add_filetype($allfiles,$attr->{$item},$item);
 2270: 			last;
 2271: 		    }
 2272: 		}
 2273: 	    }
 2274: 	} elsif ($t->[0] eq 'E') {
 2275: 	    my ($tagname) = ($t->[1]);
 2276: 	    if ($javafiles{'codebase'} ne '') {
 2277: 		$javafiles{'codebase'} .= '/';
 2278: 	    }  
 2279: 	    if (lc($tagname) eq 'applet' ||
 2280: 		lc($tagname) eq 'object' ||
 2281: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2282: 		) {
 2283: 		foreach my $item (keys(%javafiles)) {
 2284: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2285: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2286: 			&add_filetype($allfiles,$file,$item);
 2287: 		    }
 2288: 		}
 2289: 	    } 
 2290: 	    pop @state;
 2291: 	}
 2292:     }
 2293:     return 'ok';
 2294: }
 2295: 
 2296: sub add_filetype {
 2297:     my ($allfiles,$file,$type)=@_;
 2298:     if (exists($allfiles->{$file})) {
 2299: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2300: 	    push(@{$allfiles->{$file}}, &escape($type));
 2301: 	}
 2302:     } else {
 2303: 	@{$allfiles->{$file}} = (&escape($type));
 2304:     }
 2305: }
 2306: 
 2307: sub removeuploadedurl {
 2308:     my ($url)=@_;
 2309:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2310:     return &removeuserfile($uname,$udom,$fname);
 2311: }
 2312: 
 2313: sub removeuserfile {
 2314:     my ($docuname,$docudom,$fname)=@_;
 2315:     my $home=&homeserver($docuname,$docudom);
 2316:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2317:     if ($result eq 'ok') {
 2318:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2319:             my $metafile = $fname.'.meta';
 2320:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2321: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2322:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2323:             my $sqlresult = 
 2324:                 &update_portfolio_table($docuname,$docudom,$file,
 2325:                                         'portfolio_metadata',$group,
 2326:                                         'delete');
 2327:         }
 2328:     }
 2329:     return $result;
 2330: }
 2331: 
 2332: sub mkdiruserfile {
 2333:     my ($docuname,$docudom,$dir)=@_;
 2334:     my $home=&homeserver($docuname,$docudom);
 2335:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2336: }
 2337: 
 2338: sub renameuserfile {
 2339:     my ($docuname,$docudom,$old,$new)=@_;
 2340:     my $home=&homeserver($docuname,$docudom);
 2341:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2342:                         &escape("$old").':'.&escape("$new"),$home);
 2343:     if ($result eq 'ok') {
 2344:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2345:             my $oldmeta = $old.'.meta';
 2346:             my $newmeta = $new.'.meta';
 2347:             my $metaresult = 
 2348:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2349: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2350:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2351:             my $sqlresult = 
 2352:                 &update_portfolio_table($docuname,$docudom,$file,
 2353:                                         'portfolio_metadata',$group,
 2354:                                         'delete');
 2355:         }
 2356:     }
 2357:     return $result;
 2358: }
 2359: 
 2360: # ------------------------------------------------------------------------- Log
 2361: 
 2362: sub log {
 2363:     my ($dom,$nam,$hom,$what)=@_;
 2364:     return critical("log:$dom:$nam:$what",$hom);
 2365: }
 2366: 
 2367: # ------------------------------------------------------------------ Course Log
 2368: #
 2369: # This routine flushes several buffers of non-mission-critical nature
 2370: #
 2371: 
 2372: sub flushcourselogs {
 2373:     &logthis('Flushing log buffers');
 2374: #
 2375: # course logs
 2376: # This is a log of all transactions in a course, which can be used
 2377: # for data mining purposes
 2378: #
 2379: # It also collects the courseid database, which lists last transaction
 2380: # times and course titles for all courseids
 2381: #
 2382:     my %courseidbuffer=();
 2383:     foreach my $crsid (keys(%courselogs)) {
 2384:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2385: 		          &escape($courselogs{$crsid}),
 2386: 		          $coursehombuf{$crsid}) eq 'ok') {
 2387: 	    delete $courselogs{$crsid};
 2388:         } else {
 2389:             &logthis('Failed to flush log buffer for '.$crsid);
 2390:             if (length($courselogs{$crsid})>40000) {
 2391:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2392:                         " exceeded maximum size, deleting.</font>");
 2393:                delete $courselogs{$crsid};
 2394:             }
 2395:         }
 2396:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2397:             'description' => $coursedescrbuf{$crsid},
 2398:             'inst_code'    => $courseinstcodebuf{$crsid},
 2399:             'type'        => $coursetypebuf{$crsid},
 2400:             'owner'       => $courseownerbuf{$crsid},
 2401:         };
 2402:     }
 2403: #
 2404: # Write course id database (reverse lookup) to homeserver of courses 
 2405: # Is used in pickcourse
 2406: #
 2407:     foreach my $crs_home (keys(%courseidbuffer)) {
 2408:         my $response = &courseidput(&host_domain($crs_home),
 2409:                                     $courseidbuffer{$crs_home},
 2410:                                     $crs_home,'timeonly');
 2411:     }
 2412: #
 2413: # File accesses
 2414: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2415: #
 2416:     foreach my $entry (keys(%accesshash)) {
 2417:         if ($entry =~ /___count$/) {
 2418:             my ($dom,$name);
 2419:             ($dom,$name,undef)=
 2420: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2421:             if (! defined($dom) || $dom eq '' || 
 2422:                 ! defined($name) || $name eq '') {
 2423:                 my $cid = $env{'request.course.id'};
 2424:                 $dom  = $env{'request.'.$cid.'.domain'};
 2425:                 $name = $env{'request.'.$cid.'.num'};
 2426:             }
 2427:             my $value = $accesshash{$entry};
 2428:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2429:             my %temphash=($url => $value);
 2430:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2431:             if ($result eq 'ok') {
 2432:                 delete $accesshash{$entry};
 2433:             } elsif ($result eq 'unknown_cmd') {
 2434:                 # Target server has old code running on it.
 2435:                 my %temphash=($entry => $value);
 2436:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2437:                     delete $accesshash{$entry};
 2438:                 }
 2439:             }
 2440:         } else {
 2441:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2442:             my %temphash=($entry => $accesshash{$entry});
 2443:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2444:                 delete $accesshash{$entry};
 2445:             }
 2446:         }
 2447:     }
 2448: #
 2449: # Roles
 2450: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2451: #
 2452:     foreach my $entry (keys(%userrolehash)) {
 2453:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2454: 	    split(/\:/,$entry);
 2455:         if (&Apache::lonnet::put('nohist_userroles',
 2456:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2457:                 $rudom,$runame) eq 'ok') {
 2458: 	    delete $userrolehash{$entry};
 2459:         }
 2460:     }
 2461: #
 2462: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2463: #
 2464:     my %domrolebuffer = ();
 2465:     foreach my $entry (keys %domainrolehash) {
 2466:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2467:         if ($domrolebuffer{$rudom}) {
 2468:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2469:                       '='.&escape($domainrolehash{$entry});
 2470:         } else {
 2471:             $domrolebuffer{$rudom}.=&escape($entry).
 2472:                       '='.&escape($domainrolehash{$entry});
 2473:         }
 2474:         delete $domainrolehash{$entry};
 2475:     }
 2476:     foreach my $dom (keys(%domrolebuffer)) {
 2477: 	my %servers = &get_servers($dom,'library');
 2478: 	foreach my $tryserver (keys(%servers)) {
 2479: 	    unless (&reply('domroleput:'.$dom.':'.
 2480: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2481: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2482: 	    }
 2483:         }
 2484:     }
 2485:     $dumpcount++;
 2486: }
 2487: 
 2488: sub courselog {
 2489:     my $what=shift;
 2490:     $what=time.':'.$what;
 2491:     unless ($env{'request.course.id'}) { return ''; }
 2492:     $coursedombuf{$env{'request.course.id'}}=
 2493:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2494:     $coursenumbuf{$env{'request.course.id'}}=
 2495:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2496:     $coursehombuf{$env{'request.course.id'}}=
 2497:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2498:     $coursedescrbuf{$env{'request.course.id'}}=
 2499:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2500:     $courseinstcodebuf{$env{'request.course.id'}}=
 2501:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2502:     $courseownerbuf{$env{'request.course.id'}}=
 2503:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2504:     $coursetypebuf{$env{'request.course.id'}}=
 2505:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2506:     if (defined $courselogs{$env{'request.course.id'}}) {
 2507: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2508:     } else {
 2509: 	$courselogs{$env{'request.course.id'}}.=$what;
 2510:     }
 2511:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2512: 	&flushcourselogs();
 2513:     }
 2514: }
 2515: 
 2516: sub courseacclog {
 2517:     my $fnsymb=shift;
 2518:     unless ($env{'request.course.id'}) { return ''; }
 2519:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2520:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2521:         $what.=':POST';
 2522:         # FIXME: Probably ought to escape things....
 2523: 	foreach my $key (keys(%env)) {
 2524:             if ($key=~/^form\.(.*)/) {
 2525:                 my $formitem = $1;
 2526:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2527:                     $what.=':'.$formitem.'='.$env{$key};
 2528:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2529:                     $what.=':'.$formitem.'='.$env{$key};
 2530:                 }
 2531:             }
 2532:         }
 2533:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2534:         # FIXME: We should not be depending on a form parameter that someone
 2535:         # editing lonsearchcat.pm might change in the future.
 2536:         if ($env{'form.phase'} eq 'course_search') {
 2537:             $what.= ':POST';
 2538:             # FIXME: Probably ought to escape things....
 2539:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2540:                                  'crsdiscuss') {
 2541:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2542:             }
 2543:         }
 2544:     }
 2545:     &courselog($what);
 2546: }
 2547: 
 2548: sub countacc {
 2549:     my $url=&declutter(shift);
 2550:     return if (! defined($url) || $url eq '');
 2551:     unless ($env{'request.course.id'}) { return ''; }
 2552:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2553:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2554:     $accesshash{$key}++;
 2555: }
 2556: 
 2557: sub linklog {
 2558:     my ($from,$to)=@_;
 2559:     $from=&declutter($from);
 2560:     $to=&declutter($to);
 2561:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2562:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2563: }
 2564:   
 2565: sub userrolelog {
 2566:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2567:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2568:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2569:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2570:         ($trole=~/^ta/)) {
 2571:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2572:        $userrolehash
 2573:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2574:                     =$tend.':'.$tstart;
 2575:     }
 2576:     if (($env{'request.role'} =~ /dc\./) &&
 2577: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2578: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2579: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2580:        $userrolehash
 2581:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2582:                     =$tend.':'.$tstart;
 2583:     }
 2584:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2585:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2586:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2587:         ($trole=~/^sc/)) {
 2588:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2589:        $domainrolehash
 2590:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2591:                     = $tend.':'.$tstart;
 2592:     }
 2593: }
 2594: 
 2595: sub courserolelog {
 2596:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2597:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2598:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2599:         ($trole eq 'ta') || ($trole eq 'st') ||
 2600:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2601:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2602:             my $cdom = $1;
 2603:             my $cnum = $2;
 2604:             my $sec = $3;
 2605:             my $namespace = 'rolelog';
 2606:             my %storehash = (
 2607:                                role    => $trole,
 2608:                                start   => $tstart,
 2609:                                end     => $tend,
 2610:                                selfenroll => $selfenroll,
 2611:                                context    => $context,
 2612:                             );
 2613:             if ($trole eq 'gr') {
 2614:                 $namespace = 'groupslog';
 2615:                 $storehash{'group'} = $sec;
 2616:             } else {
 2617:                 $storehash{'section'} = $sec;
 2618:             }
 2619:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2620:         }
 2621:     }
 2622:     return;
 2623: }
 2624: 
 2625: sub get_course_adv_roles {
 2626:     my ($cid,$codes) = @_;
 2627:     $cid=$env{'request.course.id'} unless (defined($cid));
 2628:     my %coursehash=&coursedescription($cid);
 2629:     my %nothide=();
 2630:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2631:         if ($user !~ /:/) {
 2632: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2633:         } else {
 2634:             $nothide{$user}=1;
 2635:         }
 2636:     }
 2637:     my %returnhash=();
 2638:     my %dumphash=
 2639:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2640:     my $now=time;
 2641:     foreach my $entry (keys %dumphash) {
 2642: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2643:         if (($tstart) && ($tstart<0)) { next; }
 2644:         if (($tend) && ($tend<$now)) { next; }
 2645:         if (($tstart) && ($now<$tstart)) { next; }
 2646:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2647: 	if ($username eq '' || $domain eq '') { next; }
 2648: 	if ((&privileged($username,$domain)) && 
 2649: 	    (!$nothide{$username.':'.$domain})) { next; }
 2650: 	if ($role eq 'cr') { next; }
 2651:         if ($codes) {
 2652:             if ($section) { $role .= ':'.$section; }
 2653:             if ($returnhash{$role}) {
 2654:                 $returnhash{$role}.=','.$username.':'.$domain;
 2655:             } else {
 2656:                 $returnhash{$role}=$username.':'.$domain;
 2657:             }
 2658:         } else {
 2659:             my $key=&plaintext($role);
 2660:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2661:             if ($returnhash{$key}) {
 2662: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2663:             } else {
 2664:                 $returnhash{$key}=$username.':'.$domain;
 2665:             }
 2666:         }
 2667:     }
 2668:     return %returnhash;
 2669: }
 2670: 
 2671: sub get_my_roles {
 2672:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2673:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2674:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2675:     my (%dumphash,%nothide);
 2676:     if ($context eq 'userroles') { 
 2677:         %dumphash = &dump('roles',$udom,$uname);
 2678:     } else {
 2679:         %dumphash=
 2680:             &dump('nohist_userroles',$udom,$uname);
 2681:         if ($hidepriv) {
 2682:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2683:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2684:                 if ($user !~ /:/) {
 2685:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2686:                 } else {
 2687:                     $nothide{$user} = 1;
 2688:                 }
 2689:             }
 2690:         }
 2691:     }
 2692:     my %returnhash=();
 2693:     my $now=time;
 2694:     foreach my $entry (keys(%dumphash)) {
 2695:         my ($role,$tend,$tstart);
 2696:         if ($context eq 'userroles') {
 2697: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2698:         } else {
 2699:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2700:         }
 2701:         if (($tstart) && ($tstart<0)) { next; }
 2702:         my $status = 'active';
 2703:         if (($tend) && ($tend<=$now)) {
 2704:             $status = 'previous';
 2705:         } 
 2706:         if (($tstart) && ($now<$tstart)) {
 2707:             $status = 'future';
 2708:         }
 2709:         if (ref($types) eq 'ARRAY') {
 2710:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2711:                 next;
 2712:             } 
 2713:         } else {
 2714:             if ($status ne 'active') {
 2715:                 next;
 2716:             }
 2717:         }
 2718:         my ($rolecode,$username,$domain,$section,$area);
 2719:         if ($context eq 'userroles') {
 2720:             ($area,$rolecode) = split(/_/,$entry);
 2721:             (undef,$domain,$username,$section) = split(/\//,$area);
 2722:         } else {
 2723:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2724:         }
 2725:         if (ref($roledoms) eq 'ARRAY') {
 2726:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2727:                 next;
 2728:             }
 2729:         }
 2730:         if (ref($roles) eq 'ARRAY') {
 2731:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2732:                 if ($role =~ /^cr\//) {
 2733:                     if (!grep(/^cr$/,@{$roles})) {
 2734:                         next;
 2735:                     }
 2736:                 } else {
 2737:                     next;
 2738:                 }
 2739:             }
 2740:         }
 2741:         if ($hidepriv) {
 2742:             if ((&privileged($username,$domain)) &&
 2743:                 (!$nothide{$username.':'.$domain})) { 
 2744:                 next;
 2745:             }
 2746:         }
 2747:         if ($withsec) {
 2748:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2749:                 $tstart.':'.$tend;
 2750:         } else {
 2751:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2752:         }
 2753:     }
 2754:     return %returnhash;
 2755: }
 2756: 
 2757: # ----------------------------------------------------- Frontpage Announcements
 2758: #
 2759: #
 2760: 
 2761: sub postannounce {
 2762:     my ($server,$text)=@_;
 2763:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2764:     unless ($text=~/\w/) { $text=''; }
 2765:     return &reply('setannounce:'.&escape($text),$server);
 2766: }
 2767: 
 2768: sub getannounce {
 2769: 
 2770:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2771: 	my $announcement='';
 2772: 	while (my $line = <$fh>) { $announcement .= $line; }
 2773: 	close($fh);
 2774: 	if ($announcement=~/\w/) { 
 2775: 	    return 
 2776:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2777:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2778: 	} else {
 2779: 	    return '';
 2780: 	}
 2781:     } else {
 2782: 	return '';
 2783:     }
 2784: }
 2785: 
 2786: # ---------------------------------------------------------- Course ID routines
 2787: # Deal with domain's nohist_courseid.db files
 2788: #
 2789: 
 2790: sub courseidput {
 2791:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2792:     my $outcome;
 2793:     if ($caller eq 'timeonly') {
 2794:         my $cids = '';
 2795:         foreach my $item (keys(%$storehash)) {
 2796:             $cids.=&escape($item).'&';
 2797:         }
 2798:         $cids=~s/\&$//;
 2799:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2800:                           $coursehome);       
 2801:     } else {
 2802:         my $items = '';
 2803:         foreach my $item (keys(%$storehash)) {
 2804:             $items.= &escape($item).'='.
 2805:                      &freeze_escape($$storehash{$item}).'&';
 2806:         }
 2807:         $items=~s/\&$//;
 2808:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2809:                           $coursehome);
 2810:     }
 2811:     if ($outcome eq 'unknown_cmd') {
 2812:         my $what;
 2813:         foreach my $cid (keys(%$storehash)) {
 2814:             $what .= &escape($cid).'=';
 2815:             foreach my $item ('description','inst_code','owner','type') {
 2816:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2817:             }
 2818:             $what =~ s/\:$/&/;
 2819:         }
 2820:         $what =~ s/\&$//;  
 2821:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2822:     } else {
 2823:         return $outcome;
 2824:     }
 2825: }
 2826: 
 2827: sub courseiddump {
 2828:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2829:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2830:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2831:     my $as_hash = 1;
 2832:     my %returnhash;
 2833:     if (!$domfilter) { $domfilter=''; }
 2834:     my %libserv = &all_library();
 2835:     foreach my $tryserver (keys(%libserv)) {
 2836:         if ( (  $hostidflag == 1 
 2837: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2838: 	     || (!defined($hostidflag)) ) {
 2839: 
 2840: 	    if (($domfilter eq '') ||
 2841: 		(&host_domain($tryserver) eq $domfilter)) {
 2842:                 my $rep = 
 2843:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2844:                          $sincefilter.':'.&escape($descfilter).':'.
 2845:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2846:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2847:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2848:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2849:                          $showhidden.':'.$caller,$tryserver);
 2850:                 my @pairs=split(/\&/,$rep);
 2851:                 foreach my $item (@pairs) {
 2852:                     my ($key,$value)=split(/\=/,$item,2);
 2853:                     $key = &unescape($key);
 2854:                     next if ($key =~ /^error: 2 /);
 2855:                     my $result = &thaw_unescape($value);
 2856:                     if (ref($result) eq 'HASH') {
 2857:                         $returnhash{$key}=$result;
 2858:                     } else {
 2859:                         my @responses = split(/:/,$value);
 2860:                         my @items = ('description','inst_code','owner','type');
 2861:                         for (my $i=0; $i<@responses; $i++) {
 2862:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2863:                         }
 2864:                     } 
 2865:                 }
 2866:             }
 2867:         }
 2868:     }
 2869:     return %returnhash;
 2870: }
 2871: 
 2872: # ---------------------------------------------------------- DC e-mail
 2873: 
 2874: sub dcmailput {
 2875:     my ($domain,$msgid,$message,$server)=@_;
 2876:     my $status = &Apache::lonnet::critical(
 2877:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2878:        &escape($message),$server);
 2879:     return $status;
 2880: }
 2881: 
 2882: sub dcmaildump {
 2883:     my ($dom,$startdate,$enddate,$senders) = @_;
 2884:     my %returnhash=();
 2885: 
 2886:     if (defined(&domain($dom,'primary'))) {
 2887:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2888:                                                          &escape($enddate).':';
 2889: 	my @esc_senders=map { &escape($_)} @$senders;
 2890: 	$cmd.=&escape(join('&',@esc_senders));
 2891: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2892:             my ($key,$value) = split(/\=/,$line,2);
 2893:             if (($key) && ($value)) {
 2894:                 $returnhash{&unescape($key)} = &unescape($value);
 2895:             }
 2896:         }
 2897:     }
 2898:     return %returnhash;
 2899: }
 2900: # ---------------------------------------------------------- Domain roles
 2901: 
 2902: sub get_domain_roles {
 2903:     my ($dom,$roles,$startdate,$enddate)=@_;
 2904:     if (undef($startdate) || $startdate eq '') {
 2905:         $startdate = '.';
 2906:     }
 2907:     if (undef($enddate) || $enddate eq '') {
 2908:         $enddate = '.';
 2909:     }
 2910:     my $rolelist;
 2911:     if (ref($roles) eq 'ARRAY') {
 2912:         $rolelist = join(':',@{$roles});
 2913:     }
 2914:     my %personnel = ();
 2915: 
 2916:     my %servers = &get_servers($dom,'library');
 2917:     foreach my $tryserver (keys(%servers)) {
 2918: 	%{$personnel{$tryserver}}=();
 2919: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2920: 					    &escape($startdate).':'.
 2921: 					    &escape($enddate).':'.
 2922: 					    &escape($rolelist), $tryserver))) {
 2923: 	    my ($key,$value) = split(/\=/,$line,2);
 2924: 	    if (($key) && ($value)) {
 2925: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2926: 	    }
 2927: 	}
 2928:     }
 2929:     return %personnel;
 2930: }
 2931: 
 2932: # ----------------------------------------------------------- Check out an item
 2933: 
 2934: sub get_first_access {
 2935:     my ($type,$argsymb)=@_;
 2936:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2937:     if ($argsymb) { $symb=$argsymb; }
 2938:     my ($map,$id,$res)=&decode_symb($symb);
 2939:     if ($type eq 'course') {
 2940: 	$res='course';
 2941:     } elsif ($type eq 'map') {
 2942: 	$res=&symbread($map);
 2943:     } else {
 2944: 	$res=$symb;
 2945:     }
 2946:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2947:     return $times{"$courseid\0$res"};
 2948: }
 2949: 
 2950: sub set_first_access {
 2951:     my ($type)=@_;
 2952:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2953:     my ($map,$id,$res)=&decode_symb($symb);
 2954:     if ($type eq 'course') {
 2955: 	$res='course';
 2956:     } elsif ($type eq 'map') {
 2957: 	$res=&symbread($map);
 2958:     } else {
 2959: 	$res=$symb;
 2960:     }
 2961:     my $firstaccess=&get_first_access($type,$symb);
 2962:     if (!$firstaccess) {
 2963: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2964:     }
 2965:     return 'already_set';
 2966: }
 2967: 
 2968: sub checkout {
 2969:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2970:     my $now=time;
 2971:     my $lonhost=$perlvar{'lonHostID'};
 2972:     my $infostr=&escape(
 2973:                  'CHECKOUTTOKEN&'.
 2974:                  $tuname.'&'.
 2975:                  $tudom.'&'.
 2976:                  $tcrsid.'&'.
 2977:                  $symb.'&'.
 2978: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2979:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2980:     if ($token=~/^error\:/) { 
 2981:         &logthis("<font color=\"blue\">WARNING: ".
 2982:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2983:                  "</font>");
 2984:         return ''; 
 2985:     }
 2986: 
 2987:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2988:     $token=~tr/a-z/A-Z/;
 2989: 
 2990:     my %infohash=('resource.0.outtoken' => $token,
 2991:                   'resource.0.checkouttime' => $now,
 2992:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2993: 
 2994:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2995:        return '';
 2996:     } else {
 2997:         &logthis("<font color=\"blue\">WARNING: ".
 2998:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2999:                  "</font>");
 3000:     }    
 3001: 
 3002:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3003:                          &escape('Checkout '.$infostr.' - '.
 3004:                                                  $token)) ne 'ok') {
 3005: 	return '';
 3006:     } else {
 3007:         &logthis("<font color=\"blue\">WARNING: ".
 3008:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3009:                  "</font>");
 3010:     }
 3011:     return $token;
 3012: }
 3013: 
 3014: # ------------------------------------------------------------ Check in an item
 3015: 
 3016: sub checkin {
 3017:     my $token=shift;
 3018:     my $now=time;
 3019:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3020:     $lonhost=~tr/A-Z/a-z/;
 3021:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3022:     $dtoken=~s/\W/\_/g;
 3023:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3024:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3025: 
 3026:     unless (($tuname) && ($tudom)) {
 3027:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3028:         return '';
 3029:     }
 3030:     
 3031:     unless (&allowed('mgr',$tcrsid)) {
 3032:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3033:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3034:         return '';
 3035:     }
 3036: 
 3037:     my %infohash=('resource.0.intoken' => $token,
 3038:                   'resource.0.checkintime' => $now,
 3039:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3040: 
 3041:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3042:        return '';
 3043:     }    
 3044: 
 3045:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3046:                          &escape('Checkin - '.$token)) ne 'ok') {
 3047: 	return '';
 3048:     }
 3049: 
 3050:     return ($symb,$tuname,$tudom,$tcrsid);    
 3051: }
 3052: 
 3053: # --------------------------------------------- Set Expire Date for Spreadsheet
 3054: 
 3055: sub expirespread {
 3056:     my ($uname,$udom,$stype,$usymb)=@_;
 3057:     my $cid=$env{'request.course.id'}; 
 3058:     if ($cid) {
 3059:        my $now=time;
 3060:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3061:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3062:                             $env{'course.'.$cid.'.num'}.
 3063: 	        	    ':nohist_expirationdates:'.
 3064:                             &escape($key).'='.$now,
 3065:                             $env{'course.'.$cid.'.home'})
 3066:     }
 3067:     return 'ok';
 3068: }
 3069: 
 3070: # ----------------------------------------------------- Devalidate Spreadsheets
 3071: 
 3072: sub devalidate {
 3073:     my ($symb,$uname,$udom)=@_;
 3074:     my $cid=$env{'request.course.id'}; 
 3075:     if ($cid) {
 3076:         # delete the stored spreadsheets for
 3077:         # - the student level sheet of this user in course's homespace
 3078:         # - the assessment level sheet for this resource 
 3079:         #   for this user in user's homespace
 3080: 	# - current conditional state info
 3081: 	my $key=$uname.':'.$udom.':';
 3082:         my $status=
 3083: 	    &del('nohist_calculatedsheets',
 3084: 		 [$key.'studentcalc:'],
 3085: 		 $env{'course.'.$cid.'.domain'},
 3086: 		 $env{'course.'.$cid.'.num'})
 3087: 		.' '.
 3088: 	    &del('nohist_calculatedsheets_'.$cid,
 3089: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3090:         unless ($status eq 'ok ok') {
 3091:            &logthis('Could not devalidate spreadsheet '.
 3092:                     $uname.' at '.$udom.' for '.
 3093: 		    $symb.': '.$status);
 3094:         }
 3095: 	&delenv('user.state.'.$cid);
 3096:     }
 3097: }
 3098: 
 3099: sub get_scalar {
 3100:     my ($string,$end) = @_;
 3101:     my $value;
 3102:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3103: 	$value = $1;
 3104:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3105: 	$value = $1;
 3106:     }
 3107:     return &unescape($value);
 3108: }
 3109: 
 3110: sub array2str {
 3111:   my (@array) = @_;
 3112:   my $result=&arrayref2str(\@array);
 3113:   $result=~s/^__ARRAY_REF__//;
 3114:   $result=~s/__END_ARRAY_REF__$//;
 3115:   return $result;
 3116: }
 3117: 
 3118: sub arrayref2str {
 3119:   my ($arrayref) = @_;
 3120:   my $result='__ARRAY_REF__';
 3121:   foreach my $elem (@$arrayref) {
 3122:     if(ref($elem) eq 'ARRAY') {
 3123:       $result.=&arrayref2str($elem).'&';
 3124:     } elsif(ref($elem) eq 'HASH') {
 3125:       $result.=&hashref2str($elem).'&';
 3126:     } elsif(ref($elem)) {
 3127:       #print("Got a ref of ".(ref($elem))." skipping.");
 3128:     } else {
 3129:       $result.=&escape($elem).'&';
 3130:     }
 3131:   }
 3132:   $result=~s/\&$//;
 3133:   $result .= '__END_ARRAY_REF__';
 3134:   return $result;
 3135: }
 3136: 
 3137: sub hash2str {
 3138:   my (%hash) = @_;
 3139:   my $result=&hashref2str(\%hash);
 3140:   $result=~s/^__HASH_REF__//;
 3141:   $result=~s/__END_HASH_REF__$//;
 3142:   return $result;
 3143: }
 3144: 
 3145: sub hashref2str {
 3146:   my ($hashref)=@_;
 3147:   my $result='__HASH_REF__';
 3148:   foreach my $key (sort(keys(%$hashref))) {
 3149:     if (ref($key) eq 'ARRAY') {
 3150:       $result.=&arrayref2str($key).'=';
 3151:     } elsif (ref($key) eq 'HASH') {
 3152:       $result.=&hashref2str($key).'=';
 3153:     } elsif (ref($key)) {
 3154:       $result.='=';
 3155:       #print("Got a ref of ".(ref($key))." skipping.");
 3156:     } else {
 3157: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3158:     }
 3159: 
 3160:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3161:       $result.=&arrayref2str($hashref->{$key}).'&';
 3162:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3163:       $result.=&hashref2str($hashref->{$key}).'&';
 3164:     } elsif(ref($hashref->{$key})) {
 3165:        $result.='&';
 3166:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3167:     } else {
 3168:       $result.=&escape($hashref->{$key}).'&';
 3169:     }
 3170:   }
 3171:   $result=~s/\&$//;
 3172:   $result .= '__END_HASH_REF__';
 3173:   return $result;
 3174: }
 3175: 
 3176: sub str2hash {
 3177:     my ($string)=@_;
 3178:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3179:     return %$hash;
 3180: }
 3181: 
 3182: sub str2hashref {
 3183:   my ($string) = @_;
 3184: 
 3185:   my %hash;
 3186: 
 3187:   if($string !~ /^__HASH_REF__/) {
 3188:       if (! ($string eq '' || !defined($string))) {
 3189: 	  $hash{'error'}='Not hash reference';
 3190:       }
 3191:       return (\%hash, $string);
 3192:   }
 3193: 
 3194:   $string =~ s/^__HASH_REF__//;
 3195: 
 3196:   while($string !~ /^__END_HASH_REF__/) {
 3197:       #key
 3198:       my $key='';
 3199:       if($string =~ /^__HASH_REF__/) {
 3200:           ($key, $string)=&str2hashref($string);
 3201:           if(defined($key->{'error'})) {
 3202:               $hash{'error'}='Bad data';
 3203:               return (\%hash, $string);
 3204:           }
 3205:       } elsif($string =~ /^__ARRAY_REF__/) {
 3206:           ($key, $string)=&str2arrayref($string);
 3207:           if($key->[0] eq 'Array reference error') {
 3208:               $hash{'error'}='Bad data';
 3209:               return (\%hash, $string);
 3210:           }
 3211:       } else {
 3212:           $string =~ s/^(.*?)=//;
 3213: 	  $key=&unescape($1);
 3214:       }
 3215:       $string =~ s/^=//;
 3216: 
 3217:       #value
 3218:       my $value='';
 3219:       if($string =~ /^__HASH_REF__/) {
 3220:           ($value, $string)=&str2hashref($string);
 3221:           if(defined($value->{'error'})) {
 3222:               $hash{'error'}='Bad data';
 3223:               return (\%hash, $string);
 3224:           }
 3225:       } elsif($string =~ /^__ARRAY_REF__/) {
 3226:           ($value, $string)=&str2arrayref($string);
 3227:           if($value->[0] eq 'Array reference error') {
 3228:               $hash{'error'}='Bad data';
 3229:               return (\%hash, $string);
 3230:           }
 3231:       } else {
 3232: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3233:       }
 3234:       $string =~ s/^&//;
 3235: 
 3236:       $hash{$key}=$value;
 3237:   }
 3238: 
 3239:   $string =~ s/^__END_HASH_REF__//;
 3240: 
 3241:   return (\%hash, $string);
 3242: }
 3243: 
 3244: sub str2array {
 3245:     my ($string)=@_;
 3246:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3247:     return @$array;
 3248: }
 3249: 
 3250: sub str2arrayref {
 3251:   my ($string) = @_;
 3252:   my @array;
 3253: 
 3254:   if($string !~ /^__ARRAY_REF__/) {
 3255:       if (! ($string eq '' || !defined($string))) {
 3256: 	  $array[0]='Array reference error';
 3257:       }
 3258:       return (\@array, $string);
 3259:   }
 3260: 
 3261:   $string =~ s/^__ARRAY_REF__//;
 3262: 
 3263:   while($string !~ /^__END_ARRAY_REF__/) {
 3264:       my $value='';
 3265:       if($string =~ /^__HASH_REF__/) {
 3266:           ($value, $string)=&str2hashref($string);
 3267:           if(defined($value->{'error'})) {
 3268:               $array[0] ='Array reference error';
 3269:               return (\@array, $string);
 3270:           }
 3271:       } elsif($string =~ /^__ARRAY_REF__/) {
 3272:           ($value, $string)=&str2arrayref($string);
 3273:           if($value->[0] eq 'Array reference error') {
 3274:               $array[0] ='Array reference error';
 3275:               return (\@array, $string);
 3276:           }
 3277:       } else {
 3278: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3279:       }
 3280:       $string =~ s/^&//;
 3281: 
 3282:       push(@array, $value);
 3283:   }
 3284: 
 3285:   $string =~ s/^__END_ARRAY_REF__//;
 3286: 
 3287:   return (\@array, $string);
 3288: }
 3289: 
 3290: # -------------------------------------------------------------------Temp Store
 3291: 
 3292: sub tmpreset {
 3293:   my ($symb,$namespace,$domain,$stuname) = @_;
 3294:   if (!$symb) {
 3295:     $symb=&symbread();
 3296:     if (!$symb) { $symb= $env{'request.url'}; }
 3297:   }
 3298:   $symb=escape($symb);
 3299: 
 3300:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3301:   $namespace=~s/\//\_/g;
 3302:   $namespace=~s/\W//g;
 3303: 
 3304:   if (!$domain) { $domain=$env{'user.domain'}; }
 3305:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3306:   if ($domain eq 'public' && $stuname eq 'public') {
 3307:       $stuname=$ENV{'REMOTE_ADDR'};
 3308:   }
 3309:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3310:   my %hash;
 3311:   if (tie(%hash,'GDBM_File',
 3312: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3313: 	  &GDBM_WRCREAT(),0640)) {
 3314:     foreach my $key (keys %hash) {
 3315:       if ($key=~ /:$symb/) {
 3316: 	delete($hash{$key});
 3317:       }
 3318:     }
 3319:   }
 3320: }
 3321: 
 3322: sub tmpstore {
 3323:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3324: 
 3325:   if (!$symb) {
 3326:     $symb=&symbread();
 3327:     if (!$symb) { $symb= $env{'request.url'}; }
 3328:   }
 3329:   $symb=escape($symb);
 3330: 
 3331:   if (!$namespace) {
 3332:     # I don't think we would ever want to store this for a course.
 3333:     # it seems this will only be used if we don't have a course.
 3334:     #$namespace=$env{'request.course.id'};
 3335:     #if (!$namespace) {
 3336:       $namespace=$env{'request.state'};
 3337:     #}
 3338:   }
 3339:   $namespace=~s/\//\_/g;
 3340:   $namespace=~s/\W//g;
 3341:   if (!$domain) { $domain=$env{'user.domain'}; }
 3342:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3343:   if ($domain eq 'public' && $stuname eq 'public') {
 3344:       $stuname=$ENV{'REMOTE_ADDR'};
 3345:   }
 3346:   my $now=time;
 3347:   my %hash;
 3348:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3349:   if (tie(%hash,'GDBM_File',
 3350: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3351: 	  &GDBM_WRCREAT(),0640)) {
 3352:     $hash{"version:$symb"}++;
 3353:     my $version=$hash{"version:$symb"};
 3354:     my $allkeys=''; 
 3355:     foreach my $key (keys(%$storehash)) {
 3356:       $allkeys.=$key.':';
 3357:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3358:     }
 3359:     $hash{"$version:$symb:timestamp"}=$now;
 3360:     $allkeys.='timestamp';
 3361:     $hash{"$version:keys:$symb"}=$allkeys;
 3362:     if (untie(%hash)) {
 3363:       return 'ok';
 3364:     } else {
 3365:       return "error:$!";
 3366:     }
 3367:   } else {
 3368:     return "error:$!";
 3369:   }
 3370: }
 3371: 
 3372: # -----------------------------------------------------------------Temp Restore
 3373: 
 3374: sub tmprestore {
 3375:   my ($symb,$namespace,$domain,$stuname) = @_;
 3376: 
 3377:   if (!$symb) {
 3378:     $symb=&symbread();
 3379:     if (!$symb) { $symb= $env{'request.url'}; }
 3380:   }
 3381:   $symb=escape($symb);
 3382: 
 3383:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3384: 
 3385:   if (!$domain) { $domain=$env{'user.domain'}; }
 3386:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3387:   if ($domain eq 'public' && $stuname eq 'public') {
 3388:       $stuname=$ENV{'REMOTE_ADDR'};
 3389:   }
 3390:   my %returnhash;
 3391:   $namespace=~s/\//\_/g;
 3392:   $namespace=~s/\W//g;
 3393:   my %hash;
 3394:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3395:   if (tie(%hash,'GDBM_File',
 3396: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3397: 	  &GDBM_READER(),0640)) {
 3398:     my $version=$hash{"version:$symb"};
 3399:     $returnhash{'version'}=$version;
 3400:     my $scope;
 3401:     for ($scope=1;$scope<=$version;$scope++) {
 3402:       my $vkeys=$hash{"$scope:keys:$symb"};
 3403:       my @keys=split(/:/,$vkeys);
 3404:       my $key;
 3405:       $returnhash{"$scope:keys"}=$vkeys;
 3406:       foreach $key (@keys) {
 3407: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3408: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3409:       }
 3410:     }
 3411:     if (!(untie(%hash))) {
 3412:       return "error:$!";
 3413:     }
 3414:   } else {
 3415:     return "error:$!";
 3416:   }
 3417:   return %returnhash;
 3418: }
 3419: 
 3420: # ----------------------------------------------------------------------- Store
 3421: 
 3422: sub store {
 3423:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3424:     my $home='';
 3425: 
 3426:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3427: 
 3428:     $symb=&symbclean($symb);
 3429:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3430: 
 3431:     if (!$domain) { $domain=$env{'user.domain'}; }
 3432:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3433: 
 3434:     &devalidate($symb,$stuname,$domain);
 3435: 
 3436:     $symb=escape($symb);
 3437:     if (!$namespace) { 
 3438:        unless ($namespace=$env{'request.course.id'}) { 
 3439:           return ''; 
 3440:        } 
 3441:     }
 3442:     if (!$home) { $home=$env{'user.home'}; }
 3443: 
 3444:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3445:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3446: 
 3447:     my $namevalue='';
 3448:     foreach my $key (keys(%$storehash)) {
 3449:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3450:     }
 3451:     $namevalue=~s/\&$//;
 3452:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3453:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3454: }
 3455: 
 3456: # -------------------------------------------------------------- Critical Store
 3457: 
 3458: sub cstore {
 3459:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3460:     my $home='';
 3461: 
 3462:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3463: 
 3464:     $symb=&symbclean($symb);
 3465:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3466: 
 3467:     if (!$domain) { $domain=$env{'user.domain'}; }
 3468:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3469: 
 3470:     &devalidate($symb,$stuname,$domain);
 3471: 
 3472:     $symb=escape($symb);
 3473:     if (!$namespace) { 
 3474:        unless ($namespace=$env{'request.course.id'}) { 
 3475:           return ''; 
 3476:        } 
 3477:     }
 3478:     if (!$home) { $home=$env{'user.home'}; }
 3479: 
 3480:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3481:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3482: 
 3483:     my $namevalue='';
 3484:     foreach my $key (keys(%$storehash)) {
 3485:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3486:     }
 3487:     $namevalue=~s/\&$//;
 3488:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3489:     return critical
 3490:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3491: }
 3492: 
 3493: # --------------------------------------------------------------------- Restore
 3494: 
 3495: sub restore {
 3496:     my ($symb,$namespace,$domain,$stuname) = @_;
 3497:     my $home='';
 3498: 
 3499:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3500: 
 3501:     if (!$symb) {
 3502:       unless ($symb=escape(&symbread())) { return ''; }
 3503:     } else {
 3504:       $symb=&escape(&symbclean($symb));
 3505:     }
 3506:     if (!$namespace) { 
 3507:        unless ($namespace=$env{'request.course.id'}) { 
 3508:           return ''; 
 3509:        } 
 3510:     }
 3511:     if (!$domain) { $domain=$env{'user.domain'}; }
 3512:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3513:     if (!$home) { $home=$env{'user.home'}; }
 3514:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3515: 
 3516:     my %returnhash=();
 3517:     foreach my $line (split(/\&/,$answer)) {
 3518: 	my ($name,$value)=split(/\=/,$line);
 3519:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3520:     }
 3521:     my $version;
 3522:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3523:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3524:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3525:        }
 3526:     }
 3527:     return %returnhash;
 3528: }
 3529: 
 3530: # ---------------------------------------------------------- Course Description
 3531: 
 3532: sub coursedescription {
 3533:     my ($courseid,$args)=@_;
 3534:     $courseid=~s/^\///;
 3535:     $courseid=~s/\_/\//g;
 3536:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3537:     my $chome=&homeserver($cnum,$cdomain);
 3538:     my $normalid=$cdomain.'_'.$cnum;
 3539:     # need to always cache even if we get errors otherwise we keep 
 3540:     # trying and trying and trying to get the course description.
 3541:     my %envhash=();
 3542:     my %returnhash=();
 3543:     
 3544:     my $expiretime=600;
 3545:     if ($env{'request.course.id'} eq $normalid) {
 3546: 	$expiretime=120;
 3547:     }
 3548: 
 3549:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3550:     if (!$args->{'freshen_cache'}
 3551: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3552: 	foreach my $key (keys(%env)) {
 3553: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3554: 	    my ($setting) = $1;
 3555: 	    $returnhash{$setting} = $env{$key};
 3556: 	}
 3557: 	return %returnhash;
 3558:     }
 3559: 
 3560:     # get the data agin
 3561:     if (!$args->{'one_time'}) {
 3562: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3563:     }
 3564: 
 3565:     if ($chome ne 'no_host') {
 3566:        %returnhash=&dump('environment',$cdomain,$cnum);
 3567:        if (!exists($returnhash{'con_lost'})) {
 3568:            $returnhash{'home'}= $chome;
 3569: 	   $returnhash{'domain'} = $cdomain;
 3570: 	   $returnhash{'num'} = $cnum;
 3571:            if (!defined($returnhash{'type'})) {
 3572:                $returnhash{'type'} = 'Course';
 3573:            }
 3574:            while (my ($name,$value) = each %returnhash) {
 3575:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3576:            }
 3577:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3578:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3579: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3580:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3581:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3582:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3583:        }
 3584:     }
 3585:     if (!$args->{'one_time'}) {
 3586: 	&appenv(\%envhash);
 3587:     }
 3588:     return %returnhash;
 3589: }
 3590: 
 3591: # -------------------------------------------------See if a user is privileged
 3592: 
 3593: sub privileged {
 3594:     my ($username,$domain)=@_;
 3595:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3596: 			&homeserver($username,$domain));
 3597:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3598:     my $now=time;
 3599:     if ($rolesdump ne '') {
 3600:         foreach my $entry (split(/&/,$rolesdump)) {
 3601: 	    if ($entry!~/^rolesdef_/) {
 3602: 		my ($area,$role)=split(/=/,$entry);
 3603: 		$area=~s/\_\w\w$//;
 3604: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3605: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3606: 		    my $active=1;
 3607: 		    if ($tend) {
 3608: 			if ($tend<$now) { $active=0; }
 3609: 		    }
 3610: 		    if ($tstart) {
 3611: 			if ($tstart>$now) { $active=0; }
 3612: 		    }
 3613: 		    if ($active) { return 1; }
 3614: 		}
 3615: 	    }
 3616: 	}
 3617:     }
 3618:     return 0;
 3619: }
 3620: 
 3621: # -------------------------------------------------------- Get user privileges
 3622: 
 3623: sub rolesinit {
 3624:     my ($domain,$username,$authhost)=@_;
 3625:     my %userroles;
 3626:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3627:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3628:     my %allroles=();
 3629:     my %allgroups=();   
 3630:     my $now=time;
 3631:     %userroles = ('user.login.time' => $now);
 3632:     my $group_privs;
 3633: 
 3634:     if ($rolesdump ne '') {
 3635:         foreach my $entry (split(/&/,$rolesdump)) {
 3636: 	  if ($entry!~/^rolesdef_/) {
 3637:             my ($area,$role)=split(/=/,$entry);
 3638: 	    $area=~s/\_\w\w$//;
 3639:             my ($trole,$tend,$tstart,$group_privs);
 3640: 	    if ($role=~/^cr/) { 
 3641: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3642: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3643: 		    ($tend,$tstart)=split('_',$trest);
 3644: 		} else {
 3645: 		    $trole=$role;
 3646: 		}
 3647:             } elsif ($role =~ m|^gr/|) {
 3648:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3649:                 ($trole,$group_privs) = split(/\//,$trole);
 3650:                 $group_privs = &unescape($group_privs);
 3651: 	    } else {
 3652: 		($trole,$tend,$tstart)=split(/_/,$role);
 3653: 	    }
 3654: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3655: 					 $username);
 3656: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3657:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3658:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3659:             if (($area ne '') && ($trole ne '')) {
 3660: 		my $spec=$trole.'.'.$area;
 3661: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3662: 		if ($trole =~ /^cr\//) {
 3663:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3664:                 } elsif ($trole eq 'gr') {
 3665:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3666: 		} else {
 3667:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3668: 		}
 3669:             }
 3670:           }
 3671:         }
 3672:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3673:         $userroles{'user.adv'}    = $adv;
 3674: 	$userroles{'user.author'} = $author;
 3675:         $env{'user.adv'}=$adv;
 3676:     }
 3677:     return \%userroles;  
 3678: }
 3679: 
 3680: sub set_arearole {
 3681:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3682: # log the associated role with the area
 3683:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3684:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3685: }
 3686: 
 3687: sub custom_roleprivs {
 3688:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3689:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3690:     my $homsvr=homeserver($rauthor,$rdomain);
 3691:     if (&hostname($homsvr) ne '') {
 3692:         my ($rdummy,$roledef)=
 3693:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3694:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3695:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3696:             if (defined($syspriv)) {
 3697:                 $$allroles{'cm./'}.=':'.$syspriv;
 3698:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3699:             }
 3700:             if ($tdomain ne '') {
 3701:                 if (defined($dompriv)) {
 3702:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3703:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3704:                 }
 3705:                 if (($trest ne '') && (defined($coursepriv))) {
 3706:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3707:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3708:                 }
 3709:             }
 3710:         }
 3711:     }
 3712: }
 3713: 
 3714: sub group_roleprivs {
 3715:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3716:     my $access = 1;
 3717:     my $now = time;
 3718:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3719:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3720:     if ($access) {
 3721:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3722:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3723:     }
 3724: }
 3725: 
 3726: sub standard_roleprivs {
 3727:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3728:     if (defined($pr{$trole.':s'})) {
 3729:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3730:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3731:     }
 3732:     if ($tdomain ne '') {
 3733:         if (defined($pr{$trole.':d'})) {
 3734:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3735:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3736:         }
 3737:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3738:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3739:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3740:         }
 3741:     }
 3742: }
 3743: 
 3744: sub set_userprivs {
 3745:     my ($userroles,$allroles,$allgroups) = @_; 
 3746:     my $author=0;
 3747:     my $adv=0;
 3748:     my %grouproles = ();
 3749:     if (keys(%{$allgroups}) > 0) {
 3750:         foreach my $role (keys %{$allroles}) {
 3751:             my ($trole,$area,$sec,$extendedarea);
 3752:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3753:                 $trole = $1;
 3754:                 $area = $2;
 3755:                 $sec = $3;
 3756:                 $extendedarea = $area.$sec;
 3757:                 if (exists($$allgroups{$area})) {
 3758:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3759:                         my $spec = $trole.'.'.$extendedarea;
 3760:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3761:                                                 $$allgroups{$area}{$group};
 3762:                     }
 3763:                 }
 3764:             }
 3765:         }
 3766:     }
 3767:     foreach my $group (keys(%grouproles)) {
 3768:         $$allroles{$group} = $grouproles{$group};
 3769:     }
 3770:     foreach my $role (keys(%{$allroles})) {
 3771:         my %thesepriv;
 3772:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3773:         foreach my $item (split(/:/,$$allroles{$role})) {
 3774:             if ($item ne '') {
 3775:                 my ($privilege,$restrictions)=split(/&/,$item);
 3776:                 if ($restrictions eq '') {
 3777:                     $thesepriv{$privilege}='F';
 3778:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3779:                     $thesepriv{$privilege}.=$restrictions;
 3780:                 }
 3781:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3782:             }
 3783:         }
 3784:         my $thesestr='';
 3785:         foreach my $priv (keys(%thesepriv)) {
 3786: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3787: 	}
 3788:         $userroles->{'user.priv.'.$role} = $thesestr;
 3789:     }
 3790:     return ($author,$adv);
 3791: }
 3792: 
 3793: # --------------------------------------------------------------- get interface
 3794: 
 3795: sub get {
 3796:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3797:    my $items='';
 3798:    foreach my $item (@$storearr) {
 3799:        $items.=&escape($item).'&';
 3800:    }
 3801:    $items=~s/\&$//;
 3802:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3803:    if (!$uname) { $uname=$env{'user.name'}; }
 3804:    my $uhome=&homeserver($uname,$udomain);
 3805: 
 3806:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3807:    my @pairs=split(/\&/,$rep);
 3808:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3809:      return @pairs;
 3810:    }
 3811:    my %returnhash=();
 3812:    my $i=0;
 3813:    foreach my $item (@$storearr) {
 3814:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3815:       $i++;
 3816:    }
 3817:    return %returnhash;
 3818: }
 3819: 
 3820: # --------------------------------------------------------------- del interface
 3821: 
 3822: sub del {
 3823:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3824:    my $items='';
 3825:    foreach my $item (@$storearr) {
 3826:        $items.=&escape($item).'&';
 3827:    }
 3828:    $items=~s/\&$//;
 3829:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3830:    if (!$uname) { $uname=$env{'user.name'}; }
 3831:    my $uhome=&homeserver($uname,$udomain);
 3832: 
 3833:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3834: }
 3835: 
 3836: # -------------------------------------------------------------- dump interface
 3837: 
 3838: sub dump {
 3839:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3840:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3841:     if (!$uname) { $uname=$env{'user.name'}; }
 3842:     my $uhome=&homeserver($uname,$udomain);
 3843:     if ($regexp) {
 3844: 	$regexp=&escape($regexp);
 3845:     } else {
 3846: 	$regexp='.';
 3847:     }
 3848:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3849:     my @pairs=split(/\&/,$rep);
 3850:     my %returnhash=();
 3851:     foreach my $item (@pairs) {
 3852: 	my ($key,$value)=split(/=/,$item,2);
 3853: 	$key = &unescape($key);
 3854: 	next if ($key =~ /^error: 2 /);
 3855: 	$returnhash{$key}=&thaw_unescape($value);
 3856:     }
 3857:     return %returnhash;
 3858: }
 3859: 
 3860: # --------------------------------------------------------- dumpstore interface
 3861: 
 3862: sub dumpstore {
 3863:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3864:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3865:    if (!$uname) { $uname=$env{'user.name'}; }
 3866:    my $uhome=&homeserver($uname,$udomain);
 3867:    if ($regexp) {
 3868:        $regexp=&escape($regexp);
 3869:    } else {
 3870:        $regexp='.';
 3871:    }
 3872:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3873:    my @pairs=split(/\&/,$rep);
 3874:    my %returnhash=();
 3875:    foreach my $item (@pairs) {
 3876:        my ($key,$value)=split(/=/,$item,2);
 3877:        next if ($key =~ /^error: 2 /);
 3878:        $returnhash{$key}=&thaw_unescape($value);
 3879:    }
 3880:    return %returnhash;
 3881: }
 3882: 
 3883: # -------------------------------------------------------------- keys interface
 3884: 
 3885: sub getkeys {
 3886:    my ($namespace,$udomain,$uname)=@_;
 3887:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3888:    if (!$uname) { $uname=$env{'user.name'}; }
 3889:    my $uhome=&homeserver($uname,$udomain);
 3890:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3891:    my @keyarray=();
 3892:    foreach my $key (split(/\&/,$rep)) {
 3893:       next if ($key =~ /^error: 2 /);
 3894:       push(@keyarray,&unescape($key));
 3895:    }
 3896:    return @keyarray;
 3897: }
 3898: 
 3899: # --------------------------------------------------------------- currentdump
 3900: sub currentdump {
 3901:    my ($courseid,$sdom,$sname)=@_;
 3902:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3903:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3904:    $sname    = $env{'user.name'}         if (! defined($sname));
 3905:    my $uhome = &homeserver($sname,$sdom);
 3906:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3907:    return if ($rep =~ /^(error:|no_such_host)/);
 3908:    #
 3909:    my %returnhash=();
 3910:    #
 3911:    if ($rep eq "unknown_cmd") { 
 3912:        # an old lond will not know currentdump
 3913:        # Do a dump and make it look like a currentdump
 3914:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3915:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3916:        my %hash = @tmp;
 3917:        @tmp=();
 3918:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3919:    } else {
 3920:        my @pairs=split(/\&/,$rep);
 3921:        foreach my $pair (@pairs) {
 3922:            my ($key,$value)=split(/=/,$pair,2);
 3923:            my ($symb,$param) = split(/:/,$key);
 3924:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3925:                                                         &thaw_unescape($value);
 3926:        }
 3927:    }
 3928:    return %returnhash;
 3929: }
 3930: 
 3931: sub convert_dump_to_currentdump{
 3932:     my %hash = %{shift()};
 3933:     my %returnhash;
 3934:     # Code ripped from lond, essentially.  The only difference
 3935:     # here is the unescaping done by lonnet::dump().  Conceivably
 3936:     # we might run in to problems with parameter names =~ /^v\./
 3937:     while (my ($key,$value) = each(%hash)) {
 3938:         my ($v,$symb,$param) = split(/:/,$key);
 3939: 	$symb  = &unescape($symb);
 3940: 	$param = &unescape($param);
 3941:         next if ($v eq 'version' || $symb eq 'keys');
 3942:         next if (exists($returnhash{$symb}) &&
 3943:                  exists($returnhash{$symb}->{$param}) &&
 3944:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3945:         $returnhash{$symb}->{$param}=$value;
 3946:         $returnhash{$symb}->{'v.'.$param}=$v;
 3947:     }
 3948:     #
 3949:     # Remove all of the keys in the hashes which keep track of
 3950:     # the version of the parameter.
 3951:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3952:         # use a foreach because we are going to delete from the hash.
 3953:         foreach my $key (keys(%$param_hash)) {
 3954:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3955:         }
 3956:     }
 3957:     return \%returnhash;
 3958: }
 3959: 
 3960: # ------------------------------------------------------ critical inc interface
 3961: 
 3962: sub cinc {
 3963:     return &inc(@_,'critical');
 3964: }
 3965: 
 3966: # --------------------------------------------------------------- inc interface
 3967: 
 3968: sub inc {
 3969:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3970:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3971:     if (!$uname) { $uname=$env{'user.name'}; }
 3972:     my $uhome=&homeserver($uname,$udomain);
 3973:     my $items='';
 3974:     if (! ref($store)) {
 3975:         # got a single value, so use that instead
 3976:         $items = &escape($store).'=&';
 3977:     } elsif (ref($store) eq 'SCALAR') {
 3978:         $items = &escape($$store).'=&';        
 3979:     } elsif (ref($store) eq 'ARRAY') {
 3980:         $items = join('=&',map {&escape($_);} @{$store});
 3981:     } elsif (ref($store) eq 'HASH') {
 3982:         while (my($key,$value) = each(%{$store})) {
 3983:             $items.= &escape($key).'='.&escape($value).'&';
 3984:         }
 3985:     }
 3986:     $items=~s/\&$//;
 3987:     if ($critical) {
 3988: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3989:     } else {
 3990: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3991:     }
 3992: }
 3993: 
 3994: # --------------------------------------------------------------- put interface
 3995: 
 3996: sub put {
 3997:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3999:    if (!$uname) { $uname=$env{'user.name'}; }
 4000:    my $uhome=&homeserver($uname,$udomain);
 4001:    my $items='';
 4002:    foreach my $item (keys(%$storehash)) {
 4003:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4004:    }
 4005:    $items=~s/\&$//;
 4006:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4007: }
 4008: 
 4009: # ------------------------------------------------------------ newput interface
 4010: 
 4011: sub newput {
 4012:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4014:    if (!$uname) { $uname=$env{'user.name'}; }
 4015:    my $uhome=&homeserver($uname,$udomain);
 4016:    my $items='';
 4017:    foreach my $key (keys(%$storehash)) {
 4018:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4019:    }
 4020:    $items=~s/\&$//;
 4021:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4022: }
 4023: 
 4024: # ---------------------------------------------------------  putstore interface
 4025: 
 4026: sub putstore {
 4027:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4028:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4029:    if (!$uname) { $uname=$env{'user.name'}; }
 4030:    my $uhome=&homeserver($uname,$udomain);
 4031:    my $items='';
 4032:    foreach my $key (keys(%$storehash)) {
 4033:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4034:    }
 4035:    $items=~s/\&$//;
 4036:    my $esc_symb=&escape($symb);
 4037:    my $esc_v=&escape($version);
 4038:    my $reply =
 4039:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4040: 	      $uhome);
 4041:    if ($reply eq 'unknown_cmd') {
 4042:        # gfall back to way things use to be done
 4043:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4044: 			    $uname);
 4045:    }
 4046:    return $reply;
 4047: }
 4048: 
 4049: sub old_putstore {
 4050:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4051:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4052:     if (!$uname) { $uname=$env{'user.name'}; }
 4053:     my $uhome=&homeserver($uname,$udomain);
 4054:     my %newstorehash;
 4055:     foreach my $item (keys(%$storehash)) {
 4056: 	my $key = $version.':'.&escape($symb).':'.$item;
 4057: 	$newstorehash{$key} = $storehash->{$item};
 4058:     }
 4059:     my $items='';
 4060:     my %allitems = ();
 4061:     foreach my $item (keys(%newstorehash)) {
 4062: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4063: 	    my $key = $1.':keys:'.$2;
 4064: 	    $allitems{$key} .= $3.':';
 4065: 	}
 4066: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4067:     }
 4068:     foreach my $item (keys(%allitems)) {
 4069: 	$allitems{$item} =~ s/\:$//;
 4070: 	$items.= $item.'='.$allitems{$item}.'&';
 4071:     }
 4072:     $items=~s/\&$//;
 4073:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4074: }
 4075: 
 4076: # ------------------------------------------------------ critical put interface
 4077: 
 4078: sub cput {
 4079:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4080:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4081:    if (!$uname) { $uname=$env{'user.name'}; }
 4082:    my $uhome=&homeserver($uname,$udomain);
 4083:    my $items='';
 4084:    foreach my $item (keys(%$storehash)) {
 4085:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4086:    }
 4087:    $items=~s/\&$//;
 4088:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4089: }
 4090: 
 4091: # -------------------------------------------------------------- eget interface
 4092: 
 4093: sub eget {
 4094:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4095:    my $items='';
 4096:    foreach my $item (@$storearr) {
 4097:        $items.=&escape($item).'&';
 4098:    }
 4099:    $items=~s/\&$//;
 4100:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4101:    if (!$uname) { $uname=$env{'user.name'}; }
 4102:    my $uhome=&homeserver($uname,$udomain);
 4103:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4104:    my @pairs=split(/\&/,$rep);
 4105:    my %returnhash=();
 4106:    my $i=0;
 4107:    foreach my $item (@$storearr) {
 4108:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4109:       $i++;
 4110:    }
 4111:    return %returnhash;
 4112: }
 4113: 
 4114: # ------------------------------------------------------------ tmpput interface
 4115: sub tmpput {
 4116:     my ($storehash,$server,$context)=@_;
 4117:     my $items='';
 4118:     foreach my $item (keys(%$storehash)) {
 4119: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4120:     }
 4121:     $items=~s/\&$//;
 4122:     if (defined($context)) {
 4123:         $items .= ':'.&escape($context);
 4124:     }
 4125:     return &reply("tmpput:$items",$server);
 4126: }
 4127: 
 4128: # ------------------------------------------------------------ tmpget interface
 4129: sub tmpget {
 4130:     my ($token,$server)=@_;
 4131:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4132:     my $rep=&reply("tmpget:$token",$server);
 4133:     my %returnhash;
 4134:     foreach my $item (split(/\&/,$rep)) {
 4135: 	my ($key,$value)=split(/=/,$item);
 4136:         next if ($key =~ /^error: 2 /);
 4137: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4138:     }
 4139:     return %returnhash;
 4140: }
 4141: 
 4142: # ------------------------------------------------------------ tmpget interface
 4143: sub tmpdel {
 4144:     my ($token,$server)=@_;
 4145:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4146:     return &reply("tmpdel:$token",$server);
 4147: }
 4148: 
 4149: # -------------------------------------------------- portfolio access checking
 4150: 
 4151: sub portfolio_access {
 4152:     my ($requrl) = @_;
 4153:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4154:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4155:     if ($result) {
 4156:         my %setters;
 4157:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4158:             my ($startblock,$endblock) =
 4159:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4160:             if ($startblock && $endblock) {
 4161:                 return 'B';
 4162:             }
 4163:         } else {
 4164:             my ($startblock,$endblock) =
 4165:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4166:             if ($startblock && $endblock) {
 4167:                 return 'B';
 4168:             }
 4169:         }
 4170:     }
 4171:     if ($result eq 'ok') {
 4172:        return 'F';
 4173:     } elsif ($result =~ /^[^:]+:guest_/) {
 4174:        return 'A';
 4175:     }
 4176:     return '';
 4177: }
 4178: 
 4179: sub get_portfolio_access {
 4180:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4181: 
 4182:     if (!ref($access_hash)) {
 4183: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4184: 	my %access_controls = &get_access_controls($current_perms,$group,
 4185: 						   $file_name);
 4186: 	$access_hash = $access_controls{$file_name};
 4187:     }
 4188: 
 4189:     my ($public,$guest,@domains,@users,@courses,@groups);
 4190:     my $now = time;
 4191:     if (ref($access_hash) eq 'HASH') {
 4192:         foreach my $key (keys(%{$access_hash})) {
 4193:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4194:             if ($start > $now) {
 4195:                 next;
 4196:             }
 4197:             if ($end && $end<$now) {
 4198:                 next;
 4199:             }
 4200:             if ($scope eq 'public') {
 4201:                 $public = $key;
 4202:                 last;
 4203:             } elsif ($scope eq 'guest') {
 4204:                 $guest = $key;
 4205:             } elsif ($scope eq 'domains') {
 4206:                 push(@domains,$key);
 4207:             } elsif ($scope eq 'users') {
 4208:                 push(@users,$key);
 4209:             } elsif ($scope eq 'course') {
 4210:                 push(@courses,$key);
 4211:             } elsif ($scope eq 'group') {
 4212:                 push(@groups,$key);
 4213:             }
 4214:         }
 4215:         if ($public) {
 4216:             return 'ok';
 4217:         }
 4218:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4219:             if ($guest) {
 4220:                 return $guest;
 4221:             }
 4222:         } else {
 4223:             if (@domains > 0) {
 4224:                 foreach my $domkey (@domains) {
 4225:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4226:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4227:                             return 'ok';
 4228:                         }
 4229:                     }
 4230:                 }
 4231:             }
 4232:             if (@users > 0) {
 4233:                 foreach my $userkey (@users) {
 4234:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4235:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4236:                             if (ref($item) eq 'HASH') {
 4237:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4238:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4239:                                     return 'ok';
 4240:                                 }
 4241:                             }
 4242:                         }
 4243:                     } 
 4244:                 }
 4245:             }
 4246:             my %roleshash;
 4247:             my @courses_and_groups = @courses;
 4248:             push(@courses_and_groups,@groups); 
 4249:             if (@courses_and_groups > 0) {
 4250:                 my (%allgroups,%allroles); 
 4251:                 my ($start,$end,$role,$sec,$group);
 4252:                 foreach my $envkey (%env) {
 4253:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4254:                         my $cid = $2.'_'.$3; 
 4255:                         if ($1 eq 'gr') {
 4256:                             $group = $4;
 4257:                             $allgroups{$cid}{$group} = $env{$envkey};
 4258:                         } else {
 4259:                             if ($4 eq '') {
 4260:                                 $sec = 'none';
 4261:                             } else {
 4262:                                 $sec = $4;
 4263:                             }
 4264:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4265:                         }
 4266:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4267:                         my $cid = $2.'_'.$3;
 4268:                         if ($4 eq '') {
 4269:                             $sec = 'none';
 4270:                         } else {
 4271:                             $sec = $4;
 4272:                         }
 4273:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4274:                     }
 4275:                 }
 4276:                 if (keys(%allroles) == 0) {
 4277:                     return;
 4278:                 }
 4279:                 foreach my $key (@courses_and_groups) {
 4280:                     my %content = %{$$access_hash{$key}};
 4281:                     my $cnum = $content{'number'};
 4282:                     my $cdom = $content{'domain'};
 4283:                     my $cid = $cdom.'_'.$cnum;
 4284:                     if (!exists($allroles{$cid})) {
 4285:                         next;
 4286:                     }    
 4287:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4288:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4289:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4290:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4291:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4292:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4293:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4294:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4295:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4296:                                         if (grep/^all$/,@sections) {
 4297:                                             return 'ok';
 4298:                                         } else {
 4299:                                             if (grep/^$sec$/,@sections) {
 4300:                                                 return 'ok';
 4301:                                             }
 4302:                                         }
 4303:                                     }
 4304:                                 }
 4305:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4306:                                     if (grep/^none$/,@groups) {
 4307:                                         return 'ok';
 4308:                                     }
 4309:                                 } else {
 4310:                                     if (grep/^all$/,@groups) {
 4311:                                         return 'ok';
 4312:                                     } 
 4313:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4314:                                         if (grep/^$group$/,@groups) {
 4315:                                             return 'ok';
 4316:                                         }
 4317:                                     }
 4318:                                 } 
 4319:                             }
 4320:                         }
 4321:                     }
 4322:                 }
 4323:             }
 4324:             if ($guest) {
 4325:                 return $guest;
 4326:             }
 4327:         }
 4328:     }
 4329:     return;
 4330: }
 4331: 
 4332: sub course_group_datechecker {
 4333:     my ($dates,$now,$status) = @_;
 4334:     my ($start,$end) = split(/\./,$dates);
 4335:     if (!$start && !$end) {
 4336:         return 'ok';
 4337:     }
 4338:     if (grep/^active$/,@{$status}) {
 4339:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4340:             return 'ok';
 4341:         }
 4342:     }
 4343:     if (grep/^previous$/,@{$status}) {
 4344:         if ($end > $now ) {
 4345:             return 'ok';
 4346:         }
 4347:     }
 4348:     if (grep/^future$/,@{$status}) {
 4349:         if ($start > $now) {
 4350:             return 'ok';
 4351:         }
 4352:     }
 4353:     return; 
 4354: }
 4355: 
 4356: sub parse_portfolio_url {
 4357:     my ($url) = @_;
 4358: 
 4359:     my ($type,$udom,$unum,$group,$file_name);
 4360:     
 4361:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4362: 	$type = 1;
 4363:         $udom = $1;
 4364:         $unum = $2;
 4365:         $file_name = $3;
 4366:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4367: 	$type = 2;
 4368:         $udom = $1;
 4369:         $unum = $2;
 4370:         $group = $3;
 4371:         $file_name = $3.'/'.$4;
 4372:     }
 4373:     if (wantarray) {
 4374: 	return ($type,$udom,$unum,$file_name,$group);
 4375:     }
 4376:     return $type;
 4377: }
 4378: 
 4379: sub is_portfolio_url {
 4380:     my ($url) = @_;
 4381:     return scalar(&parse_portfolio_url($url));
 4382: }
 4383: 
 4384: sub is_portfolio_file {
 4385:     my ($file) = @_;
 4386:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4387:         return 1;
 4388:     }
 4389:     return;
 4390: }
 4391: 
 4392: sub usertools_access {
 4393:     my ($uname,$udom,$tool,$action) = @_;
 4394:     my $access;
 4395:     my %tools = (
 4396:                   aboutme   => 1,
 4397:                   blog      => 1,
 4398:                   portfolio => 1,
 4399:                 );
 4400:     return if (!defined($tools{$tool}));
 4401: 
 4402:     if ((!defined($udom)) || (!defined($uname))) {
 4403:         $udom = $env{'user.domain'};
 4404:         $uname = $env{'user.name'};
 4405:     }
 4406: 
 4407:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4408:         if ($action ne 'reload') {
 4409:             return $env{'environment.availabletools.'.$tool};
 4410:         }
 4411:     }
 4412: 
 4413:     my ($toolstatus,$inststatus);
 4414: 
 4415:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4416:         $toolstatus = $env{'environment.tools.'.$tool};
 4417:         $inststatus = $env{'environment.inststatus'};
 4418:     } else {
 4419:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4420:         $toolstatus = $userenv{'tools.'.$tool};
 4421:         $inststatus = $userenv{'inststatus'};
 4422:     }
 4423: 
 4424:     if ($toolstatus ne '') {
 4425:         if ($toolstatus) {
 4426:             $access = 1;
 4427:         } else {
 4428:             $access = 0;
 4429:         }
 4430:         return $access;
 4431:     }
 4432: 
 4433:     my $is_adv = &is_advanced_user($udom,$uname);
 4434:     my %domdef = &get_domain_defaults($udom);
 4435:     if (ref($domdef{$tool}) eq 'HASH') {
 4436:         if ($is_adv) {
 4437:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4438:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4439:                     $access = 1;
 4440:                 } else {
 4441:                     $access = 0;
 4442:                 }
 4443:                 return $access;
 4444:             }
 4445:         }
 4446:         if ($inststatus ne '') {
 4447:             my ($hasaccess,$hasnoaccess);
 4448:             foreach my $affiliation (split(/:/,$inststatus)) {
 4449:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4450:                     if ($domdef{$tool}{$affiliation}) {
 4451:                         $hasaccess = 1;
 4452:                     } else {
 4453:                         $hasnoaccess = 1;
 4454:                     }
 4455:                 }
 4456:             }
 4457:             if ($hasaccess || $hasnoaccess) {
 4458:                 if ($hasaccess) {
 4459:                     $access = 1;
 4460:                 } elsif ($hasnoaccess) {
 4461:                     $access = 0; 
 4462:                 }
 4463:                 return $access;
 4464:             }
 4465:         } else {
 4466:             if ($domdef{$tool}{'default'} ne '') {
 4467:                 if ($domdef{$tool}{'default'}) {
 4468:                     $access = 1;
 4469:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4470:                     $access = 0;
 4471:                 }
 4472:                 return $access;
 4473:             }
 4474:         }
 4475:     } else {
 4476:         $access = 1;
 4477:         return $access;
 4478:     }
 4479: }
 4480: 
 4481: sub is_advanced_user {
 4482:     my ($udom,$uname) = @_;
 4483:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4484:     my %allroles;
 4485:     my $is_adv;
 4486:     foreach my $role (keys(%roleshash)) {
 4487:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4488:         my $area = '/'.$tdomain.'/'.$trest;
 4489:         if ($sec ne '') {
 4490:             $area .= '/'.$sec;
 4491:         }
 4492:         if (($area ne '') && ($trole ne '')) {
 4493:             my $spec=$trole.'.'.$area;
 4494:             if ($trole =~ /^cr\//) {
 4495:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4496:             } elsif ($trole ne 'gr') {
 4497:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4498:             }
 4499:         }
 4500:     }
 4501:     foreach my $role (keys(%allroles)) {
 4502:         last if ($is_adv);
 4503:         foreach my $item (split(/:/,$allroles{$role})) {
 4504:             if ($item ne '') {
 4505:                 my ($privilege,$restrictions)=split(/&/,$item);
 4506:                 if ($privilege eq 'adv') {
 4507:                     $is_adv = 1;
 4508:                     last;
 4509:                 }
 4510:             }
 4511:         }
 4512:     }
 4513:     return $is_adv;
 4514: }
 4515: 
 4516: # ---------------------------------------------- Custom access rule evaluation
 4517: 
 4518: sub customaccess {
 4519:     my ($priv,$uri)=@_;
 4520:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4521:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4522:     $udom = &LONCAPA::clean_domain($udom);
 4523:     $ucrs = &LONCAPA::clean_username($ucrs);
 4524:     my $access=0;
 4525:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4526: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4527: 	if ($type eq 'user') {
 4528: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4529: 		my ($tdom,$tuname)=split(m{/},$scope);
 4530: 		if ($tdom) {
 4531: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4532: 		}
 4533: 		if ($tuname) {
 4534: 		    if ($tuname ne $env{'user.name'}) { next; }
 4535: 		}
 4536: 		$access=($effect eq 'allow');
 4537: 		last;
 4538: 	    }
 4539: 	} else {
 4540: 	    if ($role) {
 4541: 		if ($role ne $urole) { next; }
 4542: 	    }
 4543: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4544: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4545: 		if ($tdom) {
 4546: 		    if ($tdom ne $udom) { next; }
 4547: 		}
 4548: 		if ($tcrs) {
 4549: 		    if ($tcrs ne $ucrs) { next; }
 4550: 		}
 4551: 		if ($tsec) {
 4552: 		    if ($tsec ne $usec) { next; }
 4553: 		}
 4554: 		$access=($effect eq 'allow');
 4555: 		last;
 4556: 	    }
 4557: 	    if ($realm eq '' && $role eq '') {
 4558: 		$access=($effect eq 'allow');
 4559: 	    }
 4560: 	}
 4561:     }
 4562:     return $access;
 4563: }
 4564: 
 4565: # ------------------------------------------------- Check for a user privilege
 4566: 
 4567: sub allowed {
 4568:     my ($priv,$uri,$symb,$role)=@_;
 4569:     my $ver_orguri=$uri;
 4570:     $uri=&deversion($uri);
 4571:     my $orguri=$uri;
 4572:     $uri=&declutter($uri);
 4573: 
 4574:     if ($priv eq 'evb') {
 4575: # Evade communication block restrictions for specified role in a course
 4576:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4577:             return $1;
 4578:         } else {
 4579:             return;
 4580:         }
 4581:     }
 4582: 
 4583:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4584: # Free bre access to adm and meta resources
 4585:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4586: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4587: 	&& ($priv eq 'bre')) {
 4588: 	return 'F';
 4589:     }
 4590: 
 4591: # Free bre access to user's own portfolio contents
 4592:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4593:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4594: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4595:         my %setters;
 4596:         my ($startblock,$endblock) = 
 4597:             &Apache::loncommon::blockcheck(\%setters,'port');
 4598:         if ($startblock && $endblock) {
 4599:             return 'B';
 4600:         } else {
 4601:             return 'F';
 4602:         }
 4603:     }
 4604: 
 4605: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4606:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4607:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4608:         if (exists($env{'request.course.id'})) {
 4609:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4610:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4611:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4612:                 my $courseprivid=$env{'request.course.id'};
 4613:                 $courseprivid=~s/\_/\//;
 4614:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4615:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4616:                     return $1; 
 4617:                 } else {
 4618:                     if ($env{'request.course.sec'}) {
 4619:                         $courseprivid.='/'.$env{'request.course.sec'};
 4620:                     }
 4621:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4622:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4623:                         return $2;
 4624:                     }
 4625:                 }
 4626:             }
 4627:         }
 4628:     }
 4629: 
 4630: # Free bre to public access
 4631: 
 4632:     if ($priv eq 'bre') {
 4633:         my $copyright=&metadata($uri,'copyright');
 4634: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4635:            return 'F'; 
 4636:         }
 4637:         if ($copyright eq 'priv') {
 4638:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4639: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4640: 		return '';
 4641:             }
 4642:         }
 4643:         if ($copyright eq 'domain') {
 4644:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4645: 	    unless (($env{'user.domain'} eq $1) ||
 4646:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4647: 		return '';
 4648:             }
 4649:         }
 4650:         if ($env{'request.role'}=~ /li\.\//) {
 4651:             # Library role, so allow browsing of resources in this domain.
 4652:             return 'F';
 4653:         }
 4654:         if ($copyright eq 'custom') {
 4655: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4656:         }
 4657:     }
 4658:     # Domain coordinator is trying to create a course
 4659:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4660:         # uri is the requested domain in this case.
 4661:         # comparison to 'request.role.domain' shows if the user has selected
 4662:         # a role of dc for the domain in question.
 4663:         return 'F' if ($uri eq $env{'request.role.domain'});
 4664:     }
 4665: 
 4666:     my $thisallowed='';
 4667:     my $statecond=0;
 4668:     my $courseprivid='';
 4669: 
 4670: # Course
 4671: 
 4672:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4673:        $thisallowed.=$1;
 4674:     }
 4675: 
 4676: # Domain
 4677: 
 4678:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4679:        =~/\Q$priv\E\&([^\:]*)/) {
 4680:        $thisallowed.=$1;
 4681:     }
 4682: 
 4683: # Course: uri itself is a course
 4684:     my $courseuri=$uri;
 4685:     $courseuri=~s/\_(\d)/\/$1/;
 4686:     $courseuri=~s/^([^\/])/\/$1/;
 4687: 
 4688:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4689:        =~/\Q$priv\E\&([^\:]*)/) {
 4690:        $thisallowed.=$1;
 4691:     }
 4692: 
 4693: # URI is an uploaded document for this course, default permissions don't matter
 4694: # not allowing 'edit' access (editupload) to uploaded course docs
 4695:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4696: 	$thisallowed='';
 4697:         my ($match)=&is_on_map($uri);
 4698:         if ($match) {
 4699:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4700:                   =~/\Q$priv\E\&([^\:]*)/) {
 4701:                 $thisallowed.=$1;
 4702:             }
 4703:         } else {
 4704:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4705:             if ($refuri) {
 4706:                 if ($refuri =~ m|^/adm/|) {
 4707:                     $thisallowed='F';
 4708:                 } else {
 4709:                     $refuri=&declutter($refuri);
 4710:                     my ($match) = &is_on_map($refuri);
 4711:                     if ($match) {
 4712:                         $thisallowed='F';
 4713:                     }
 4714:                 }
 4715:             }
 4716:         }
 4717:     }
 4718: 
 4719:     if ($priv eq 'bre'
 4720: 	&& $thisallowed ne 'F' 
 4721: 	&& $thisallowed ne '2'
 4722: 	&& &is_portfolio_url($uri)) {
 4723: 	$thisallowed = &portfolio_access($uri);
 4724:     }
 4725:     
 4726: # Full access at system, domain or course-wide level? Exit.
 4727:     if ($thisallowed=~/F/) {
 4728: 	return 'F';
 4729:     }
 4730: 
 4731: # If this is generating or modifying users, exit with special codes
 4732: 
 4733:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4734: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4735: 	    my ($audom,$auname)=split('/',$uri);
 4736: # no author name given, so this just checks on the general right to make a co-author in this domain
 4737: 	    unless ($auname) { return $thisallowed; }
 4738: # an author name is given, so we are about to actually make a co-author for a certain account
 4739: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4740: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4741: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4742: 	}
 4743: 	return $thisallowed;
 4744:     }
 4745: #
 4746: # Gathered so far: system, domain and course wide privileges
 4747: #
 4748: # Course: See if uri or referer is an individual resource that is part of 
 4749: # the course
 4750: 
 4751:     if ($env{'request.course.id'}) {
 4752: 
 4753:        $courseprivid=$env{'request.course.id'};
 4754:        if ($env{'request.course.sec'}) {
 4755:           $courseprivid.='/'.$env{'request.course.sec'};
 4756:        }
 4757:        $courseprivid=~s/\_/\//;
 4758:        my $checkreferer=1;
 4759:        my ($match,$cond)=&is_on_map($uri);
 4760:        if ($match) {
 4761:            $statecond=$cond;
 4762:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4763:                =~/\Q$priv\E\&([^\:]*)/) {
 4764:                $thisallowed.=$1;
 4765:                $checkreferer=0;
 4766:            }
 4767:        }
 4768:        
 4769:        if ($checkreferer) {
 4770: 	  my $refuri=$env{'httpref.'.$orguri};
 4771:             unless ($refuri) {
 4772:                 foreach my $key (keys(%env)) {
 4773: 		    if ($key=~/^httpref\..*\*/) {
 4774: 			my $pattern=$key;
 4775:                         $pattern=~s/^httpref\.\/res\///;
 4776:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4777:                         $pattern=~s/\//\\\//g;
 4778:                         if ($orguri=~/$pattern/) {
 4779: 			    $refuri=$env{$key};
 4780:                         }
 4781:                     }
 4782:                 }
 4783:             }
 4784: 
 4785:          if ($refuri) { 
 4786: 	  $refuri=&declutter($refuri);
 4787:           my ($match,$cond)=&is_on_map($refuri);
 4788:             if ($match) {
 4789:               my $refstatecond=$cond;
 4790:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4791:                   =~/\Q$priv\E\&([^\:]*)/) {
 4792:                   $thisallowed.=$1;
 4793:                   $uri=$refuri;
 4794:                   $statecond=$refstatecond;
 4795:               }
 4796:           }
 4797:         }
 4798:        }
 4799:    }
 4800: 
 4801: #
 4802: # Gathered now: all privileges that could apply, and condition number
 4803: # 
 4804: #
 4805: # Full or no access?
 4806: #
 4807: 
 4808:     if ($thisallowed=~/F/) {
 4809: 	return 'F';
 4810:     }
 4811: 
 4812:     unless ($thisallowed) {
 4813:         return '';
 4814:     }
 4815: 
 4816: # Restrictions exist, deal with them
 4817: #
 4818: #   C:according to course preferences
 4819: #   R:according to resource settings
 4820: #   L:unless locked
 4821: #   X:according to user session state
 4822: #
 4823: 
 4824: # Possibly locked functionality, check all courses
 4825: # Locks might take effect only after 10 minutes cache expiration for other
 4826: # courses, and 2 minutes for current course
 4827: 
 4828:     my $envkey;
 4829:     if ($thisallowed=~/L/) {
 4830:         foreach $envkey (keys %env) {
 4831:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4832:                my $courseid=$2;
 4833:                my $roleid=$1.'.'.$2;
 4834:                $courseid=~s/^\///;
 4835:                my $expiretime=600;
 4836:                if ($env{'request.role'} eq $roleid) {
 4837: 		  $expiretime=120;
 4838:                }
 4839: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4840:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4841:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4842: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4843:                }
 4844:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4845:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4846: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4847:                        &log($env{'user.domain'},$env{'user.name'},
 4848:                             $env{'user.home'},
 4849:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4850:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4851:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4852: 		       return '';
 4853:                    }
 4854:                }
 4855:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4856:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4857: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4858:                        &log($env{'user.domain'},$env{'user.name'},
 4859:                             $env{'user.home'},
 4860:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4861:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4862:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4863: 		       return '';
 4864:                    }
 4865:                }
 4866: 	   }
 4867:        }
 4868:     }
 4869:    
 4870: #
 4871: # Rest of the restrictions depend on selected course
 4872: #
 4873: 
 4874:     unless ($env{'request.course.id'}) {
 4875: 	if ($thisallowed eq 'A') {
 4876: 	    return 'A';
 4877:         } elsif ($thisallowed eq 'B') {
 4878:             return 'B';
 4879: 	} else {
 4880: 	    return '1';
 4881: 	}
 4882:     }
 4883: 
 4884: #
 4885: # Now user is definitely in a course
 4886: #
 4887: 
 4888: 
 4889: # Course preferences
 4890: 
 4891:    if ($thisallowed=~/C/) {
 4892:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4893:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4894:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4895: 	   =~/\Q$rolecode\E/) {
 4896: 	   if ($priv ne 'pch') { 
 4897: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4898: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4899: 			$env{'request.course.id'});
 4900: 	   }
 4901:            return '';
 4902:        }
 4903: 
 4904:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4905: 	   =~/\Q$unamedom\E/) {
 4906: 	   if ($priv ne 'pch') { 
 4907: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4908: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4909: 			$env{'request.course.id'});
 4910: 	   }
 4911:            return '';
 4912:        }
 4913:    }
 4914: 
 4915: # Resource preferences
 4916: 
 4917:    if ($thisallowed=~/R/) {
 4918:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4919:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4920: 	   if ($priv ne 'pch') { 
 4921: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4922: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4923: 	   }
 4924: 	   return '';
 4925:        }
 4926:    }
 4927: 
 4928: # Restricted by state or randomout?
 4929: 
 4930:    if ($thisallowed=~/X/) {
 4931:       if ($env{'acc.randomout'}) {
 4932: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4933:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4934:             return ''; 
 4935:          }
 4936:       }
 4937:       if (&condval($statecond)) {
 4938: 	 return '2';
 4939:       } else {
 4940:          return '';
 4941:       }
 4942:    }
 4943: 
 4944:     if ($thisallowed eq 'A') {
 4945: 	return 'A';
 4946:     } elsif ($thisallowed eq 'B') {
 4947:         return 'B';
 4948:     }
 4949:    return 'F';
 4950: }
 4951: 
 4952: sub split_uri_for_cond {
 4953:     my $uri=&deversion(&declutter(shift));
 4954:     my @uriparts=split(/\//,$uri);
 4955:     my $filename=pop(@uriparts);
 4956:     my $pathname=join('/',@uriparts);
 4957:     return ($pathname,$filename);
 4958: }
 4959: # --------------------------------------------------- Is a resource on the map?
 4960: 
 4961: sub is_on_map {
 4962:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4963:     #Trying to find the conditional for the file
 4964:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4965: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4966:     if ($match) {
 4967: 	return (1,$1);
 4968:     } else {
 4969: 	return (0,0);
 4970:     }
 4971: }
 4972: 
 4973: # --------------------------------------------------------- Get symb from alias
 4974: 
 4975: sub get_symb_from_alias {
 4976:     my $symb=shift;
 4977:     my ($map,$resid,$url)=&decode_symb($symb);
 4978: # Already is a symb
 4979:     if ($url) { return $symb; }
 4980: # Must be an alias
 4981:     my $aliassymb='';
 4982:     my %bighash;
 4983:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4984:                             &GDBM_READER(),0640)) {
 4985:         my $rid=$bighash{'mapalias_'.$symb};
 4986: 	if ($rid) {
 4987: 	    my ($mapid,$resid)=split(/\./,$rid);
 4988: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4989: 				    $resid,$bighash{'src_'.$rid});
 4990: 	}
 4991:         untie %bighash;
 4992:     }
 4993:     return $aliassymb;
 4994: }
 4995: 
 4996: # ----------------------------------------------------------------- Define Role
 4997: 
 4998: sub definerole {
 4999:   if (allowed('mcr','/')) {
 5000:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5001:     foreach my $role (split(':',$sysrole)) {
 5002: 	my ($crole,$cqual)=split(/\&/,$role);
 5003:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5004:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5005: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5006:                return "refused:s:$crole&$cqual"; 
 5007:             }
 5008:         }
 5009:     }
 5010:     foreach my $role (split(':',$domrole)) {
 5011: 	my ($crole,$cqual)=split(/\&/,$role);
 5012:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5013:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5014: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5015:                return "refused:d:$crole&$cqual"; 
 5016:             }
 5017:         }
 5018:     }
 5019:     foreach my $role (split(':',$courole)) {
 5020: 	my ($crole,$cqual)=split(/\&/,$role);
 5021:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5022:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5023: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5024:                return "refused:c:$crole&$cqual"; 
 5025:             }
 5026:         }
 5027:     }
 5028:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5029:                 "$env{'user.domain'}:$env{'user.name'}:".
 5030: 	        "rolesdef_$rolename=".
 5031:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5032:     return reply($command,$env{'user.home'});
 5033:   } else {
 5034:     return 'refused';
 5035:   }
 5036: }
 5037: 
 5038: # ---------------- Make a metadata query against the network of library servers
 5039: 
 5040: sub metadata_query {
 5041:     my ($query,$custom,$customshow,$server_array)=@_;
 5042:     my %rhash;
 5043:     my %libserv = &all_library();
 5044:     my @server_list = (defined($server_array) ? @$server_array
 5045:                                               : keys(%libserv) );
 5046:     for my $server (@server_list) {
 5047: 	unless ($custom or $customshow) {
 5048: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5049: 	    $rhash{$server}=$reply;
 5050: 	}
 5051: 	else {
 5052: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5053: 			     &escape($custom).':'.&escape($customshow),
 5054: 			     $server);
 5055: 	    $rhash{$server}=$reply;
 5056: 	}
 5057:     }
 5058:     return \%rhash;
 5059: }
 5060: 
 5061: # ----------------------------------------- Send log queries and wait for reply
 5062: 
 5063: sub log_query {
 5064:     my ($uname,$udom,$query,%filters)=@_;
 5065:     my $uhome=&homeserver($uname,$udom);
 5066:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5067:     my $uhost=&hostname($uhome);
 5068:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5069:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5070:                        $uhome);
 5071:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5072:     return get_query_reply($queryid);
 5073: }
 5074: 
 5075: # -------------------------- Update MySQL table for portfolio file
 5076: 
 5077: sub update_portfolio_table {
 5078:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5079:     if ($group ne '') {
 5080:         $file_name =~s /^\Q$group\E//;
 5081:     }
 5082:     my $homeserver = &homeserver($uname,$udom);
 5083:     my $queryid=
 5084:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5085:                ':'.&escape($file_name).':'.$action,$homeserver);
 5086:     my $reply = &get_query_reply($queryid);
 5087:     return $reply;
 5088: }
 5089: 
 5090: # -------------------------- Update MySQL allusers table
 5091: 
 5092: sub update_allusers_table {
 5093:     my ($uname,$udom,$names) = @_;
 5094:     my $homeserver = &homeserver($uname,$udom);
 5095:     my $queryid=
 5096:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5097:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5098:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5099:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5100:                'generation='.&escape($names->{'generation'}).'%%'.
 5101:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5102:                'id='.&escape($names->{'id'}),$homeserver);
 5103:     my $reply = &get_query_reply($queryid);
 5104:     return $reply;
 5105: }
 5106: 
 5107: # ------- Request retrieval of institutional classlists for course(s)
 5108: 
 5109: sub fetch_enrollment_query {
 5110:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5111:     my $homeserver;
 5112:     my $maxtries = 1;
 5113:     if ($context eq 'automated') {
 5114:         $homeserver = $perlvar{'lonHostID'};
 5115:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5116:     } else {
 5117:         $homeserver = &homeserver($cnum,$dom);
 5118:     }
 5119:     my $host=&hostname($homeserver);
 5120:     my $cmd = '';
 5121:     foreach my $affiliate (keys %{$affiliatesref}) {
 5122:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5123:     }
 5124:     $cmd =~ s/%%$//;
 5125:     $cmd = &escape($cmd);
 5126:     my $query = 'fetchenrollment';
 5127:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5128:     unless ($queryid=~/^\Q$host\E\_/) { 
 5129:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5130:         return 'error: '.$queryid;
 5131:     }
 5132:     my $reply = &get_query_reply($queryid);
 5133:     my $tries = 1;
 5134:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5135:         $reply = &get_query_reply($queryid);
 5136:         $tries ++;
 5137:     }
 5138:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5139:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5140:     } else {
 5141:         my @responses = split(/:/,$reply);
 5142:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5143:             foreach my $line (@responses) {
 5144:                 my ($key,$value) = split(/=/,$line,2);
 5145:                 $$replyref{$key} = $value;
 5146:             }
 5147:         } else {
 5148:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5149:             foreach my $line (@responses) {
 5150:                 my ($key,$value) = split(/=/,$line);
 5151:                 $$replyref{$key} = $value;
 5152:                 if ($value > 0) {
 5153:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5154:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5155:                         my $destname = $pathname.'/'.$filename;
 5156:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5157:                         if ($xml_classlist =~ /^error/) {
 5158:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5159:                         } else {
 5160:                             if ( open(FILE,">$destname") ) {
 5161:                                 print FILE &unescape($xml_classlist);
 5162:                                 close(FILE);
 5163:                             } else {
 5164:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5165:                             }
 5166:                         }
 5167:                     }
 5168:                 }
 5169:             }
 5170:         }
 5171:         return 'ok';
 5172:     }
 5173:     return 'error';
 5174: }
 5175: 
 5176: sub get_query_reply {
 5177:     my $queryid=shift;
 5178:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5179:     my $reply='';
 5180:     for (1..100) {
 5181: 	sleep 2;
 5182:         if (-e $replyfile.'.end') {
 5183: 	    if (open(my $fh,$replyfile)) {
 5184: 		$reply = join('',<$fh>);
 5185: 		close($fh);
 5186: 	   } else { return 'error: reply_file_error'; }
 5187:            return &unescape($reply);
 5188: 	}
 5189:     }
 5190:     return 'timeout:'.$queryid;
 5191: }
 5192: 
 5193: sub courselog_query {
 5194: #
 5195: # possible filters:
 5196: # url: url or symb
 5197: # username
 5198: # domain
 5199: # action: view, submit, grade
 5200: # start: timestamp
 5201: # end: timestamp
 5202: #
 5203:     my (%filters)=@_;
 5204:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5205:     if ($filters{'url'}) {
 5206: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5207:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5208:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5209:     }
 5210:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5211:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5212:     return &log_query($cname,$cdom,'courselog',%filters);
 5213: }
 5214: 
 5215: sub userlog_query {
 5216: #
 5217: # possible filters:
 5218: # action: log check role
 5219: # start: timestamp
 5220: # end: timestamp
 5221: #
 5222:     my ($uname,$udom,%filters)=@_;
 5223:     return &log_query($uname,$udom,'userlog',%filters);
 5224: }
 5225: 
 5226: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5227: 
 5228: sub auto_run {
 5229:     my ($cnum,$cdom) = @_;
 5230:     my $response = 0;
 5231:     my $settings;
 5232:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5233:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5234:         $settings = $domconfig{'autoenroll'};
 5235:         if ($settings->{'run'} eq '1') {
 5236:             $response = 1;
 5237:         }
 5238:     } else {
 5239:         my $homeserver;
 5240:         if (&is_course($cdom,$cnum)) {
 5241:             $homeserver = &homeserver($cnum,$cdom);
 5242:         } else {
 5243:             $homeserver = &domain($cdom,'primary');
 5244:         }
 5245:         if ($homeserver ne 'no_host') {
 5246:             $response = &reply('autorun:'.$cdom,$homeserver);
 5247:         }
 5248:     }
 5249:     return $response;
 5250: }
 5251: 
 5252: sub auto_get_sections {
 5253:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5254:     my $homeserver = &homeserver($cnum,$cdom);
 5255:     my @secs = ();
 5256:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5257:     unless ($response eq 'refused') {
 5258:         @secs = split(/:/,$response);
 5259:     }
 5260:     return @secs;
 5261: }
 5262: 
 5263: sub auto_new_course {
 5264:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5265:     my $homeserver = &homeserver($cnum,$cdom);
 5266:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5267:     return $response;
 5268: }
 5269: 
 5270: sub auto_validate_courseID {
 5271:     my ($cnum,$cdom,$inst_course_id) = @_;
 5272:     my $homeserver = &homeserver($cnum,$cdom);
 5273:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5274:     return $response;
 5275: }
 5276: 
 5277: sub auto_create_password {
 5278:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5279:     my ($homeserver,$response);
 5280:     my $create_passwd = 0;
 5281:     my $authchk = '';
 5282:     if ($udom =~ /^$match_domain$/) {
 5283:         $homeserver = &domain($udom,'primary');
 5284:     }
 5285:     if ($homeserver eq '') {
 5286:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5287:             $homeserver = &homeserver($cnum,$cdom);
 5288:         }
 5289:     }
 5290:     if ($homeserver eq '') {
 5291:         $authchk = 'nodomain';
 5292:     } else {
 5293:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5294:         if ($response eq 'refused') {
 5295:             $authchk = 'refused';
 5296:         } else {
 5297:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5298:         }
 5299:     }
 5300:     return ($authparam,$create_passwd,$authchk);
 5301: }
 5302: 
 5303: sub auto_photo_permission {
 5304:     my ($cnum,$cdom,$students) = @_;
 5305:     my $homeserver = &homeserver($cnum,$cdom);
 5306:     my ($outcome,$perm_reqd,$conditions) = 
 5307: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5308:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5309: 	return (undef,undef);
 5310:     }
 5311:     return ($outcome,$perm_reqd,$conditions);
 5312: }
 5313: 
 5314: sub auto_checkphotos {
 5315:     my ($uname,$udom,$pid) = @_;
 5316:     my $homeserver = &homeserver($uname,$udom);
 5317:     my ($result,$resulttype);
 5318:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5319: 				   &escape($uname).':'.&escape($pid),
 5320: 				   $homeserver));
 5321:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5322: 	return (undef,undef);
 5323:     }
 5324:     if ($outcome) {
 5325:         ($result,$resulttype) = split(/:/,$outcome);
 5326:     } 
 5327:     return ($result,$resulttype);
 5328: }
 5329: 
 5330: sub auto_photochoice {
 5331:     my ($cnum,$cdom) = @_;
 5332:     my $homeserver = &homeserver($cnum,$cdom);
 5333:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5334: 						       &escape($cdom),
 5335: 						       $homeserver)));
 5336:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5337: 	return (undef,undef);
 5338:     }
 5339:     return ($update,$comment);
 5340: }
 5341: 
 5342: sub auto_photoupdate {
 5343:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5344:     my $homeserver = &homeserver($cnum,$dom);
 5345:     my $host=&hostname($homeserver);
 5346:     my $cmd = '';
 5347:     my $maxtries = 1;
 5348:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5349:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5350:     }
 5351:     $cmd =~ s/%%$//;
 5352:     $cmd = &escape($cmd);
 5353:     my $query = 'institutionalphotos';
 5354:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5355:     unless ($queryid=~/^\Q$host\E\_/) {
 5356:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5357:         return 'error: '.$queryid;
 5358:     }
 5359:     my $reply = &get_query_reply($queryid);
 5360:     my $tries = 1;
 5361:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5362:         $reply = &get_query_reply($queryid);
 5363:         $tries ++;
 5364:     }
 5365:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5366:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5367:     } else {
 5368:         my @responses = split(/:/,$reply);
 5369:         my $outcome = shift(@responses); 
 5370:         foreach my $item (@responses) {
 5371:             my ($key,$value) = split(/=/,$item);
 5372:             $$photo{$key} = $value;
 5373:         }
 5374:         return $outcome;
 5375:     }
 5376:     return 'error';
 5377: }
 5378: 
 5379: sub auto_instcode_format {
 5380:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5381: 	$cat_order) = @_;
 5382:     my $courses = '';
 5383:     my @homeservers;
 5384:     if ($caller eq 'global') {
 5385: 	my %servers = &get_servers($codedom,'library');
 5386: 	foreach my $tryserver (keys(%servers)) {
 5387: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5388: 		push(@homeservers,$tryserver);
 5389: 	    }
 5390:         }
 5391:     } else {
 5392:         push(@homeservers,&homeserver($caller,$codedom));
 5393:     }
 5394:     foreach my $code (keys(%{$instcodes})) {
 5395:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5396:     }
 5397:     chop($courses);
 5398:     my $ok_response = 0;
 5399:     my $response;
 5400:     while (@homeservers > 0 && $ok_response == 0) {
 5401:         my $server = shift(@homeservers); 
 5402:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5403:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5404:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5405: 		split(/:/,$response);
 5406:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5407:             push(@{$codetitles},&str2array($codetitles_str));
 5408:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5409:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5410:             $ok_response = 1;
 5411:         }
 5412:     }
 5413:     if ($ok_response) {
 5414:         return 'ok';
 5415:     } else {
 5416:         return $response;
 5417:     }
 5418: }
 5419: 
 5420: sub auto_instcode_defaults {
 5421:     my ($domain,$returnhash,$code_order) = @_;
 5422:     my @homeservers;
 5423: 
 5424:     my %servers = &get_servers($domain,'library');
 5425:     foreach my $tryserver (keys(%servers)) {
 5426: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5427: 	    push(@homeservers,$tryserver);
 5428: 	}
 5429:     }
 5430: 
 5431:     my $response;
 5432:     foreach my $server (@homeservers) {
 5433:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5434:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5435: 	
 5436: 	foreach my $pair (split(/\&/,$response)) {
 5437: 	    my ($name,$value)=split(/\=/,$pair);
 5438: 	    if ($name eq 'code_order') {
 5439: 		@{$code_order} = split(/\&/,&unescape($value));
 5440: 	    } else {
 5441: 		$returnhash->{&unescape($name)}=&unescape($value);
 5442: 	    }
 5443: 	}
 5444: 	return 'ok';
 5445:     }
 5446: 
 5447:     return $response;
 5448: } 
 5449: 
 5450: sub auto_validate_class_sec {
 5451:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5452:     my $homeserver = &homeserver($cnum,$cdom);
 5453:     my $ownerlist;
 5454:     if (ref($owners) eq 'ARRAY') {
 5455:         $ownerlist = join(',',@{$owners});
 5456:     } else {
 5457:         $ownerlist = $owners;
 5458:     }
 5459:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5460:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5461:     return $response;
 5462: }
 5463: 
 5464: # ------------------------------------------------------- Course Group routines
 5465: 
 5466: sub get_coursegroups {
 5467:     my ($cdom,$cnum,$group,$namespace) = @_;
 5468:     return(&dump($namespace,$cdom,$cnum,$group));
 5469: }
 5470: 
 5471: sub modify_coursegroup {
 5472:     my ($cdom,$cnum,$groupsettings) = @_;
 5473:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5474: }
 5475: 
 5476: sub toggle_coursegroup_status {
 5477:     my ($cdom,$cnum,$group,$action) = @_;
 5478:     my ($from_namespace,$to_namespace);
 5479:     if ($action eq 'delete') {
 5480:         $from_namespace = 'coursegroups';
 5481:         $to_namespace = 'deleted_groups';
 5482:     } else {
 5483:         $from_namespace = 'deleted_groups';
 5484:         $to_namespace = 'coursegroups';
 5485:     }
 5486:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5487:     if (my $tmp = &error(%curr_group)) {
 5488:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5489:         return ('read error',$tmp);
 5490:     } else {
 5491:         my %savedsettings = %curr_group; 
 5492:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5493:         my $deloutcome;
 5494:         if ($result eq 'ok') {
 5495:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5496:         } else {
 5497:             return ('write error',$result);
 5498:         }
 5499:         if ($deloutcome eq 'ok') {
 5500:             return 'ok';
 5501:         } else {
 5502:             return ('delete error',$deloutcome);
 5503:         }
 5504:     }
 5505: }
 5506: 
 5507: sub modify_group_roles {
 5508:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5509:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5510:     my $role = 'gr/'.&escape($userprivs);
 5511:     my ($uname,$udom) = split(/:/,$user);
 5512:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5513:     if ($result eq 'ok') {
 5514:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5515:     }
 5516:     return $result;
 5517: }
 5518: 
 5519: sub modify_coursegroup_membership {
 5520:     my ($cdom,$cnum,$membership) = @_;
 5521:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5522:     return $result;
 5523: }
 5524: 
 5525: sub get_active_groups {
 5526:     my ($udom,$uname,$cdom,$cnum) = @_;
 5527:     my $now = time;
 5528:     my %groups = ();
 5529:     foreach my $key (keys(%env)) {
 5530:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5531:             my ($start,$end) = split(/\./,$env{$key});
 5532:             if (($end!=0) && ($end<$now)) { next; }
 5533:             if (($start!=0) && ($start>$now)) { next; }
 5534:             if ($1 eq $cdom && $2 eq $cnum) {
 5535:                 $groups{$3} = $env{$key} ;
 5536:             }
 5537:         }
 5538:     }
 5539:     return %groups;
 5540: }
 5541: 
 5542: sub get_group_membership {
 5543:     my ($cdom,$cnum,$group) = @_;
 5544:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5545: }
 5546: 
 5547: sub get_users_groups {
 5548:     my ($udom,$uname,$courseid) = @_;
 5549:     my @usersgroups;
 5550:     my $cachetime=1800;
 5551: 
 5552:     my $hashid="$udom:$uname:$courseid";
 5553:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5554:     if (defined($cached)) {
 5555:         @usersgroups = split(/:/,$grouplist);
 5556:     } else {  
 5557:         $grouplist = '';
 5558:         my $courseurl = &courseid_to_courseurl($courseid);
 5559:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5560:         my $access_end = $env{'course.'.$courseid.
 5561:                               '.default_enrollment_end_date'};
 5562:         my $now = time;
 5563:         foreach my $key (keys(%roleshash)) {
 5564:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5565:                 my $group = $1;
 5566:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5567:                     my $start = $2;
 5568:                     my $end = $1;
 5569:                     if ($start == -1) { next; } # deleted from group
 5570:                     if (($start!=0) && ($start>$now)) { next; }
 5571:                     if (($end!=0) && ($end<$now)) {
 5572:                         if ($access_end && $access_end < $now) {
 5573:                             if ($access_end - $end < 86400) {
 5574:                                 push(@usersgroups,$group);
 5575:                             }
 5576:                         }
 5577:                         next;
 5578:                     }
 5579:                     push(@usersgroups,$group);
 5580:                 }
 5581:             }
 5582:         }
 5583:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5584:         $grouplist = join(':',@usersgroups);
 5585:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5586:     }
 5587:     return @usersgroups;
 5588: }
 5589: 
 5590: sub devalidate_getgroups_cache {
 5591:     my ($udom,$uname,$cdom,$cnum)=@_;
 5592:     my $courseid = $cdom.'_'.$cnum;
 5593: 
 5594:     my $hashid="$udom:$uname:$courseid";
 5595:     &devalidate_cache_new('getgroups',$hashid);
 5596: }
 5597: 
 5598: # ------------------------------------------------------------------ Plain Text
 5599: 
 5600: sub plaintext {
 5601:     my ($short,$type,$cid) = @_;
 5602:     if ($short =~ /^cr/) {
 5603: 	return (split('/',$short))[-1];
 5604:     }
 5605:     if (!defined($cid)) {
 5606:         $cid = $env{'request.course.id'};
 5607:     }
 5608:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5609:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5610:                                           '.plaintext'});
 5611:     }
 5612:     my %rolenames = (
 5613:                       Course => 'std',
 5614:                       Group => 'alt1',
 5615:                     );
 5616:     if (defined($type) && 
 5617:          defined($rolenames{$type}) && 
 5618:          defined($prp{$short}{$rolenames{$type}})) {
 5619:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5620:     } else {
 5621:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5622:     }
 5623: }
 5624: 
 5625: # ----------------------------------------------------------------- Assign Role
 5626: 
 5627: sub assignrole {
 5628:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5629:         $context)=@_;
 5630:     my $mrole;
 5631:     if ($role =~ /^cr\//) {
 5632:         my $cwosec=$url;
 5633:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5634: 	unless (&allowed('ccr',$cwosec)) {
 5635:            &logthis('Refused custom assignrole: '.
 5636:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5637: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5638:            return 'refused'; 
 5639:         }
 5640:         $mrole='cr';
 5641:     } elsif ($role =~ /^gr\//) {
 5642:         my $cwogrp=$url;
 5643:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5644:         unless (&allowed('mdg',$cwogrp)) {
 5645:             &logthis('Refused group assignrole: '.
 5646:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5647:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5648:             return 'refused';
 5649:         }
 5650:         $mrole='gr';
 5651:     } else {
 5652:         my $cwosec=$url;
 5653:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5654:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5655:             my $refused;
 5656:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5657:                 if (!(&allowed('c'.$role,$url))) {
 5658:                     $refused = 1;
 5659:                 }
 5660:             } else {
 5661:                 $refused = 1;
 5662:             }
 5663:             if ($refused) {
 5664:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5665:                     $refused = '';
 5666:                 } else {
 5667:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5668:                              ' '.$role.' '.$end.' '.$start.' by '.
 5669: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5670:                     return 'refused';
 5671:                 }
 5672:             }
 5673:         }
 5674:         $mrole=$role;
 5675:     }
 5676:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5677:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5678:     if ($end) { $command.='_'.$end; }
 5679:     if ($start) {
 5680: 	if ($end) { 
 5681:            $command.='_'.$start; 
 5682:         } else {
 5683:            $command.='_0_'.$start;
 5684:         }
 5685:     }
 5686:     my $origstart = $start;
 5687:     my $origend = $end;
 5688:     my $delflag;
 5689: # actually delete
 5690:     if ($deleteflag) {
 5691: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5692: # modify command to delete the role
 5693:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5694:                 "$udom:$uname:$url".'_'."$mrole";
 5695: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5696: # set start and finish to negative values for userrolelog
 5697:            $start=-1;
 5698:            $end=-1;
 5699:            $delflag = 1;
 5700:         }
 5701:     }
 5702: # send command
 5703:     my $answer=&reply($command,&homeserver($uname,$udom));
 5704: # log new user role if status is ok
 5705:     if ($answer eq 'ok') {
 5706: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5707: # for course roles, perform group memberships changes triggered by role change.
 5708:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5709:         unless ($role =~ /^gr/) {
 5710:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5711:                                              $origstart,$selfenroll,$context);
 5712:         }
 5713:     }
 5714:     return $answer;
 5715: }
 5716: 
 5717: # -------------------------------------------------- Modify user authentication
 5718: # Overrides without validation
 5719: 
 5720: sub modifyuserauth {
 5721:     my ($udom,$uname,$umode,$upass)=@_;
 5722:     my $uhome=&homeserver($uname,$udom);
 5723:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5724:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5725:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5726:              ' in domain '.$env{'request.role.domain'});  
 5727:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5728: 		     &escape($upass),$uhome);
 5729:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5730:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5731:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5732:     &log($udom,,$uname,$uhome,
 5733:         'Authentication changed by '.$env{'user.domain'}.', '.
 5734:                                      $env{'user.name'}.', '.$umode.
 5735:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5736:     unless ($reply eq 'ok') {
 5737:         &logthis('Authentication mode error: '.$reply);
 5738: 	return 'error: '.$reply;
 5739:     }   
 5740:     return 'ok';
 5741: }
 5742: 
 5743: # --------------------------------------------------------------- Modify a user
 5744: 
 5745: sub modifyuser {
 5746:     my ($udom,    $uname, $uid,
 5747:         $umode,   $upass, $first,
 5748:         $middle,  $last,  $gene,
 5749:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5750:     $udom= &LONCAPA::clean_domain($udom);
 5751:     $uname=&LONCAPA::clean_username($uname);
 5752:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5753:              $umode.', '.$first.', '.$middle.', '.
 5754: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5755:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5756:                                      ' desiredhome not specified'). 
 5757:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5758:              ' in domain '.$env{'request.role.domain'});
 5759:     my $uhome=&homeserver($uname,$udom,'true');
 5760: # ----------------------------------------------------------------- Create User
 5761:     if (($uhome eq 'no_host') && 
 5762: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5763:         my $unhome='';
 5764:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5765:             $unhome = $desiredhome;
 5766: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5767: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5768:         } else { # load balancing routine for determining $unhome
 5769:             my $loadm=10000000;
 5770: 	    my %servers = &get_servers($udom,'library');
 5771: 	    foreach my $tryserver (keys(%servers)) {
 5772: 		my $answer=reply('load',$tryserver);
 5773: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5774: 		    $loadm=$answer;
 5775: 		    $unhome=$tryserver;
 5776: 		}
 5777: 	    }
 5778:         }
 5779:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5780: 	    return 'error: unable to find a home server for '.$uname.
 5781:                    ' in domain '.$udom;
 5782:         }
 5783:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5784:                          &escape($upass),$unhome);
 5785: 	unless ($reply eq 'ok') {
 5786:             return 'error: '.$reply;
 5787:         }   
 5788:         $uhome=&homeserver($uname,$udom,'true');
 5789:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5790: 	    return 'error: unable verify users home machine.';
 5791:         }
 5792:     }   # End of creation of new user
 5793: # ---------------------------------------------------------------------- Add ID
 5794:     if ($uid) {
 5795:        $uid=~tr/A-Z/a-z/;
 5796:        my %uidhash=&idrget($udom,$uname);
 5797:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5798:          && (!$forceid)) {
 5799: 	  unless ($uid eq $uidhash{$uname}) {
 5800: 	      return 'error: user id "'.$uid.'" does not match '.
 5801:                   'current user id "'.$uidhash{$uname}.'".';
 5802:           }
 5803:        } else {
 5804: 	  &idput($udom,($uname => $uid));
 5805:        }
 5806:     }
 5807: # -------------------------------------------------------------- Add names, etc
 5808:     my @tmp=&get('environment',
 5809: 		   ['firstname','middlename','lastname','generation','id',
 5810:                     'permanentemail','inststatus'],
 5811: 		   $udom,$uname);
 5812:     my %names;
 5813:     if ($tmp[0] =~ m/^error:.*/) { 
 5814:         %names=(); 
 5815:     } else {
 5816:         %names = @tmp;
 5817:     }
 5818: #
 5819: # Make sure to not trash student environment if instructor does not bother
 5820: # to supply name and email information
 5821: #
 5822:     if ($first)  { $names{'firstname'}  = $first; }
 5823:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5824:     if ($last)   { $names{'lastname'}   = $last; }
 5825:     if (defined($gene))   { $names{'generation'} = $gene; }
 5826:     if ($email) {
 5827:        $email=~s/[^\w\@\.\-\,]//gs;
 5828:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5829:     }
 5830:     if ($uid) { $names{'id'}  = $uid; }
 5831:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5832:     my $reply = &put('environment', \%names, $udom,$uname);
 5833:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5834:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5835:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5836:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5837:                  $umode.', '.$first.', '.$middle.', '.
 5838: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5839:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5840:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5841:     } else {
 5842:         $logmsg .= ' during self creation';
 5843:     }
 5844:     &logthis($logmsg);
 5845:     return 'ok';
 5846: }
 5847: 
 5848: # -------------------------------------------------------------- Modify student
 5849: 
 5850: sub modifystudent {
 5851:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5852:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5853:         $selfenroll,$context)=@_;
 5854:     if (!$cid) {
 5855: 	unless ($cid=$env{'request.course.id'}) {
 5856: 	    return 'not_in_class';
 5857: 	}
 5858:     }
 5859: # --------------------------------------------------------------- Make the user
 5860:     my $reply=&modifyuser
 5861: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5862:          $desiredhome,$email);
 5863:     unless ($reply eq 'ok') { return $reply; }
 5864:     # This will cause &modify_student_enrollment to get the uid from the
 5865:     # students environment
 5866:     $uid = undef if (!$forceid);
 5867:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5868: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5869:     return $reply;
 5870: }
 5871: 
 5872: sub modify_student_enrollment {
 5873:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5874:     my ($cdom,$cnum,$chome);
 5875:     if (!$cid) {
 5876: 	unless ($cid=$env{'request.course.id'}) {
 5877: 	    return 'not_in_class';
 5878: 	}
 5879: 	$cdom=$env{'course.'.$cid.'.domain'};
 5880: 	$cnum=$env{'course.'.$cid.'.num'};
 5881:     } else {
 5882: 	($cdom,$cnum)=split(/_/,$cid);
 5883:     }
 5884:     $chome=$env{'course.'.$cid.'.home'};
 5885:     if (!$chome) {
 5886: 	$chome=&homeserver($cnum,$cdom);
 5887:     }
 5888:     if (!$chome) { return 'unknown_course'; }
 5889:     # Make sure the user exists
 5890:     my $uhome=&homeserver($uname,$udom);
 5891:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5892: 	return 'error: no such user';
 5893:     }
 5894:     # Get student data if we were not given enough information
 5895:     if (!defined($first)  || $first  eq '' || 
 5896:         !defined($last)   || $last   eq '' || 
 5897:         !defined($uid)    || $uid    eq '' || 
 5898:         !defined($middle) || $middle eq '' || 
 5899:         !defined($gene)   || $gene   eq '') {
 5900:         # They did not supply us with enough data to enroll the student, so
 5901:         # we need to pick up more information.
 5902:         my %tmp = &get('environment',
 5903:                        ['firstname','middlename','lastname', 'generation','id']
 5904:                        ,$udom,$uname);
 5905: 
 5906:         #foreach my $key (keys(%tmp)) {
 5907:         #    &logthis("key $key = ".$tmp{$key});
 5908:         #}
 5909:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5910:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5911:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5912:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5913:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5914:     }
 5915:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5916:     my $reply=cput('classlist',
 5917: 		   {"$uname:$udom" => 
 5918: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5919: 		   $cdom,$cnum);
 5920:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5921: 	return 'error: '.$reply;
 5922:     } else {
 5923: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5924:     }
 5925:     # Add student role to user
 5926:     my $uurl='/'.$cid;
 5927:     $uurl=~s/\_/\//g;
 5928:     if ($usec) {
 5929: 	$uurl.='/'.$usec;
 5930:     }
 5931:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5932: }
 5933: 
 5934: sub format_name {
 5935:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5936:     my $name;
 5937:     if ($first ne 'lastname') {
 5938: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5939:     } else {
 5940: 	if ($lastname=~/\S/) {
 5941: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5942: 	    $name=~s/\s+,/,/;
 5943: 	} else {
 5944: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5945: 	}
 5946:     }
 5947:     $name=~s/^\s+//;
 5948:     $name=~s/\s+$//;
 5949:     $name=~s/\s+/ /g;
 5950:     return $name;
 5951: }
 5952: 
 5953: # ------------------------------------------------- Write to course preferences
 5954: 
 5955: sub writecoursepref {
 5956:     my ($courseid,%prefs)=@_;
 5957:     $courseid=~s/^\///;
 5958:     $courseid=~s/\_/\//g;
 5959:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5960:     my $chome=homeserver($cnum,$cdomain);
 5961:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5962: 	return 'error: no such course';
 5963:     }
 5964:     my $cstring='';
 5965:     foreach my $pref (keys(%prefs)) {
 5966: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5967:     }
 5968:     $cstring=~s/\&$//;
 5969:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5970: }
 5971: 
 5972: # ---------------------------------------------------------- Make/modify course
 5973: 
 5974: sub createcourse {
 5975:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5976:         $course_owner,$crstype)=@_;
 5977:     $url=&declutter($url);
 5978:     my $cid='';
 5979:     unless (&allowed('ccc',$udom)) {
 5980:         return 'refused';
 5981:     }
 5982: # ------------------------------------------------------------------- Create ID
 5983:    my $uname=int(1+rand(9)).
 5984:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5985:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5986:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5987: # ----------------------------------------------- Make sure that does not exist
 5988:    my $uhome=&homeserver($uname,$udom,'true');
 5989:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5990:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5991:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5992:        $uhome=&homeserver($uname,$udom,'true');       
 5993:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5994:            return 'error: unable to generate unique course-ID';
 5995:        } 
 5996:    }
 5997: # ------------------------------------------------ Check supplied server name
 5998:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5999:     if (! &is_library($course_server)) {
 6000:         return 'error:bad server name '.$course_server;
 6001:     }
 6002: # ------------------------------------------------------------- Make the course
 6003:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6004:                       $course_server);
 6005:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6006:     $uhome=&homeserver($uname,$udom,'true');
 6007:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6008: 	return 'error: no such course';
 6009:     }
 6010: # ----------------------------------------------------------------- Course made
 6011: # log existence
 6012:     my $newcourse = {
 6013:                     $udom.'_'.$uname => {
 6014:                                      description => $description,
 6015:                                      inst_code   => $inst_code,
 6016:                                      owner       => $course_owner,
 6017:                                      type        => $crstype,
 6018:                                                 },
 6019:                     };
 6020:     &courseidput($udom,$newcourse,$uhome,'notime');
 6021: # set toplevel url
 6022:     my $topurl=$url;
 6023:     unless ($nonstandard) {
 6024: # ------------------------------------------ For standard courses, make top url
 6025:         my $mapurl=&clutter($url);
 6026:         if ($mapurl eq '/res/') { $mapurl=''; }
 6027:         $env{'form.initmap'}=(<<ENDINITMAP);
 6028: <map>
 6029: <resource id="1" type="start"></resource>
 6030: <resource id="2" src="$mapurl"></resource>
 6031: <resource id="3" type="finish"></resource>
 6032: <link index="1" from="1" to="2"></link>
 6033: <link index="2" from="2" to="3"></link>
 6034: </map>
 6035: ENDINITMAP
 6036:         $topurl=&declutter(
 6037:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6038:                           );
 6039:     }
 6040: # ----------------------------------------------------------- Write preferences
 6041:     &writecoursepref($udom.'_'.$uname,
 6042:                      ('description' => $description,
 6043:                       'url'         => $topurl));
 6044:     return '/'.$udom.'/'.$uname;
 6045: }
 6046: 
 6047: sub is_course {
 6048:     my ($cdom,$cnum) = @_;
 6049:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6050: 				undef,'.');
 6051:     if (exists($courses{$cdom.'_'.$cnum})) {
 6052:         return 1;
 6053:     }
 6054:     return 0;
 6055: }
 6056: 
 6057: # ---------------------------------------------------------- Assign Custom Role
 6058: 
 6059: sub assigncustomrole {
 6060:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6061:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6062:                        $end,$start,$deleteflag,$selfenroll,$context);
 6063: }
 6064: 
 6065: # ----------------------------------------------------------------- Revoke Role
 6066: 
 6067: sub revokerole {
 6068:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6069:     my $now=time;
 6070:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6071: }
 6072: 
 6073: # ---------------------------------------------------------- Revoke Custom Role
 6074: 
 6075: sub revokecustomrole {
 6076:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6077:     my $now=time;
 6078:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6079:            $deleteflag,$selfenroll,$context);
 6080: }
 6081: 
 6082: # ------------------------------------------------------------ Disk usage
 6083: sub diskusage {
 6084:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6085:     $directorypath =~ s/\/$//;
 6086:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6087:                        .&escape($getpropath).':'.&escape($uname).':'
 6088:                        .&escape($udom),homeserver($uname,$udom));
 6089:     if ($listing eq 'unknown_cmd') {
 6090:         if ($getpropath) {
 6091:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6092:         }
 6093:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6094:     }
 6095:     return $listing;
 6096: }
 6097: 
 6098: sub is_locked {
 6099:     my ($file_name, $domain, $user) = @_;
 6100:     my @check;
 6101:     my $is_locked;
 6102:     push @check, $file_name;
 6103:     my %locked = &get('file_permissions',\@check,
 6104: 		      $env{'user.domain'},$env{'user.name'});
 6105:     my ($tmp)=keys(%locked);
 6106:     if ($tmp=~/^error:/) { undef(%locked); }
 6107:     
 6108:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6109:         $is_locked = 'false';
 6110:         foreach my $entry (@{$locked{$file_name}}) {
 6111:            if (ref($entry) eq 'ARRAY') { 
 6112:                $is_locked = 'true';
 6113:                last;
 6114:            }
 6115:        }
 6116:     } else {
 6117:         $is_locked = 'false';
 6118:     }
 6119: }
 6120: 
 6121: sub declutter_portfile {
 6122:     my ($file) = @_;
 6123:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6124:     return $file;
 6125: }
 6126: 
 6127: # ------------------------------------------------------------- Mark as Read Only
 6128: 
 6129: sub mark_as_readonly {
 6130:     my ($domain,$user,$files,$what) = @_;
 6131:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6132:     my ($tmp)=keys(%current_permissions);
 6133:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6134:     foreach my $file (@{$files}) {
 6135: 	$file = &declutter_portfile($file);
 6136:         push(@{$current_permissions{$file}},$what);
 6137:     }
 6138:     &put('file_permissions',\%current_permissions,$domain,$user);
 6139:     return;
 6140: }
 6141: 
 6142: # ------------------------------------------------------------Save Selected Files
 6143: 
 6144: sub save_selected_files {
 6145:     my ($user, $path, @files) = @_;
 6146:     my $filename = $user."savedfiles";
 6147:     my @other_files = &files_not_in_path($user, $path);
 6148:     open (OUT, '>'.$tmpdir.$filename);
 6149:     foreach my $file (@files) {
 6150:         print (OUT $env{'form.currentpath'}.$file."\n");
 6151:     }
 6152:     foreach my $file (@other_files) {
 6153:         print (OUT $file."\n");
 6154:     }
 6155:     close (OUT);
 6156:     return 'ok';
 6157: }
 6158: 
 6159: sub clear_selected_files {
 6160:     my ($user) = @_;
 6161:     my $filename = $user."savedfiles";
 6162:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6163:     print (OUT undef);
 6164:     close (OUT);
 6165:     return ("ok");    
 6166: }
 6167: 
 6168: sub files_in_path {
 6169:     my ($user, $path) = @_;
 6170:     my $filename = $user."savedfiles";
 6171:     my %return_files;
 6172:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6173:     while (my $line_in = <IN>) {
 6174:         chomp ($line_in);
 6175:         my @paths_and_file = split (m!/!, $line_in);
 6176:         my $file_part = pop (@paths_and_file);
 6177:         my $path_part = join ('/', @paths_and_file);
 6178:         $path_part.='/';
 6179:         my $path_and_file = $path_part.$file_part;
 6180:         if ($path_part eq $path) {
 6181:             $return_files{$file_part}= 'selected';
 6182:         }
 6183:     }
 6184:     close (IN);
 6185:     return (\%return_files);
 6186: }
 6187: 
 6188: # called in portfolio select mode, to show files selected NOT in current directory
 6189: sub files_not_in_path {
 6190:     my ($user, $path) = @_;
 6191:     my $filename = $user."savedfiles";
 6192:     my @return_files;
 6193:     my $path_part;
 6194:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6195:     while (my $line = <IN>) {
 6196:         #ok, I know it's clunky, but I want it to work
 6197:         my @paths_and_file = split(m|/|, $line);
 6198:         my $file_part = pop(@paths_and_file);
 6199:         chomp($file_part);
 6200:         my $path_part = join('/', @paths_and_file);
 6201:         $path_part .= '/';
 6202:         my $path_and_file = $path_part.$file_part;
 6203:         if ($path_part ne $path) {
 6204:             push(@return_files, ($path_and_file));
 6205:         }
 6206:     }
 6207:     close(OUT);
 6208:     return (@return_files);
 6209: }
 6210: 
 6211: #----------------------------------------------Get portfolio file permissions
 6212: 
 6213: sub get_portfile_permissions {
 6214:     my ($domain,$user) = @_;
 6215:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6216:     my ($tmp)=keys(%current_permissions);
 6217:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6218:     return \%current_permissions;
 6219: }
 6220: 
 6221: #---------------------------------------------Get portfolio file access controls
 6222: 
 6223: sub get_access_controls {
 6224:     my ($current_permissions,$group,$file) = @_;
 6225:     my %access;
 6226:     my $real_file = $file;
 6227:     $file =~ s/\.meta$//;
 6228:     if (defined($file)) {
 6229:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6230:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6231:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6232:             }
 6233:         }
 6234:     } else {
 6235:         foreach my $key (keys(%{$current_permissions})) {
 6236:             if ($key =~ /\0accesscontrol$/) {
 6237:                 if (defined($group)) {
 6238:                     if ($key !~ m-^\Q$group\E/-) {
 6239:                         next;
 6240:                     }
 6241:                 }
 6242:                 my ($fullpath) = split(/\0/,$key);
 6243:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6244:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6245:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6246:                     }
 6247:                 }
 6248:             }
 6249:         }
 6250:     }
 6251:     return %access;
 6252: }
 6253: 
 6254: sub modify_access_controls {
 6255:     my ($file_name,$changes,$domain,$user)=@_;
 6256:     my ($outcome,$deloutcome);
 6257:     my %store_permissions;
 6258:     my %new_values;
 6259:     my %new_control;
 6260:     my %translation;
 6261:     my @deletions = ();
 6262:     my $now = time;
 6263:     if (exists($$changes{'activate'})) {
 6264:         if (ref($$changes{'activate'}) eq 'HASH') {
 6265:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6266:             my $numnew = scalar(@newitems);
 6267:             for (my $i=0; $i<$numnew; $i++) {
 6268:                 my $newkey = $newitems[$i];
 6269:                 my $newid = &Apache::loncommon::get_cgi_id();
 6270:                 if ($newkey =~ /^\d+:/) { 
 6271:                     $newkey =~ s/^(\d+)/$newid/;
 6272:                     $translation{$1} = $newid;
 6273:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6274:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6275:                     $translation{$1} = $newid;
 6276:                 }
 6277:                 $new_values{$file_name."\0".$newkey} = 
 6278:                                           $$changes{'activate'}{$newitems[$i]};
 6279:                 $new_control{$newkey} = $now;
 6280:             }
 6281:         }
 6282:     }
 6283:     my %todelete;
 6284:     my %changed_items;
 6285:     foreach my $action ('delete','update') {
 6286:         if (exists($$changes{$action})) {
 6287:             if (ref($$changes{$action}) eq 'HASH') {
 6288:                 foreach my $key (keys(%{$$changes{$action}})) {
 6289:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6290:                     if ($action eq 'delete') { 
 6291:                         $todelete{$itemnum} = 1;
 6292:                     } else {
 6293:                         $changed_items{$itemnum} = $key;
 6294:                     }
 6295:                 }
 6296:             }
 6297:         }
 6298:     }
 6299:     # get lock on access controls for file.
 6300:     my $lockhash = {
 6301:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6302:                                                        ':'.$env{'user.domain'},
 6303:                    }; 
 6304:     my $tries = 0;
 6305:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6306:    
 6307:     while (($gotlock ne 'ok') && $tries <3) {
 6308:         $tries ++;
 6309:         sleep 1;
 6310:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6311:     }
 6312:     if ($gotlock eq 'ok') {
 6313:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6314:         my ($tmp)=keys(%curr_permissions);
 6315:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6316:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6317:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6318:             if (ref($curr_controls) eq 'HASH') {
 6319:                 foreach my $control_item (keys(%{$curr_controls})) {
 6320:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6321:                     if (defined($todelete{$itemnum})) {
 6322:                         push(@deletions,$file_name."\0".$control_item);
 6323:                     } else {
 6324:                         if (defined($changed_items{$itemnum})) {
 6325:                             $new_control{$changed_items{$itemnum}} = $now;
 6326:                             push(@deletions,$file_name."\0".$control_item);
 6327:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6328:                         } else {
 6329:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6330:                         }
 6331:                     }
 6332:                 }
 6333:             }
 6334:         }
 6335:         my ($group);
 6336:         if (&is_course($domain,$user)) {
 6337:             ($group,my $file) = split(/\//,$file_name,2);
 6338:         }
 6339:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6340:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6341:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6342:         #  remove lock
 6343:         my @del_lock = ($file_name."\0".'locked_access_records');
 6344:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6345:         my $sqlresult =
 6346:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6347:                                     $group);
 6348:     } else {
 6349:         $outcome = "error: could not obtain lockfile\n";  
 6350:     }
 6351:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6352: }
 6353: 
 6354: sub make_public_indefinitely {
 6355:     my ($requrl) = @_;
 6356:     my $now = time;
 6357:     my $action = 'activate';
 6358:     my $aclnum = 0;
 6359:     if (&is_portfolio_url($requrl)) {
 6360:         my (undef,$udom,$unum,$file_name,$group) =
 6361:             &parse_portfolio_url($requrl);
 6362:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6363:         my %access_controls = &get_access_controls($current_perms,
 6364:                                                    $group,$file_name);
 6365:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6366:             my ($num,$scope,$end,$start) = 
 6367:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6368:             if ($scope eq 'public') {
 6369:                 if ($start <= $now && $end == 0) {
 6370:                     $action = 'none';
 6371:                 } else {
 6372:                     $action = 'update';
 6373:                     $aclnum = $num;
 6374:                 }
 6375:                 last;
 6376:             }
 6377:         }
 6378:         if ($action eq 'none') {
 6379:              return 'ok';
 6380:         } else {
 6381:             my %changes;
 6382:             my $newend = 0;
 6383:             my $newstart = $now;
 6384:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6385:             $changes{$action}{$newkey} = {
 6386:                 type => 'public',
 6387:                 time => {
 6388:                     start => $newstart,
 6389:                     end   => $newend,
 6390:                 },
 6391:             };
 6392:             my ($outcome,$deloutcome,$new_values,$translation) =
 6393:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6394:             return $outcome;
 6395:         }
 6396:     } else {
 6397:         return 'invalid';
 6398:     }
 6399: }
 6400: 
 6401: #------------------------------------------------------Get Marked as Read Only
 6402: 
 6403: sub get_marked_as_readonly {
 6404:     my ($domain,$user,$what,$group) = @_;
 6405:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6406:     my @readonly_files;
 6407:     my $cmp1=$what;
 6408:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6409:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6410:         if (defined($group)) {
 6411:             if ($file_name !~ m-^\Q$group\E/-) {
 6412:                 next;
 6413:             }
 6414:         }
 6415:         if (ref($value) eq "ARRAY"){
 6416:             foreach my $stored_what (@{$value}) {
 6417:                 my $cmp2=$stored_what;
 6418:                 if (ref($stored_what) eq 'ARRAY') {
 6419:                     $cmp2=join('',@{$stored_what});
 6420:                 }
 6421:                 if ($cmp1 eq $cmp2) {
 6422:                     push(@readonly_files, $file_name);
 6423:                     last;
 6424:                 } elsif (!defined($what)) {
 6425:                     push(@readonly_files, $file_name);
 6426:                     last;
 6427:                 }
 6428:             }
 6429:         }
 6430:     }
 6431:     return @readonly_files;
 6432: }
 6433: #-----------------------------------------------------------Get Marked as Read Only Hash
 6434: 
 6435: sub get_marked_as_readonly_hash {
 6436:     my ($current_permissions,$group,$what) = @_;
 6437:     my %readonly_files;
 6438:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6439:         if (defined($group)) {
 6440:             if ($file_name !~ m-^\Q$group\E/-) {
 6441:                 next;
 6442:             }
 6443:         }
 6444:         if (ref($value) eq "ARRAY"){
 6445:             foreach my $stored_what (@{$value}) {
 6446:                 if (ref($stored_what) eq 'ARRAY') {
 6447:                     foreach my $lock_descriptor(@{$stored_what}) {
 6448:                         if ($lock_descriptor eq 'graded') {
 6449:                             $readonly_files{$file_name} = 'graded';
 6450:                         } elsif ($lock_descriptor eq 'handback') {
 6451:                             $readonly_files{$file_name} = 'handback';
 6452:                         } else {
 6453:                             if (!exists($readonly_files{$file_name})) {
 6454:                                 $readonly_files{$file_name} = 'locked';
 6455:                             }
 6456:                         }
 6457:                     }
 6458:                 } 
 6459:             }
 6460:         } 
 6461:     }
 6462:     return %readonly_files;
 6463: }
 6464: # ------------------------------------------------------------ Unmark as Read Only
 6465: 
 6466: sub unmark_as_readonly {
 6467:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6468:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6469:     my ($domain,$user,$what,$file_name,$group) = @_;
 6470:     $file_name = &declutter_portfile($file_name);
 6471:     my $symb_crs = $what;
 6472:     if (ref($what)) { $symb_crs=join('',@$what); }
 6473:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6474:     my ($tmp)=keys(%current_permissions);
 6475:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6476:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6477:     foreach my $file (@readonly_files) {
 6478: 	my $clean_file = &declutter_portfile($file);
 6479: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6480: 	my $current_locks = $current_permissions{$file};
 6481:         my @new_locks;
 6482:         my @del_keys;
 6483:         if (ref($current_locks) eq "ARRAY"){
 6484:             foreach my $locker (@{$current_locks}) {
 6485:                 my $compare=$locker;
 6486:                 if (ref($locker) eq 'ARRAY') {
 6487:                     $compare=join('',@{$locker});
 6488:                     if ($compare ne $symb_crs) {
 6489:                         push(@new_locks, $locker);
 6490:                     }
 6491:                 }
 6492:             }
 6493:             if (scalar(@new_locks) > 0) {
 6494:                 $current_permissions{$file} = \@new_locks;
 6495:             } else {
 6496:                 push(@del_keys, $file);
 6497:                 &del('file_permissions',\@del_keys, $domain, $user);
 6498:                 delete($current_permissions{$file});
 6499:             }
 6500:         }
 6501:     }
 6502:     &put('file_permissions',\%current_permissions,$domain,$user);
 6503:     return;
 6504: }
 6505: 
 6506: # ------------------------------------------------------------ Directory lister
 6507: 
 6508: sub dirlist {
 6509:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6510:     $uri=~s/^\///;
 6511:     $uri=~s/\/$//;
 6512:     my ($udom, $uname);
 6513:     if ($getuserdir) {
 6514:         $udom = $userdomain;
 6515:         $uname = $username;
 6516:     } else {
 6517:         (undef,$udom,$uname)=split(/\//,$uri);
 6518:         if(defined($userdomain)) {
 6519:             $udom = $userdomain;
 6520:         }
 6521:         if(defined($username)) {
 6522:             $uname = $username;
 6523:         }
 6524:     }
 6525:     my ($dirRoot,$listing,@listing_results);
 6526: 
 6527:     $dirRoot = $perlvar{'lonDocRoot'};
 6528:     if (defined($getpropath)) {
 6529:         $dirRoot = &propath($udom,$uname);
 6530:         $dirRoot =~ s/\/$//;
 6531:     } elsif (defined($getuserdir)) {
 6532:         my $subdir=$uname.'__';
 6533:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6534:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6535:                    ."/$udom/$subdir/$uname";
 6536:     } elsif (defined($alternateRoot)) {
 6537:         $dirRoot = $alternateRoot;
 6538:     }
 6539: 
 6540:     if($udom) {
 6541:         if($uname) {
 6542:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6543:                               .$getuserdir.':'.&escape($dirRoot)
 6544:                               .':'.&escape($uname).':'.&escape($udom),
 6545:                               &homeserver($uname,$udom));
 6546:             if ($listing eq 'unknown_cmd') {
 6547:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6548:                                   &homeserver($uname,$udom));
 6549:             } else {
 6550:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6551:             }
 6552:             if ($listing eq 'unknown_cmd') {
 6553:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6554: 				  &homeserver($uname,$udom));
 6555:                 @listing_results = split(/:/,$listing);
 6556:             } else {
 6557:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6558:             }
 6559:             return @listing_results;
 6560:         } elsif(!$alternateRoot) {
 6561:             my %allusers;
 6562: 	    my %servers = &get_servers($udom,'library');
 6563:  	    foreach my $tryserver (keys(%servers)) {
 6564:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6565:                                   &escape($udom),$tryserver);
 6566:                 if ($listing eq 'unknown_cmd') {
 6567: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6568: 				      $udom, $tryserver);
 6569:                 } else {
 6570:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6571:                 }
 6572: 		if ($listing eq 'unknown_cmd') {
 6573: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6574: 				      $udom, $tryserver);
 6575: 		    @listing_results = split(/:/,$listing);
 6576: 		} else {
 6577: 		    @listing_results =
 6578: 			map { &unescape($_); } split(/:/,$listing);
 6579: 		}
 6580: 		if ($listing_results[0] ne 'no_such_dir' && 
 6581: 		    $listing_results[0] ne 'empty'       &&
 6582: 		    $listing_results[0] ne 'con_lost') {
 6583: 		    foreach my $line (@listing_results) {
 6584: 			my ($entry) = split(/&/,$line,2);
 6585: 			$allusers{$entry} = 1;
 6586: 		    }
 6587: 		}
 6588:             }
 6589:             my $alluserstr='';
 6590:             foreach my $user (sort(keys(%allusers))) {
 6591:                 $alluserstr.=$user.'&user:';
 6592:             }
 6593:             $alluserstr=~s/:$//;
 6594:             return split(/:/,$alluserstr);
 6595:         } else {
 6596:             return ('missing user name');
 6597:         }
 6598:     } elsif(!defined($getpropath)) {
 6599:         my @all_domains = sort(&all_domains());
 6600:         foreach my $domain (@all_domains) {
 6601:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6602:         }
 6603:         return @all_domains;
 6604:     } else {
 6605:         return ('missing domain');
 6606:     }
 6607: }
 6608: 
 6609: # --------------------------------------------- GetFileTimestamp
 6610: # This function utilizes dirlist and returns the date stamp for
 6611: # when it was last modified.  It will also return an error of -1
 6612: # if an error occurs
 6613: 
 6614: sub GetFileTimestamp {
 6615:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6616:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6617:     $studentName   = &LONCAPA::clean_username($studentName);
 6618:     my ($fileStat) = 
 6619:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6620:                                  undef,$getuserdir);
 6621:     my @stats = split('&', $fileStat);
 6622:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6623:         # @stats contains first the filename, then the stat output
 6624:         return $stats[10]; # so this is 10 instead of 9.
 6625:     } else {
 6626:         return -1;
 6627:     }
 6628: }
 6629: 
 6630: sub stat_file {
 6631:     my ($uri) = @_;
 6632:     $uri = &clutter_with_no_wrapper($uri);
 6633: 
 6634:     my ($udom,$uname,$file);
 6635:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6636: 	($udom,$uname,$file) =
 6637: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6638: 	$file = 'userfiles/'.$file;
 6639:     }
 6640:     if ($uri =~ m-^/res/-) {
 6641: 	($udom,$uname) = 
 6642: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6643: 	$file = $uri;
 6644:     }
 6645: 
 6646:     if (!$udom || !$uname || !$file) {
 6647: 	# unable to handle the uri
 6648: 	return ();
 6649:     }
 6650:     my $getpropath;
 6651:     if ($file =~ /^userfiles\//) {
 6652:         $getpropath = 1;
 6653:     }
 6654:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6655:     my @stats = split('&', $result);
 6656:     
 6657:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6658: 	shift(@stats); #filename is first
 6659: 	return @stats;
 6660:     }
 6661:     return ();
 6662: }
 6663: 
 6664: # -------------------------------------------------------- Value of a Condition
 6665: 
 6666: # gets the value of a specific preevaluated condition
 6667: #    stored in the string  $env{user.state.<cid>}
 6668: # or looks up a condition reference in the bighash and if if hasn't
 6669: # already been evaluated recurses into docondval to get the value of
 6670: # the condition, then memoizing it to 
 6671: #   $env{user.state.<cid>.<condition>}
 6672: sub directcondval {
 6673:     my $number=shift;
 6674:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6675: 	&Apache::lonuserstate::evalstate();
 6676:     }
 6677:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6678: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6679:     } elsif ($number =~ /^_/) {
 6680: 	my $sub_condition;
 6681: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6682: 		&GDBM_READER(),0640)) {
 6683: 	    $sub_condition=$bighash{'conditions'.$number};
 6684: 	    untie(%bighash);
 6685: 	}
 6686: 	my $value = &docondval($sub_condition);
 6687: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6688: 	return $value;
 6689:     }
 6690:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6691:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6692:     } else {
 6693:        return 2;
 6694:     }
 6695: }
 6696: 
 6697: # get the collection of conditions for this resource
 6698: sub condval {
 6699:     my $condidx=shift;
 6700:     my $allpathcond='';
 6701:     foreach my $cond (split(/\|/,$condidx)) {
 6702: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6703: 	    $allpathcond.=
 6704: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6705: 	}
 6706:     }
 6707:     $allpathcond=~s/\|$//;
 6708:     return &docondval($allpathcond);
 6709: }
 6710: 
 6711: #evaluates an expression of conditions
 6712: sub docondval {
 6713:     my ($allpathcond) = @_;
 6714:     my $result=0;
 6715:     if ($env{'request.course.id'}
 6716: 	&& defined($allpathcond)) {
 6717: 	my $operand='|';
 6718: 	my @stack;
 6719: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6720: 	    if ($chunk eq '(') {
 6721: 		push @stack,($operand,$result);
 6722: 	    } elsif ($chunk eq ')') {
 6723: 		my $before=pop @stack;
 6724: 		if (pop @stack eq '&') {
 6725: 		    $result=$result>$before?$before:$result;
 6726: 		} else {
 6727: 		    $result=$result>$before?$result:$before;
 6728: 		}
 6729: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6730: 		$operand=$chunk;
 6731: 	    } else {
 6732: 		my $new=directcondval($chunk);
 6733: 		if ($operand eq '&') {
 6734: 		    $result=$result>$new?$new:$result;
 6735: 		} else {
 6736: 		    $result=$result>$new?$result:$new;
 6737: 		}
 6738: 	    }
 6739: 	}
 6740:     }
 6741:     return $result;
 6742: }
 6743: 
 6744: # ---------------------------------------------------- Devalidate courseresdata
 6745: 
 6746: sub devalidatecourseresdata {
 6747:     my ($coursenum,$coursedomain)=@_;
 6748:     my $hashid=$coursenum.':'.$coursedomain;
 6749:     &devalidate_cache_new('courseres',$hashid);
 6750: }
 6751: 
 6752: 
 6753: # --------------------------------------------------- Course Resourcedata Query
 6754: #
 6755: #  Parameters:
 6756: #      $coursenum    - Number of the course.
 6757: #      $coursedomain - Domain at which the course was created.
 6758: #  Returns:
 6759: #     A hash of the course parameters along (I think) with timestamps
 6760: #     and version info.
 6761: 
 6762: sub get_courseresdata {
 6763:     my ($coursenum,$coursedomain)=@_;
 6764:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6765:     my $hashid=$coursenum.':'.$coursedomain;
 6766:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6767:     my %dumpreply;
 6768:     unless (defined($cached)) {
 6769: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6770: 	$result=\%dumpreply;
 6771: 	my ($tmp) = keys(%dumpreply);
 6772: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6773: 	    &do_cache_new('courseres',$hashid,$result,600);
 6774: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6775: 	    return $tmp;
 6776: 	} elsif ($tmp =~ /^(error)/) {
 6777: 	    $result=undef;
 6778: 	    &do_cache_new('courseres',$hashid,$result,600);
 6779: 	}
 6780:     }
 6781:     return $result;
 6782: }
 6783: 
 6784: sub devalidateuserresdata {
 6785:     my ($uname,$udom)=@_;
 6786:     my $hashid="$udom:$uname";
 6787:     &devalidate_cache_new('userres',$hashid);
 6788: }
 6789: 
 6790: sub get_userresdata {
 6791:     my ($uname,$udom)=@_;
 6792:     #most student don\'t have any data set, check if there is some data
 6793:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6794: 
 6795:     my $hashid="$udom:$uname";
 6796:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6797:     if (!defined($cached)) {
 6798: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6799: 	$result=\%resourcedata;
 6800: 	&do_cache_new('userres',$hashid,$result,600);
 6801:     }
 6802:     my ($tmp)=keys(%$result);
 6803:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6804: 	return $result;
 6805:     }
 6806:     #error 2 occurs when the .db doesn't exist
 6807:     if ($tmp!~/error: 2 /) {
 6808: 	&logthis("<font color=\"blue\">WARNING:".
 6809: 		 " Trying to get resource data for ".
 6810: 		 $uname." at ".$udom.": ".
 6811: 		 $tmp."</font>");
 6812:     } elsif ($tmp=~/error: 2 /) {
 6813: 	#&EXT_cache_set($udom,$uname);
 6814: 	&do_cache_new('userres',$hashid,undef,600);
 6815: 	undef($tmp); # not really an error so don't send it back
 6816:     }
 6817:     return $tmp;
 6818: }
 6819: #----------------------------------------------- resdata - return resource data
 6820: #  Purpose:
 6821: #    Return resource data for either users or for a course.
 6822: #  Parameters:
 6823: #     $name      - Course/user name.
 6824: #     $domain    - Name of the domain the user/course is registered on.
 6825: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6826: #     @which     - Array of names of resources desired.
 6827: #  Returns:
 6828: #     The value of the first reasource in @which that is found in the
 6829: #     resource hash.
 6830: #  Exceptional Conditions:
 6831: #     If the $type passed in is not valid (not the string 'course' or 
 6832: #     'user', an undefined  reference is returned.
 6833: #     If none of the resources are found, an undef is returned
 6834: sub resdata {
 6835:     my ($name,$domain,$type,@which)=@_;
 6836:     my $result;
 6837:     if ($type eq 'course') {
 6838: 	$result=&get_courseresdata($name,$domain);
 6839:     } elsif ($type eq 'user') {
 6840: 	$result=&get_userresdata($name,$domain);
 6841:     }
 6842:     if (!ref($result)) { return $result; }    
 6843:     foreach my $item (@which) {
 6844: 	if (defined($result->{$item->[0]})) {
 6845: 	    return [$result->{$item->[0]},$item->[1]];
 6846: 	}
 6847:     }
 6848:     return undef;
 6849: }
 6850: 
 6851: #
 6852: # EXT resource caching routines
 6853: #
 6854: 
 6855: sub clear_EXT_cache_status {
 6856:     &delenv('cache.EXT.');
 6857: }
 6858: 
 6859: sub EXT_cache_status {
 6860:     my ($target_domain,$target_user) = @_;
 6861:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6862:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6863:         # We know already the user has no data
 6864:         return 1;
 6865:     } else {
 6866:         return 0;
 6867:     }
 6868: }
 6869: 
 6870: sub EXT_cache_set {
 6871:     my ($target_domain,$target_user) = @_;
 6872:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6873:     #&appenv({$cachename => time});
 6874: }
 6875: 
 6876: # --------------------------------------------------------- Value of a Variable
 6877: sub EXT {
 6878: 
 6879:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6880:     unless ($varname) { return ''; }
 6881:     #get real user name/domain, courseid and symb
 6882:     my $courseid;
 6883:     my $publicuser;
 6884:     if ($symbparm) {
 6885: 	$symbparm=&get_symb_from_alias($symbparm);
 6886:     }
 6887:     if (!($uname && $udom)) {
 6888:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6889:       if (!$symbparm) {	$symbparm=$cursymb; }
 6890:     } else {
 6891: 	$courseid=$env{'request.course.id'};
 6892:     }
 6893:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6894:     my $rest;
 6895:     if (defined($therest[0])) {
 6896:        $rest=join('.',@therest);
 6897:     } else {
 6898:        $rest='';
 6899:     }
 6900: 
 6901:     my $qualifierrest=$qualifier;
 6902:     if ($rest) { $qualifierrest.='.'.$rest; }
 6903:     my $spacequalifierrest=$space;
 6904:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6905:     if ($realm eq 'user') {
 6906: # --------------------------------------------------------------- user.resource
 6907: 	if ($space eq 'resource') {
 6908: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6909: 		  || defined($Apache::lonhomework::parsing_a_task))
 6910: 		 &&
 6911: 		 ($symbparm eq &symbread()) ) {	
 6912: 		# if we are in the middle of processing the resource the
 6913: 		# get the value we are planning on committing
 6914:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6915:                     return $Apache::lonhomework::results{$qualifierrest};
 6916:                 } else {
 6917:                     return $Apache::lonhomework::history{$qualifierrest};
 6918:                 }
 6919: 	    } else {
 6920: 		my %restored;
 6921: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6922: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6923: 		} else {
 6924: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6925: 		}
 6926: 		return $restored{$qualifierrest};
 6927: 	    }
 6928: # ----------------------------------------------------------------- user.access
 6929:         } elsif ($space eq 'access') {
 6930: 	    # FIXME - not supporting calls for a specific user
 6931:             return &allowed($qualifier,$rest);
 6932: # ------------------------------------------ user.preferences, user.environment
 6933:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6934: 	    if (($uname eq $env{'user.name'}) &&
 6935: 		($udom eq $env{'user.domain'})) {
 6936: 		return $env{join('.',('environment',$qualifierrest))};
 6937: 	    } else {
 6938: 		my %returnhash;
 6939: 		if (!$publicuser) {
 6940: 		    %returnhash=&userenvironment($udom,$uname,
 6941: 						 $qualifierrest);
 6942: 		}
 6943: 		return $returnhash{$qualifierrest};
 6944: 	    }
 6945: # ----------------------------------------------------------------- user.course
 6946:         } elsif ($space eq 'course') {
 6947: 	    # FIXME - not supporting calls for a specific user
 6948:             return $env{join('.',('request.course',$qualifier))};
 6949: # ------------------------------------------------------------------- user.role
 6950:         } elsif ($space eq 'role') {
 6951: 	    # FIXME - not supporting calls for a specific user
 6952:             my ($role,$where)=split(/\./,$env{'request.role'});
 6953:             if ($qualifier eq 'value') {
 6954: 		return $role;
 6955:             } elsif ($qualifier eq 'extent') {
 6956:                 return $where;
 6957:             }
 6958: # ----------------------------------------------------------------- user.domain
 6959:         } elsif ($space eq 'domain') {
 6960:             return $udom;
 6961: # ------------------------------------------------------------------- user.name
 6962:         } elsif ($space eq 'name') {
 6963:             return $uname;
 6964: # ---------------------------------------------------- Any other user namespace
 6965:         } else {
 6966: 	    my %reply;
 6967: 	    if (!$publicuser) {
 6968: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6969: 	    }
 6970: 	    return $reply{$qualifierrest};
 6971:         }
 6972:     } elsif ($realm eq 'query') {
 6973: # ---------------------------------------------- pull stuff out of query string
 6974:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6975: 						[$spacequalifierrest]);
 6976: 	return $env{'form.'.$spacequalifierrest}; 
 6977:    } elsif ($realm eq 'request') {
 6978: # ------------------------------------------------------------- request.browser
 6979:         if ($space eq 'browser') {
 6980: 	    if ($qualifier eq 'textremote') {
 6981: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6982: 		    return 1;
 6983: 		} else {
 6984: 		    return 0;
 6985: 		}
 6986: 	    } else {
 6987: 		return $env{'browser.'.$qualifier};
 6988: 	    }
 6989: # ------------------------------------------------------------ request.filename
 6990:         } else {
 6991:             return $env{'request.'.$spacequalifierrest};
 6992:         }
 6993:     } elsif ($realm eq 'course') {
 6994: # ---------------------------------------------------------- course.description
 6995:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6996:     } elsif ($realm eq 'resource') {
 6997: 
 6998: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6999: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7000: 	}
 7001: 
 7002: 	if ($space eq 'title') {
 7003: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7004: 	    return &gettitle($symbparm);
 7005: 	}
 7006: 	
 7007: 	if ($space eq 'map') {
 7008: 	    my ($map) = &decode_symb($symbparm);
 7009: 	    return &symbread($map);
 7010: 	}
 7011: 	if ($space eq 'filename') {
 7012: 	    if ($symbparm) {
 7013: 		return &clutter((&decode_symb($symbparm))[2]);
 7014: 	    }
 7015: 	    return &hreflocation('',$env{'request.filename'});
 7016: 	}
 7017: 
 7018: 	my ($section, $group, @groups);
 7019: 	my ($courselevelm,$courselevel);
 7020: 	if ($symbparm && defined($courseid) && 
 7021: 	    $courseid eq $env{'request.course.id'}) {
 7022: 
 7023: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7024: 
 7025: # ----------------------------------------------------- Cascading lookup scheme
 7026: 	    my $symbp=$symbparm;
 7027: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7028: 
 7029: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7030: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7031: 
 7032: 	    if (($env{'user.name'} eq $uname) &&
 7033: 		($env{'user.domain'} eq $udom)) {
 7034: 		$section=$env{'request.course.sec'};
 7035:                 @groups = split(/:/,$env{'request.course.groups'});  
 7036:                 @groups=&sort_course_groups($courseid,@groups); 
 7037: 	    } else {
 7038: 		if (! defined($usection)) {
 7039: 		    $section=&getsection($udom,$uname,$courseid);
 7040: 		} else {
 7041: 		    $section = $usection;
 7042: 		}
 7043:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7044: 	    }
 7045: 
 7046: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7047: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7048: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7049: 
 7050: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7051: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7052: 	    $courselevelm=$courseid.'.'.$mapparm;
 7053: 
 7054: # ----------------------------------------------------------- first, check user
 7055: 
 7056: 	    my $userreply=&resdata($uname,$udom,'user',
 7057: 				       ([$courselevelr,'resource'],
 7058: 					[$courselevelm,'map'     ],
 7059: 					[$courselevel, 'course'  ]));
 7060: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7061: 
 7062: # ------------------------------------------------ second, check some of course
 7063:             my $coursereply;
 7064:             if (@groups > 0) {
 7065:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7066:                                        $mapparm,$spacequalifierrest);
 7067:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7068:             }
 7069: 
 7070: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7071: 				  $env{'course.'.$courseid.'.domain'},
 7072: 				  'course',
 7073: 				  ([$seclevelr,   'resource'],
 7074: 				   [$seclevelm,   'map'     ],
 7075: 				   [$seclevel,    'course'  ],
 7076: 				   [$courselevelr,'resource']));
 7077: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7078: 
 7079: # ------------------------------------------------------ third, check map parms
 7080: 	    my %parmhash=();
 7081: 	    my $thisparm='';
 7082: 	    if (tie(%parmhash,'GDBM_File',
 7083: 		    $env{'request.course.fn'}.'_parms.db',
 7084: 		    &GDBM_READER(),0640)) {
 7085: 		$thisparm=$parmhash{$symbparm};
 7086: 		untie(%parmhash);
 7087: 	    }
 7088: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7089: 	}
 7090: # ------------------------------------------ fourth, look in resource metadata
 7091: 
 7092: 	$spacequalifierrest=~s/\./\_/;
 7093: 	my $filename;
 7094: 	if (!$symbparm) { $symbparm=&symbread(); }
 7095: 	if ($symbparm) {
 7096: 	    $filename=(&decode_symb($symbparm))[2];
 7097: 	} else {
 7098: 	    $filename=$env{'request.filename'};
 7099: 	}
 7100: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7101: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7102: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7103: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7104: 
 7105: # ---------------------------------------------- fourth, look in rest of course
 7106: 	if ($symbparm && defined($courseid) && 
 7107: 	    $courseid eq $env{'request.course.id'}) {
 7108: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7109: 				     $env{'course.'.$courseid.'.domain'},
 7110: 				     'course',
 7111: 				     ([$courselevelm,'map'   ],
 7112: 				      [$courselevel, 'course']));
 7113: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7114: 	}
 7115: # ------------------------------------------------------------------ Cascade up
 7116: 	unless ($space eq '0') {
 7117: 	    my @parts=split(/_/,$space);
 7118: 	    my $id=pop(@parts);
 7119: 	    my $part=join('_',@parts);
 7120: 	    if ($part eq '') { $part='0'; }
 7121: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7122: 				 $symbparm,$udom,$uname,$section,1);
 7123: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7124: 	}
 7125: 	if ($recurse) { return undef; }
 7126: 	my $pack_def=&packages_tab_default($filename,$varname);
 7127: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7128: # ---------------------------------------------------- Any other user namespace
 7129:     } elsif ($realm eq 'environment') {
 7130: # ----------------------------------------------------------------- environment
 7131: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7132: 	    return $env{'environment.'.$spacequalifierrest};
 7133: 	} else {
 7134: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7135: 		return '';
 7136: 	    }
 7137: 	    my %returnhash=&userenvironment($udom,$uname,
 7138: 					    $spacequalifierrest);
 7139: 	    return $returnhash{$spacequalifierrest};
 7140: 	}
 7141:     } elsif ($realm eq 'system') {
 7142: # ----------------------------------------------------------------- system.time
 7143: 	if ($space eq 'time') {
 7144: 	    return time;
 7145:         }
 7146:     } elsif ($realm eq 'server') {
 7147: # ----------------------------------------------------------------- system.time
 7148: 	if ($space eq 'name') {
 7149: 	    return $ENV{'SERVER_NAME'};
 7150:         }
 7151:     }
 7152:     return '';
 7153: }
 7154: 
 7155: sub get_reply {
 7156:     my ($reply_value) = @_;
 7157:     if (ref($reply_value) eq 'ARRAY') {
 7158:         if (wantarray) {
 7159: 	    return @$reply_value;
 7160:         }
 7161:         return $reply_value->[0];
 7162:     } else {
 7163:         return $reply_value;
 7164:     }
 7165: }
 7166: 
 7167: sub check_group_parms {
 7168:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7169:     my @groupitems = ();
 7170:     my $resultitem;
 7171:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7172:     foreach my $group (@{$groups}) {
 7173:         foreach my $level (@levels) {
 7174:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7175:              push(@groupitems,[$item,$level->[1]]);
 7176:         }
 7177:     }
 7178:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7179:                             $env{'course.'.$courseid.'.domain'},
 7180:                                      'course',@groupitems);
 7181:     return $coursereply;
 7182: }
 7183: 
 7184: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7185:     my ($courseid,@groups) = @_;
 7186:     @groups = sort(@groups);
 7187:     return @groups;
 7188: }
 7189: 
 7190: sub packages_tab_default {
 7191:     my ($uri,$varname)=@_;
 7192:     my (undef,$part,$name)=split(/\./,$varname);
 7193: 
 7194:     my (@extension,@specifics,$do_default);
 7195:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7196: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7197: 	if ($pack_type eq 'default') {
 7198: 	    $do_default=1;
 7199: 	} elsif ($pack_type eq 'extension') {
 7200: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7201: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7202: 	    # only look at packages defaults for packages that this id is
 7203: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7204: 	}
 7205:     }
 7206:     # first look for a package that matches the requested part id
 7207:     foreach my $package (@specifics) {
 7208: 	my (undef,$pack_type,$pack_part)=@{$package};
 7209: 	next if ($pack_part ne $part);
 7210: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7211: 	    return $packagetab{"$pack_type&$name&default"};
 7212: 	}
 7213:     }
 7214:     # look for any possible matching non extension_ package
 7215:     foreach my $package (@specifics) {
 7216: 	my (undef,$pack_type,$pack_part)=@{$package};
 7217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7218: 	    return $packagetab{"$pack_type&$name&default"};
 7219: 	}
 7220: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7221: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7222: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7223: 	}
 7224:     }
 7225:     # look for any posible extension_ match
 7226:     foreach my $package (@extension) {
 7227: 	my ($package,$pack_type)=@{$package};
 7228: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7229: 	    return $packagetab{"$pack_type&$name&default"};
 7230: 	}
 7231: 	if (defined($packagetab{$package."&$name&default"})) {
 7232: 	    return $packagetab{$package."&$name&default"};
 7233: 	}
 7234:     }
 7235:     # look for a global default setting
 7236:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7237: 	return $packagetab{"default&$name&default"};
 7238:     }
 7239:     return undef;
 7240: }
 7241: 
 7242: sub add_prefix_and_part {
 7243:     my ($prefix,$part)=@_;
 7244:     my $keyroot;
 7245:     if (defined($prefix) && $prefix !~ /^__/) {
 7246: 	# prefix that has a part already
 7247: 	$keyroot=$prefix;
 7248:     } elsif (defined($prefix)) {
 7249: 	# prefix that is missing a part
 7250: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7251:     } else {
 7252: 	# no prefix at all
 7253: 	if (defined($part)) { $keyroot='_'.$part; }
 7254:     }
 7255:     return $keyroot;
 7256: }
 7257: 
 7258: # ---------------------------------------------------------------- Get metadata
 7259: 
 7260: my %metaentry;
 7261: sub metadata {
 7262:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7263:     $uri=&declutter($uri);
 7264:     # if it is a non metadata possible uri return quickly
 7265:     if (($uri eq '') || 
 7266: 	(($uri =~ m|^/*adm/|) && 
 7267: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7268:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7269: 	return undef;
 7270:     }
 7271:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7272: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7273: 	return undef;
 7274:     }
 7275:     my $filename=$uri;
 7276:     $uri=~s/\.meta$//;
 7277: #
 7278: # Is the metadata already cached?
 7279: # Look at timestamp of caching
 7280: # Everything is cached by the main uri, libraries are never directly cached
 7281: #
 7282:     if (!defined($liburi)) {
 7283: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7284: 	if (defined($cached)) { return $result->{':'.$what}; }
 7285:     }
 7286:     {
 7287: #
 7288: # Is this a recursive call for a library?
 7289: #
 7290: #	if (! exists($metacache{$uri})) {
 7291: #	    $metacache{$uri}={};
 7292: #	}
 7293: 	my $cachetime = 60*60;
 7294:         if ($liburi) {
 7295: 	    $liburi=&declutter($liburi);
 7296:             $filename=$liburi;
 7297:         } else {
 7298: 	    &devalidate_cache_new('meta',$uri);
 7299: 	    undef(%metaentry);
 7300: 	}
 7301:         my %metathesekeys=();
 7302:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7303: 	my $metastring;
 7304: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7305: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7306: 	    $metastring = 
 7307: 		&Apache::lonnet::ssi_body($which,
 7308: 					  ('grade_target' => 'meta'));
 7309: 	    $cachetime = 1; # only want this cached in the child not long term
 7310: 	} elsif ($uri !~ m -^(editupload)/-) {
 7311: 	    my $file=&filelocation('',&clutter($filename));
 7312: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7313: 	    $metastring=&getfile($file);
 7314: 	}
 7315:         my $parser=HTML::LCParser->new(\$metastring);
 7316:         my $token;
 7317:         undef %metathesekeys;
 7318:         while ($token=$parser->get_token) {
 7319: 	    if ($token->[0] eq 'S') {
 7320: 		if (defined($token->[2]->{'package'})) {
 7321: #
 7322: # This is a package - get package info
 7323: #
 7324: 		    my $package=$token->[2]->{'package'};
 7325: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7326: 		    if (defined($token->[2]->{'id'})) { 
 7327: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7328: 		    }
 7329: 		    if ($metaentry{':packages'}) {
 7330: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7331: 		    } else {
 7332: 			$metaentry{':packages'}=$package.$keyroot;
 7333: 		    }
 7334: 		    foreach my $pack_entry (keys(%packagetab)) {
 7335: 			my $part=$keyroot;
 7336: 			$part=~s/^\_//;
 7337: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7338: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7339: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7340: 			    # ignore package.tab specified default values
 7341:                             # here &package_tab_default() will fetch those
 7342: 			    if ($subp eq 'default') { next; }
 7343: 			    my $value=$packagetab{$pack_entry};
 7344: 			    my $unikey;
 7345: 			    if ($pack =~ /_0$/) {
 7346: 				$unikey='parameter_0_'.$name;
 7347: 				$part=0;
 7348: 			    } else {
 7349: 				$unikey='parameter'.$keyroot.'_'.$name;
 7350: 			    }
 7351: 			    if ($subp eq 'display') {
 7352: 				$value.=' [Part: '.$part.']';
 7353: 			    }
 7354: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7355: 			    $metathesekeys{$unikey}=1;
 7356: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7357: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7358: 			    }
 7359: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7360: 				$metaentry{':'.$unikey}=
 7361: 				    $metaentry{':'.$unikey.'.default'};
 7362: 			    }
 7363: 			}
 7364: 		    }
 7365: 		} else {
 7366: #
 7367: # This is not a package - some other kind of start tag
 7368: #
 7369: 		    my $entry=$token->[1];
 7370: 		    my $unikey;
 7371: 		    if ($entry eq 'import') {
 7372: 			$unikey='';
 7373: 		    } else {
 7374: 			$unikey=$entry;
 7375: 		    }
 7376: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7377: 
 7378: 		    if (defined($token->[2]->{'id'})) { 
 7379: 			$unikey.='_'.$token->[2]->{'id'}; 
 7380: 		    }
 7381: 
 7382: 		    if ($entry eq 'import') {
 7383: #
 7384: # Importing a library here
 7385: #
 7386: 			if ($depthcount<20) {
 7387: 			    my $location=$parser->get_text('/import');
 7388: 			    my $dir=$filename;
 7389: 			    $dir=~s|[^/]*$||;
 7390: 			    $location=&filelocation($dir,$location);
 7391: 			    my $metadata = 
 7392: 				&metadata($uri,'keys', $location,$unikey,
 7393: 					  $depthcount+1);
 7394: 			    foreach my $meta (split(',',$metadata)) {
 7395: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7396: 				$metathesekeys{$meta}=1;
 7397: 			    }
 7398: 			}
 7399: 		    } else { 
 7400: 			
 7401: 			if (defined($token->[2]->{'name'})) { 
 7402: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7403: 			}
 7404: 			$metathesekeys{$unikey}=1;
 7405: 			foreach my $param (@{$token->[3]}) {
 7406: 			    $metaentry{':'.$unikey.'.'.$param} =
 7407: 				$token->[2]->{$param};
 7408: 			}
 7409: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7410: 			my $default=$metaentry{':'.$unikey.'.default'};
 7411: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7412: 		 # only ws inside the tag, and not in default, so use default
 7413: 		 # as value
 7414: 			    $metaentry{':'.$unikey}=$default;
 7415: 			} elsif ( $internaltext =~ /\S/ ) {
 7416: 		  # something interesting inside the tag
 7417: 			    $metaentry{':'.$unikey}=$internaltext;
 7418: 			} else {
 7419: 		  # no interesting values, don't set a default
 7420: 			}
 7421: # end of not-a-package not-a-library import
 7422: 		    }
 7423: # end of not-a-package start tag
 7424: 		}
 7425: # the next is the end of "start tag"
 7426: 	    }
 7427: 	}
 7428: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7429: 	$extension = lc($extension);
 7430: 	if ($extension eq 'htm') { $extension='html'; }
 7431: 
 7432: 	foreach my $key (keys(%packagetab)) {
 7433: 	    #no specific packages #how's our extension
 7434: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7435: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7436: 					 \%metathesekeys);
 7437: 	}
 7438: 
 7439: 	if (!exists($metaentry{':packages'})
 7440: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7441: 	    foreach my $key (keys(%packagetab)) {
 7442: 		#no specific packages well let's get default then
 7443: 		if ($key!~/^default&/) { next; }
 7444: 		&metadata_create_package_def($uri,$key,'default',
 7445: 					     \%metathesekeys);
 7446: 	    }
 7447: 	}
 7448: # are there custom rights to evaluate
 7449: 	if ($metaentry{':copyright'} eq 'custom') {
 7450: 
 7451:     #
 7452:     # Importing a rights file here
 7453:     #
 7454: 	    unless ($depthcount) {
 7455: 		my $location=$metaentry{':customdistributionfile'};
 7456: 		my $dir=$filename;
 7457: 		$dir=~s|[^/]*$||;
 7458: 		$location=&filelocation($dir,$location);
 7459: 		my $rights_metadata =
 7460: 		    &metadata($uri,'keys',$location,'_rights',
 7461: 			      $depthcount+1);
 7462: 		foreach my $rights (split(',',$rights_metadata)) {
 7463: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7464: 		    $metathesekeys{$rights}=1;
 7465: 		}
 7466: 	    }
 7467: 	}
 7468: 	# uniqifiy package listing
 7469: 	my %seen;
 7470: 	my @uniq_packages =
 7471: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7472: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7473: 
 7474: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7475: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7476: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7477: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7478: # this is the end of "was not already recently cached
 7479:     }
 7480:     return $metaentry{':'.$what};
 7481: }
 7482: 
 7483: sub metadata_create_package_def {
 7484:     my ($uri,$key,$package,$metathesekeys)=@_;
 7485:     my ($pack,$name,$subp)=split(/\&/,$key);
 7486:     if ($subp eq 'default') { next; }
 7487:     
 7488:     if (defined($metaentry{':packages'})) {
 7489: 	$metaentry{':packages'}.=','.$package;
 7490:     } else {
 7491: 	$metaentry{':packages'}=$package;
 7492:     }
 7493:     my $value=$packagetab{$key};
 7494:     my $unikey;
 7495:     $unikey='parameter_0_'.$name;
 7496:     $metaentry{':'.$unikey.'.part'}=0;
 7497:     $$metathesekeys{$unikey}=1;
 7498:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7499: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7500:     }
 7501:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7502: 	$metaentry{':'.$unikey}=
 7503: 	    $metaentry{':'.$unikey.'.default'};
 7504:     }
 7505: }
 7506: 
 7507: sub metadata_generate_part0 {
 7508:     my ($metadata,$metacache,$uri) = @_;
 7509:     my %allnames;
 7510:     foreach my $metakey (keys(%$metadata)) {
 7511: 	if ($metakey=~/^parameter\_(.*)/) {
 7512: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7513: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7514: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7515: 	    $allnames{$name}=$part;
 7516: 	  }
 7517: 	}
 7518:     }
 7519:     foreach my $name (keys(%allnames)) {
 7520:       $$metadata{"parameter_0_$name"}=1;
 7521:       my $key=":parameter_0_$name";
 7522:       $$metacache{"$key.part"}='0';
 7523:       $$metacache{"$key.name"}=$name;
 7524:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7525: 					   $allnames{$name}.'_'.$name.
 7526: 					   '.type'};
 7527:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7528: 			     '.display'};
 7529:       my $expr='[Part: '.$allnames{$name}.']';
 7530:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7531:       $$metacache{"$key.display"}=$olddis;
 7532:     }
 7533: }
 7534: 
 7535: # ------------------------------------------------------ Devalidate title cache
 7536: 
 7537: sub devalidate_title_cache {
 7538:     my ($url)=@_;
 7539:     if (!$env{'request.course.id'}) { return; }
 7540:     my $symb=&symbread($url);
 7541:     if (!$symb) { return; }
 7542:     my $key=$env{'request.course.id'}."\0".$symb;
 7543:     &devalidate_cache_new('title',$key);
 7544: }
 7545: 
 7546: # ------------------------------------------------- Get the title of a resource
 7547: 
 7548: sub gettitle {
 7549:     my $urlsymb=shift;
 7550:     my $symb=&symbread($urlsymb);
 7551:     if ($symb) {
 7552: 	my $key=$env{'request.course.id'}."\0".$symb;
 7553: 	my ($result,$cached)=&is_cached_new('title',$key);
 7554: 	if (defined($cached)) { 
 7555: 	    return $result;
 7556: 	}
 7557: 	my ($map,$resid,$url)=&decode_symb($symb);
 7558: 	my $title='';
 7559: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7560: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7561: 	} else {
 7562: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7563: 		    &GDBM_READER(),0640)) {
 7564: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7565: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7566: 		untie(%bighash);
 7567: 	    }
 7568: 	}
 7569: 	$title=~s/\&colon\;/\:/gs;
 7570: 	if ($title) {
 7571: 	    return &do_cache_new('title',$key,$title,600);
 7572: 	}
 7573: 	$urlsymb=$url;
 7574:     }
 7575:     my $title=&metadata($urlsymb,'title');
 7576:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7577:     return $title;
 7578: }
 7579: 
 7580: sub get_slot {
 7581:     my ($which,$cnum,$cdom)=@_;
 7582:     if (!$cnum || !$cdom) {
 7583: 	(undef,my $courseid)=&whichuser();
 7584: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7585: 	$cnum=$env{'course.'.$courseid.'.num'};
 7586:     }
 7587:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7588:     my %slotinfo;
 7589:     if (exists($remembered{$key})) {
 7590: 	$slotinfo{$which} = $remembered{$key};
 7591:     } else {
 7592: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7593: 	&Apache::lonhomework::showhash(%slotinfo);
 7594: 	my ($tmp)=keys(%slotinfo);
 7595: 	if ($tmp=~/^error:/) { return (); }
 7596: 	$remembered{$key} = $slotinfo{$which};
 7597:     }
 7598:     if (ref($slotinfo{$which}) eq 'HASH') {
 7599: 	return %{$slotinfo{$which}};
 7600:     }
 7601:     return $slotinfo{$which};
 7602: }
 7603: # ------------------------------------------------- Update symbolic store links
 7604: 
 7605: sub symblist {
 7606:     my ($mapname,%newhash)=@_;
 7607:     $mapname=&deversion(&declutter($mapname));
 7608:     my %hash;
 7609:     if (($env{'request.course.fn'}) && (%newhash)) {
 7610:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7611:                       &GDBM_WRCREAT(),0640)) {
 7612: 	    foreach my $url (keys %newhash) {
 7613: 		next if ($url eq 'last_known'
 7614: 			 && $env{'form.no_update_last_known'});
 7615: 		$hash{declutter($url)}=&encode_symb($mapname,
 7616: 						    $newhash{$url}->[1],
 7617: 						    $newhash{$url}->[0]);
 7618:             }
 7619:             if (untie(%hash)) {
 7620: 		return 'ok';
 7621:             }
 7622:         }
 7623:     }
 7624:     return 'error';
 7625: }
 7626: 
 7627: # --------------------------------------------------------------- Verify a symb
 7628: 
 7629: sub symbverify {
 7630:     my ($symb,$thisurl)=@_;
 7631:     my $thisfn=$thisurl;
 7632:     $thisfn=&declutter($thisfn);
 7633: # direct jump to resource in page or to a sequence - will construct own symbs
 7634:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7635: # check URL part
 7636:     my ($map,$resid,$url)=&decode_symb($symb);
 7637: 
 7638:     unless ($url eq $thisfn) { return 0; }
 7639: 
 7640:     $symb=&symbclean($symb);
 7641:     $thisurl=&deversion($thisurl);
 7642:     $thisfn=&deversion($thisfn);
 7643: 
 7644:     my %bighash;
 7645:     my $okay=0;
 7646: 
 7647:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7648:                             &GDBM_READER(),0640)) {
 7649:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7650:         unless ($ids) { 
 7651:            $ids=$bighash{'ids_/'.$thisurl};
 7652:         }
 7653:         if ($ids) {
 7654: # ------------------------------------------------------------------- Has ID(s)
 7655: 	    foreach my $id (split(/\,/,$ids)) {
 7656: 	       my ($mapid,$resid)=split(/\./,$id);
 7657:                if (
 7658:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7659:    eq $symb) { 
 7660: 		   if (($env{'request.role.adv'}) ||
 7661: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7662: 		       $okay=1; 
 7663: 		   }
 7664: 	       }
 7665: 	   }
 7666:         }
 7667: 	untie(%bighash);
 7668:     }
 7669:     return $okay;
 7670: }
 7671: 
 7672: # --------------------------------------------------------------- Clean-up symb
 7673: 
 7674: sub symbclean {
 7675:     my $symb=shift;
 7676:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7677: # remove version from map
 7678:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7679: 
 7680: # remove version from URL
 7681:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7682: 
 7683: # remove wrapper
 7684: 
 7685:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7686:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7687:     return $symb;
 7688: }
 7689: 
 7690: # ---------------------------------------------- Split symb to find map and url
 7691: 
 7692: sub encode_symb {
 7693:     my ($map,$resid,$url)=@_;
 7694:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7695: }
 7696: 
 7697: sub decode_symb {
 7698:     my $symb=shift;
 7699:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7700:     my ($map,$resid,$url)=split(/___/,$symb);
 7701:     return (&fixversion($map),$resid,&fixversion($url));
 7702: }
 7703: 
 7704: sub fixversion {
 7705:     my $fn=shift;
 7706:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7707:     my %bighash;
 7708:     my $uri=&clutter($fn);
 7709:     my $key=$env{'request.course.id'}.'_'.$uri;
 7710: # is this cached?
 7711:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7712:     if (defined($cached)) { return $result; }
 7713: # unfortunately not cached, or expired
 7714:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7715: 	    &GDBM_READER(),0640)) {
 7716:  	if ($bighash{'version_'.$uri}) {
 7717:  	    my $version=$bighash{'version_'.$uri};
 7718:  	    unless (($version eq 'mostrecent') || 
 7719: 		    ($version==&getversion($uri))) {
 7720:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7721:  	    }
 7722:  	}
 7723:  	untie %bighash;
 7724:     }
 7725:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7726: }
 7727: 
 7728: sub deversion {
 7729:     my $url=shift;
 7730:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7731:     return $url;
 7732: }
 7733: 
 7734: # ------------------------------------------------------ Return symb list entry
 7735: 
 7736: sub symbread {
 7737:     my ($thisfn,$donotrecurse)=@_;
 7738:     my $cache_str='request.symbread.cached.'.$thisfn;
 7739:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7740: # no filename provided? try from environment
 7741:     unless ($thisfn) {
 7742:         if ($env{'request.symb'}) {
 7743: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7744: 	}
 7745: 	$thisfn=$env{'request.filename'};
 7746:     }
 7747:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7748: # is that filename actually a symb? Verify, clean, and return
 7749:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7750: 	if (&symbverify($thisfn,$1)) {
 7751: 	    return $env{$cache_str}=&symbclean($thisfn);
 7752: 	}
 7753:     }
 7754:     $thisfn=declutter($thisfn);
 7755:     my %hash;
 7756:     my %bighash;
 7757:     my $syval='';
 7758:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7759:         my $targetfn = $thisfn;
 7760:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7761:             $targetfn = 'adm/wrapper/'.$thisfn;
 7762:         }
 7763: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7764: 	    $targetfn=$1;
 7765: 	}
 7766:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7767:                       &GDBM_READER(),0640)) {
 7768: 	    $syval=$hash{$targetfn};
 7769:             untie(%hash);
 7770:         }
 7771: # ---------------------------------------------------------- There was an entry
 7772:         if ($syval) {
 7773: 	    #unless ($syval=~/\_\d+$/) {
 7774: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7775: 		    #&appenv({'request.ambiguous' => $thisfn});
 7776: 		    #return $env{$cache_str}='';
 7777: 		#}    
 7778: 		#$syval.=$1;
 7779: 	    #}
 7780:         } else {
 7781: # ------------------------------------------------------- Was not in symb table
 7782:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7783:                             &GDBM_READER(),0640)) {
 7784: # ---------------------------------------------- Get ID(s) for current resource
 7785:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7786:               unless ($ids) { 
 7787:                  $ids=$bighash{'ids_/'.$thisfn};
 7788:               }
 7789:               unless ($ids) {
 7790: # alias?
 7791: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7792:               }
 7793:               if ($ids) {
 7794: # ------------------------------------------------------------------- Has ID(s)
 7795:                  my @possibilities=split(/\,/,$ids);
 7796:                  if ($#possibilities==0) {
 7797: # ----------------------------------------------- There is only one possibility
 7798: 		     my ($mapid,$resid)=split(/\./,$ids);
 7799: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7800: 						    $resid,$thisfn);
 7801:                  } elsif (!$donotrecurse) {
 7802: # ------------------------------------------ There is more than one possibility
 7803:                      my $realpossible=0;
 7804:                      foreach my $id (@possibilities) {
 7805: 			 my $file=$bighash{'src_'.$id};
 7806:                          if (&allowed('bre',$file)) {
 7807:          		    my ($mapid,$resid)=split(/\./,$id);
 7808:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7809: 				$realpossible++;
 7810:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7811: 						    $resid,$thisfn);
 7812:                             }
 7813: 			 }
 7814:                      }
 7815: 		     if ($realpossible!=1) { $syval=''; }
 7816:                  } else {
 7817:                      $syval='';
 7818:                  }
 7819: 	      }
 7820:               untie(%bighash)
 7821:            }
 7822:         }
 7823:         if ($syval) {
 7824: 	    return $env{$cache_str}=$syval;
 7825:         }
 7826:     }
 7827:     &appenv({'request.ambiguous' => $thisfn});
 7828:     return $env{$cache_str}='';
 7829: }
 7830: 
 7831: # ---------------------------------------------------------- Return random seed
 7832: 
 7833: sub numval {
 7834:     my $txt=shift;
 7835:     $txt=~tr/A-J/0-9/;
 7836:     $txt=~tr/a-j/0-9/;
 7837:     $txt=~tr/K-T/0-9/;
 7838:     $txt=~tr/k-t/0-9/;
 7839:     $txt=~tr/U-Z/0-5/;
 7840:     $txt=~tr/u-z/0-5/;
 7841:     $txt=~s/\D//g;
 7842:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7843:     return int($txt);
 7844: }
 7845: 
 7846: sub numval2 {
 7847:     my $txt=shift;
 7848:     $txt=~tr/A-J/0-9/;
 7849:     $txt=~tr/a-j/0-9/;
 7850:     $txt=~tr/K-T/0-9/;
 7851:     $txt=~tr/k-t/0-9/;
 7852:     $txt=~tr/U-Z/0-5/;
 7853:     $txt=~tr/u-z/0-5/;
 7854:     $txt=~s/\D//g;
 7855:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7856:     my $total;
 7857:     foreach my $val (@txts) { $total+=$val; }
 7858:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7859:     return int($total);
 7860: }
 7861: 
 7862: sub numval3 {
 7863:     use integer;
 7864:     my $txt=shift;
 7865:     $txt=~tr/A-J/0-9/;
 7866:     $txt=~tr/a-j/0-9/;
 7867:     $txt=~tr/K-T/0-9/;
 7868:     $txt=~tr/k-t/0-9/;
 7869:     $txt=~tr/U-Z/0-5/;
 7870:     $txt=~tr/u-z/0-5/;
 7871:     $txt=~s/\D//g;
 7872:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7873:     my $total;
 7874:     foreach my $val (@txts) { $total+=$val; }
 7875:     if ($_64bit) { $total=(($total<<32)>>32); }
 7876:     return $total;
 7877: }
 7878: 
 7879: sub digest {
 7880:     my ($data)=@_;
 7881:     my $digest=&Digest::MD5::md5($data);
 7882:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7883:     my ($e,$f);
 7884:     {
 7885:         use integer;
 7886:         $e=($a+$b);
 7887:         $f=($c+$d);
 7888:         if ($_64bit) {
 7889:             $e=(($e<<32)>>32);
 7890:             $f=(($f<<32)>>32);
 7891:         }
 7892:     }
 7893:     if (wantarray) {
 7894: 	return ($e,$f);
 7895:     } else {
 7896: 	my $g;
 7897: 	{
 7898: 	    use integer;
 7899: 	    $g=($e+$f);
 7900: 	    if ($_64bit) {
 7901: 		$g=(($g<<32)>>32);
 7902: 	    }
 7903: 	}
 7904: 	return $g;
 7905:     }
 7906: }
 7907: 
 7908: sub latest_rnd_algorithm_id {
 7909:     return '64bit5';
 7910: }
 7911: 
 7912: sub get_rand_alg {
 7913:     my ($courseid)=@_;
 7914:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7915:     if ($courseid) {
 7916: 	return $env{"course.$courseid.rndseed"};
 7917:     }
 7918:     return &latest_rnd_algorithm_id();
 7919: }
 7920: 
 7921: sub validCODE {
 7922:     my ($CODE)=@_;
 7923:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7924:     return 0;
 7925: }
 7926: 
 7927: sub getCODE {
 7928:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7929:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7930: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7931: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7932: 	return $Apache::lonhomework::history{'resource.CODE'};
 7933:     }
 7934:     return undef;
 7935: }
 7936: 
 7937: sub rndseed {
 7938:     my ($symb,$courseid,$domain,$username)=@_;
 7939:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7940:     if (!defined($symb)) {
 7941: 	unless ($symb=$wsymb) { return time; }
 7942:     }
 7943:     if (!$courseid) { $courseid=$wcourseid; }
 7944:     if (!$domain) { $domain=$wdomain; }
 7945:     if (!$username) { $username=$wusername }
 7946:     my $which=&get_rand_alg();
 7947: 
 7948:     if (defined(&getCODE())) {
 7949: 	if ($which eq '64bit5') {
 7950: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7951: 	} elsif ($which eq '64bit4') {
 7952: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7953: 	} else {
 7954: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7955: 	}
 7956:     } elsif ($which eq '64bit5') {
 7957: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7958:     } elsif ($which eq '64bit4') {
 7959: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7960:     } elsif ($which eq '64bit3') {
 7961: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7962:     } elsif ($which eq '64bit2') {
 7963: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7964:     } elsif ($which eq '64bit') {
 7965: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7966:     }
 7967:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7968: }
 7969: 
 7970: sub rndseed_32bit {
 7971:     my ($symb,$courseid,$domain,$username)=@_;
 7972:     {
 7973: 	use integer;
 7974: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7975: 	my $symbseed=numval($symb) << 22;
 7976: 	my $namechck=unpack("%32C*",$username) << 17;
 7977: 	my $nameseed=numval($username) << 12;
 7978: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7979: 	my $courseseed=unpack("%32C*",$courseid);
 7980: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7981: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7982: 	#&logthis("rndseed :$num:$symb");
 7983: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7984: 	return $num;
 7985:     }
 7986: }
 7987: 
 7988: sub rndseed_64bit {
 7989:     my ($symb,$courseid,$domain,$username)=@_;
 7990:     {
 7991: 	use integer;
 7992: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7993: 	my $symbseed=numval($symb) << 10;
 7994: 	my $namechck=unpack("%32S*",$username);
 7995: 	
 7996: 	my $nameseed=numval($username) << 21;
 7997: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7998: 	my $courseseed=unpack("%32S*",$courseid);
 7999: 	
 8000: 	my $num1=$symbchck+$symbseed+$namechck;
 8001: 	my $num2=$nameseed+$domainseed+$courseseed;
 8002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8003: 	#&logthis("rndseed :$num:$symb");
 8004: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8005: 	return "$num1,$num2";
 8006:     }
 8007: }
 8008: 
 8009: sub rndseed_64bit2 {
 8010:     my ($symb,$courseid,$domain,$username)=@_;
 8011:     {
 8012: 	use integer;
 8013: 	# strings need to be an even # of cahracters long, it it is odd the
 8014:         # last characters gets thrown away
 8015: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8016: 	my $symbseed=numval($symb) << 10;
 8017: 	my $namechck=unpack("%32S*",$username.' ');
 8018: 	
 8019: 	my $nameseed=numval($username) << 21;
 8020: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8021: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8022: 	
 8023: 	my $num1=$symbchck+$symbseed+$namechck;
 8024: 	my $num2=$nameseed+$domainseed+$courseseed;
 8025: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8026: 	#&logthis("rndseed :$num:$symb");
 8027: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8028: 	return "$num1,$num2";
 8029:     }
 8030: }
 8031: 
 8032: sub rndseed_64bit3 {
 8033:     my ($symb,$courseid,$domain,$username)=@_;
 8034:     {
 8035: 	use integer;
 8036: 	# strings need to be an even # of cahracters long, it it is odd the
 8037:         # last characters gets thrown away
 8038: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8039: 	my $symbseed=numval2($symb) << 10;
 8040: 	my $namechck=unpack("%32S*",$username.' ');
 8041: 	
 8042: 	my $nameseed=numval2($username) << 21;
 8043: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8044: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8045: 	
 8046: 	my $num1=$symbchck+$symbseed+$namechck;
 8047: 	my $num2=$nameseed+$domainseed+$courseseed;
 8048: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8049: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8050: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8051: 	
 8052: 	return "$num1:$num2";
 8053:     }
 8054: }
 8055: 
 8056: sub rndseed_64bit4 {
 8057:     my ($symb,$courseid,$domain,$username)=@_;
 8058:     {
 8059: 	use integer;
 8060: 	# strings need to be an even # of cahracters long, it it is odd the
 8061:         # last characters gets thrown away
 8062: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8063: 	my $symbseed=numval3($symb) << 10;
 8064: 	my $namechck=unpack("%32S*",$username.' ');
 8065: 	
 8066: 	my $nameseed=numval3($username) << 21;
 8067: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8068: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8069: 	
 8070: 	my $num1=$symbchck+$symbseed+$namechck;
 8071: 	my $num2=$nameseed+$domainseed+$courseseed;
 8072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8073: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8074: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8075: 	
 8076: 	return "$num1:$num2";
 8077:     }
 8078: }
 8079: 
 8080: sub rndseed_64bit5 {
 8081:     my ($symb,$courseid,$domain,$username)=@_;
 8082:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8083:     return "$num1:$num2";
 8084: }
 8085: 
 8086: sub rndseed_CODE_64bit {
 8087:     my ($symb,$courseid,$domain,$username)=@_;
 8088:     {
 8089: 	use integer;
 8090: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8091: 	my $symbseed=numval2($symb);
 8092: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8093: 	my $CODEseed=numval(&getCODE());
 8094: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8095: 	my $num1=$symbseed+$CODEchck;
 8096: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8097: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8098: 	#&logthis("rndseed :$num1:$num2:$symb");
 8099: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8100: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8101: 	return "$num1:$num2";
 8102:     }
 8103: }
 8104: 
 8105: sub rndseed_CODE_64bit4 {
 8106:     my ($symb,$courseid,$domain,$username)=@_;
 8107:     {
 8108: 	use integer;
 8109: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8110: 	my $symbseed=numval3($symb);
 8111: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8112: 	my $CODEseed=numval3(&getCODE());
 8113: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8114: 	my $num1=$symbseed+$CODEchck;
 8115: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8116: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8117: 	#&logthis("rndseed :$num1:$num2:$symb");
 8118: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8119: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8120: 	return "$num1:$num2";
 8121:     }
 8122: }
 8123: 
 8124: sub rndseed_CODE_64bit5 {
 8125:     my ($symb,$courseid,$domain,$username)=@_;
 8126:     my $code = &getCODE();
 8127:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8128:     return "$num1:$num2";
 8129: }
 8130: 
 8131: sub setup_random_from_rndseed {
 8132:     my ($rndseed)=@_;
 8133:     if ($rndseed =~/([,:])/) {
 8134: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8135: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8136:     } else {
 8137: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8138:     }
 8139: }
 8140: 
 8141: sub latest_receipt_algorithm_id {
 8142:     return 'receipt3';
 8143: }
 8144: 
 8145: sub recunique {
 8146:     my $fucourseid=shift;
 8147:     my $unique;
 8148:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8149: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8150: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8151:     } else {
 8152: 	$unique=$perlvar{'lonReceipt'};
 8153:     }
 8154:     return unpack("%32C*",$unique);
 8155: }
 8156: 
 8157: sub recprefix {
 8158:     my $fucourseid=shift;
 8159:     my $prefix;
 8160:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8161: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8162: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8163:     } else {
 8164: 	$prefix=$perlvar{'lonHostID'};
 8165:     }
 8166:     return unpack("%32C*",$prefix);
 8167: }
 8168: 
 8169: sub ireceipt {
 8170:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8171: 
 8172:     my $return =&recprefix($fucourseid).'-';
 8173: 
 8174:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8175: 	$env{'request.state'} eq 'construct') {
 8176: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8177: 	return $return;
 8178:     }
 8179: 
 8180:     my $cuname=unpack("%32C*",$funame);
 8181:     my $cudom=unpack("%32C*",$fudom);
 8182:     my $cucourseid=unpack("%32C*",$fucourseid);
 8183:     my $cusymb=unpack("%32C*",$fusymb);
 8184:     my $cunique=&recunique($fucourseid);
 8185:     my $cpart=unpack("%32S*",$part);
 8186:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8187: 
 8188: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8189: 			       
 8190: 	$return.= ($cunique%$cuname+
 8191: 		   $cunique%$cudom+
 8192: 		   $cusymb%$cuname+
 8193: 		   $cusymb%$cudom+
 8194: 		   $cucourseid%$cuname+
 8195: 		   $cucourseid%$cudom+
 8196: 		   $cpart%$cuname+
 8197: 		   $cpart%$cudom);
 8198:     } else {
 8199: 	$return.= ($cunique%$cuname+
 8200: 		   $cunique%$cudom+
 8201: 		   $cusymb%$cuname+
 8202: 		   $cusymb%$cudom+
 8203: 		   $cucourseid%$cuname+
 8204: 		   $cucourseid%$cudom);
 8205:     }
 8206:     return $return;
 8207: }
 8208: 
 8209: sub receipt {
 8210:     my ($part)=@_;
 8211:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8212:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8213: }
 8214: 
 8215: sub whichuser {
 8216:     my ($passedsymb)=@_;
 8217:     my ($symb,$courseid,$domain,$name,$publicuser);
 8218:     if (defined($env{'form.grade_symb'})) {
 8219: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8220: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8221: 	if (!$allowed &&
 8222: 	    exists($env{'request.course.sec'}) &&
 8223: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8224: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8225: 			      '/'.$env{'request.course.sec'});
 8226: 	}
 8227: 	if ($allowed) {
 8228: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8229: 	    $courseid=$tmp_courseid;
 8230: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8231: 	    ($name)=&get_env_multiple('form.grade_username');
 8232: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8233: 	}
 8234:     }
 8235:     if (!$passedsymb) {
 8236: 	$symb=&symbread();
 8237:     } else {
 8238: 	$symb=$passedsymb;
 8239:     }
 8240:     $courseid=$env{'request.course.id'};
 8241:     $domain=$env{'user.domain'};
 8242:     $name=$env{'user.name'};
 8243:     if ($name eq 'public' && $domain eq 'public') {
 8244: 	if (!defined($env{'form.username'})) {
 8245: 	    $env{'form.username'}.=time.rand(10000000);
 8246: 	}
 8247: 	$name.=$env{'form.username'};
 8248:     }
 8249:     return ($symb,$courseid,$domain,$name,$publicuser);
 8250: 
 8251: }
 8252: 
 8253: # ------------------------------------------------------------ Serves up a file
 8254: # returns either the contents of the file or 
 8255: # -1 if the file doesn't exist
 8256: #
 8257: # if the target is a file that was uploaded via DOCS, 
 8258: # a check will be made to see if a current copy exists on the local server,
 8259: # if it does this will be served, otherwise a copy will be retrieved from
 8260: # the home server for the course and stored in /home/httpd/html/userfiles on
 8261: # the local server.   
 8262: 
 8263: sub getfile {
 8264:     my ($file) = @_;
 8265:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8266:     &repcopy($file);
 8267:     return &readfile($file);
 8268: }
 8269: 
 8270: sub repcopy_userfile {
 8271:     my ($file)=@_;
 8272:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8273:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8274:     my ($cdom,$cnum,$filename) = 
 8275: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8276:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8277:     if (-e "$file") {
 8278: # we already have a local copy, check it out
 8279: 	my @fileinfo = stat($file);
 8280: 	my $rtncode;
 8281: 	my $info;
 8282: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8283: 	if ($lwpresp ne 'ok') {
 8284: # there is no such file anymore, even though we had a local copy
 8285: 	    if ($rtncode eq '404') {
 8286: 		unlink($file);
 8287: 	    }
 8288: 	    return -1;
 8289: 	}
 8290: 	if ($info < $fileinfo[9]) {
 8291: # nice, the file we have is up-to-date, just say okay
 8292: 	    return 'ok';
 8293: 	} else {
 8294: # the file is outdated, get rid of it
 8295: 	    unlink($file);
 8296: 	}
 8297:     }
 8298: # one way or the other, at this point, we don't have the file
 8299: # construct the correct path for the file
 8300:     my @parts = ($cdom,$cnum); 
 8301:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8302: 	push @parts, split(/\//,$1);
 8303:     }
 8304:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8305:     foreach my $part (@parts) {
 8306: 	$path .= '/'.$part;
 8307: 	if (!-e $path) {
 8308: 	    mkdir($path,0770);
 8309: 	}
 8310:     }
 8311: # now the path exists for sure
 8312: # get a user agent
 8313:     my $ua=new LWP::UserAgent;
 8314:     my $transferfile=$file.'.in.transfer';
 8315: # FIXME: this should flock
 8316:     if (-e $transferfile) { return 'ok'; }
 8317:     my $request;
 8318:     $uri=~s/^\///;
 8319:     my $homeserver = &homeserver($cnum,$cdom);
 8320:     my $protocol = $protocol{$homeserver};
 8321:     $protocol = 'http' if ($protocol ne 'https');
 8322:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8323:     my $response=$ua->request($request,$transferfile);
 8324: # did it work?
 8325:     if ($response->is_error()) {
 8326: 	unlink($transferfile);
 8327: 	&logthis("Userfile repcopy failed for $uri");
 8328: 	return -1;
 8329:     }
 8330: # worked, rename the transfer file
 8331:     rename($transferfile,$file);
 8332:     return 'ok';
 8333: }
 8334: 
 8335: sub tokenwrapper {
 8336:     my $uri=shift;
 8337:     $uri=~s|^https?\://([^/]+)||;
 8338:     $uri=~s|^/||;
 8339:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8340:     my $token=$1;
 8341:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8342:     if ($udom && $uname && $file) {
 8343: 	$file=~s|(\?\.*)*$||;
 8344:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8345:         my $homeserver = &homeserver($uname,$udom);
 8346:         my $protocol = $protocol{$homeserver};
 8347:         $protocol = 'http' if ($protocol ne 'https');
 8348:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8349:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8350:                                '&tokenissued='.$perlvar{'lonHostID'};
 8351:     } else {
 8352:         return '/adm/notfound.html';
 8353:     }
 8354: }
 8355: 
 8356: # call with reqtype HEAD: get last modification time
 8357: # call with reqtype GET: get the file contents
 8358: # Do not call this with reqtype GET for large files! It loads everything into memory
 8359: #
 8360: sub getuploaded {
 8361:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8362:     $uri=~s/^\///;
 8363:     my $homeserver = &homeserver($cnum,$cdom);
 8364:     my $protocol = $protocol{$homeserver};
 8365:     $protocol = 'http' if ($protocol ne 'https');
 8366:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8367:     my $ua=new LWP::UserAgent;
 8368:     my $request=new HTTP::Request($reqtype,$uri);
 8369:     my $response=$ua->request($request);
 8370:     $$rtncode = $response->code;
 8371:     if (! $response->is_success()) {
 8372: 	return 'failed';
 8373:     }      
 8374:     if ($reqtype eq 'HEAD') {
 8375: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8376:     } elsif ($reqtype eq 'GET') {
 8377: 	$$info = $response->content;
 8378:     }
 8379:     return 'ok';
 8380: }
 8381: 
 8382: sub readfile {
 8383:     my $file = shift;
 8384:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8385:     my $fh;
 8386:     open($fh,"<$file");
 8387:     my $a='';
 8388:     while (my $line = <$fh>) { $a .= $line; }
 8389:     return $a;
 8390: }
 8391: 
 8392: sub filelocation {
 8393:     my ($dir,$file) = @_;
 8394:     my $location;
 8395:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8396: 
 8397:     if ($file =~ m-^/adm/-) {
 8398: 	$file=~s-^/adm/wrapper/-/-;
 8399: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8400:     }
 8401: 
 8402:     if ($file=~m:^/~:) { # is a contruction space reference
 8403:         $location = $file;
 8404:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8405:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8406: 	# is a correct contruction space reference
 8407:         $location = $file;
 8408:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8409:         $location = $file;
 8410:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8411:         my ($udom,$uname,$filename)=
 8412:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8413:         my $home=&homeserver($uname,$udom);
 8414:         my $is_me=0;
 8415:         my @ids=&current_machine_ids();
 8416:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8417:         if ($is_me) {
 8418:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8419:         } else {
 8420:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8421:   	      $udom.'/'.$uname.'/'.$filename;
 8422:         }
 8423:     } elsif ($file =~ m-^/adm/-) {
 8424: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8425:     } else {
 8426:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8427:         $file=~s:^/res/:/:;
 8428:         if ( !( $file =~ m:^/:) ) {
 8429:             $location = $dir. '/'.$file;
 8430:         } else {
 8431:             $location = '/home/httpd/html/res'.$file;
 8432:         }
 8433:     }
 8434:     $location=~s://+:/:g; # remove duplicate /
 8435:     while ($location=~m{/\.\./}) {
 8436: 	if ($location =~ m{/[^/]+/\.\./}) {
 8437: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8438: 	} else {
 8439: 	    $location=~ s{/\.\./}{/}g;
 8440: 	}
 8441:     } #remove dir/..
 8442:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8443:     return $location;
 8444: }
 8445: 
 8446: sub hreflocation {
 8447:     my ($dir,$file)=@_;
 8448:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8449: 	$file=filelocation($dir,$file);
 8450:     } elsif ($file=~m-^/adm/-) {
 8451: 	$file=~s-^/adm/wrapper/-/-;
 8452: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8453:     }
 8454:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8455: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8456:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8457: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8458:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8459: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8460: 	    -/uploaded/$1/$2/-x;
 8461:     }
 8462:     if ($file=~ m{^/userfiles/}) {
 8463: 	$file =~ s{^/userfiles/}{/uploaded/};
 8464:     }
 8465:     return $file;
 8466: }
 8467: 
 8468: sub current_machine_domains {
 8469:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8470: }
 8471: 
 8472: sub machine_domains {
 8473:     my ($hostname) = @_;
 8474:     my @domains;
 8475:     my %hostname = &all_hostnames();
 8476:     while( my($id, $name) = each(%hostname)) {
 8477: #	&logthis("-$id-$name-$hostname-");
 8478: 	if ($hostname eq $name) {
 8479: 	    push(@domains,&host_domain($id));
 8480: 	}
 8481:     }
 8482:     return @domains;
 8483: }
 8484: 
 8485: sub current_machine_ids {
 8486:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8487: }
 8488: 
 8489: sub machine_ids {
 8490:     my ($hostname) = @_;
 8491:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8492:     my @ids;
 8493:     my %name_to_host = &all_names();
 8494:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8495: 	return @{ $name_to_host{$hostname} };
 8496:     }
 8497:     return;
 8498: }
 8499: 
 8500: sub additional_machine_domains {
 8501:     my @domains;
 8502:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8503:     while( my $line = <$fh>) {
 8504:         $line =~ s/\s//g;
 8505:         push(@domains,$line);
 8506:     }
 8507:     return @domains;
 8508: }
 8509: 
 8510: sub default_login_domain {
 8511:     my $domain = $perlvar{'lonDefDomain'};
 8512:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8513:     foreach my $posdom (&current_machine_domains(),
 8514:                         &additional_machine_domains()) {
 8515:         if (lc($posdom) eq lc($testdomain)) {
 8516:             $domain=$posdom;
 8517:             last;
 8518:         }
 8519:     }
 8520:     return $domain;
 8521: }
 8522: 
 8523: # ------------------------------------------------------------- Declutters URLs
 8524: 
 8525: sub declutter {
 8526:     my $thisfn=shift;
 8527:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8528:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8529:     $thisfn=~s/^\///;
 8530:     $thisfn=~s|^adm/wrapper/||;
 8531:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8532:     $thisfn=~s/^res\///;
 8533:     $thisfn=~s/\?.+$//;
 8534:     return $thisfn;
 8535: }
 8536: 
 8537: # ------------------------------------------------------------- Clutter up URLs
 8538: 
 8539: sub clutter {
 8540:     my $thisfn='/'.&declutter(shift);
 8541:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8542: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8543:        $thisfn='/res'.$thisfn; 
 8544:     }
 8545:     if ($thisfn !~m|/adm|) {
 8546: 	if ($thisfn =~ m|/ext/|) {
 8547: 	    $thisfn='/adm/wrapper'.$thisfn;
 8548: 	} else {
 8549: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8550: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8551: 	    if ($embstyle eq 'ssi'
 8552: 		|| ($embstyle eq 'hdn')
 8553: 		|| ($embstyle eq 'rat')
 8554: 		|| ($embstyle eq 'prv')
 8555: 		|| ($embstyle eq 'ign')) {
 8556: 		#do nothing with these
 8557: 	    } elsif (($embstyle eq 'img') 
 8558: 		|| ($embstyle eq 'emb')
 8559: 		|| ($embstyle eq 'wrp')) {
 8560: 		$thisfn='/adm/wrapper'.$thisfn;
 8561: 	    } elsif ($embstyle eq 'unk'
 8562: 		     && $thisfn!~/\.(sequence|page)$/) {
 8563: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8564: 	    } else {
 8565: #		&logthis("Got a blank emb style");
 8566: 	    }
 8567: 	}
 8568:     }
 8569:     return $thisfn;
 8570: }
 8571: 
 8572: sub clutter_with_no_wrapper {
 8573:     my $uri = &clutter(shift);
 8574:     if ($uri =~ m-^/adm/-) {
 8575: 	$uri =~ s-^/adm/wrapper/-/-;
 8576: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8577:     }
 8578:     return $uri;
 8579: }
 8580: 
 8581: sub freeze_escape {
 8582:     my ($value)=@_;
 8583:     if (ref($value)) {
 8584: 	$value=&nfreeze($value);
 8585: 	return '__FROZEN__'.&escape($value);
 8586:     }
 8587:     return &escape($value);
 8588: }
 8589: 
 8590: 
 8591: sub thaw_unescape {
 8592:     my ($value)=@_;
 8593:     if ($value =~ /^__FROZEN__/) {
 8594: 	substr($value,0,10,undef);
 8595: 	$value=&unescape($value);
 8596: 	return &thaw($value);
 8597:     }
 8598:     return &unescape($value);
 8599: }
 8600: 
 8601: sub correct_line_ends {
 8602:     my ($result)=@_;
 8603:     $$result =~s/\r\n/\n/mg;
 8604:     $$result =~s/\r/\n/mg;
 8605: }
 8606: # ================================================================ Main Program
 8607: 
 8608: sub goodbye {
 8609:    &logthis("Starting Shut down");
 8610: #not converted to using infrastruture and probably shouldn't be
 8611:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8612: #converted
 8613: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8614:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8615: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8616: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8617: #1.1 only
 8618: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8619: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8620: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8621: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8622:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8623:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8624:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8625:    &flushcourselogs();
 8626:    &logthis("Shutting down");
 8627: }
 8628: 
 8629: sub get_dns {
 8630:     my ($url,$func,$ignore_cache) = @_;
 8631:     if (!$ignore_cache) {
 8632: 	my ($content,$cached)=
 8633: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8634: 	if ($cached) {
 8635: 	    &$func($content);
 8636: 	    return;
 8637: 	}
 8638:     }
 8639: 
 8640:     my %alldns;
 8641:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8642:     foreach my $dns (<$config>) {
 8643: 	next if ($dns !~ /^\^(\S*)/x);
 8644:         my $line = $1;
 8645:         my ($host,$protocol) = split(/:/,$line);
 8646:         if ($protocol ne 'https') {
 8647:             $protocol = 'http';
 8648:         }
 8649: 	$alldns{$host} = $protocol;
 8650:     }
 8651:     while (%alldns) {
 8652: 	my ($dns) = keys(%alldns);
 8653: 	my $ua=new LWP::UserAgent;
 8654: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8655: 	my $response=$ua->request($request);
 8656:         delete($alldns{$dns});
 8657: 	next if ($response->is_error());
 8658: 	my @content = split("\n",$response->content);
 8659: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8660: 	&$func(\@content);
 8661: 	return;
 8662:     }
 8663:     close($config);
 8664:     my $which = (split('/',$url))[3];
 8665:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8666:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8667:     my @content = <$config>;
 8668:     &$func(\@content);
 8669:     return;
 8670: }
 8671: # ------------------------------------------------------------ Read domain file
 8672: {
 8673:     my $loaded;
 8674:     my %domain;
 8675: 
 8676:     sub parse_domain_tab {
 8677: 	my ($lines) = @_;
 8678: 	foreach my $line (@$lines) {
 8679: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8680: 
 8681: 	    chomp($line);
 8682: 	    my ($name,@elements) = split(/:/,$line,9);
 8683: 	    my %this_domain;
 8684: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8685: 			       'lang_def', 'city', 'longi', 'lati',
 8686: 			       'primary') {
 8687: 		$this_domain{$field} = shift(@elements);
 8688: 	    }
 8689: 	    $domain{$name} = \%this_domain;
 8690: 	}
 8691:     }
 8692: 
 8693:     sub reset_domain_info {
 8694: 	undef($loaded);
 8695: 	undef(%domain);
 8696:     }
 8697: 
 8698:     sub load_domain_tab {
 8699: 	my ($ignore_cache) = @_;
 8700: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8701: 	my $fh;
 8702: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8703: 	    my @lines = <$fh>;
 8704: 	    &parse_domain_tab(\@lines);
 8705: 	}
 8706: 	close($fh);
 8707: 	$loaded = 1;
 8708:     }
 8709: 
 8710:     sub domain {
 8711: 	&load_domain_tab() if (!$loaded);
 8712: 
 8713: 	my ($name,$what) = @_;
 8714: 	return if ( !exists($domain{$name}) );
 8715: 
 8716: 	if (!$what) {
 8717: 	    return $domain{$name}{'description'};
 8718: 	}
 8719: 	return $domain{$name}{$what};
 8720:     }
 8721: 
 8722:     sub domain_info {
 8723:         &load_domain_tab() if (!$loaded);
 8724:         return %domain;
 8725:     }
 8726: 
 8727: }
 8728: 
 8729: 
 8730: # ------------------------------------------------------------- Read hosts file
 8731: {
 8732:     my %hostname;
 8733:     my %hostdom;
 8734:     my %libserv;
 8735:     my $loaded;
 8736:     my %name_to_host;
 8737: 
 8738:     sub parse_hosts_tab {
 8739: 	my ($file) = @_;
 8740: 	foreach my $configline (@$file) {
 8741: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8742: 	    next if ($configline =~ /^\^/);
 8743: 	    chomp($configline);
 8744: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8745: 	    $name=~s/\s//g;
 8746: 	    if ($id && $domain && $role && $name) {
 8747: 		$hostname{$id}=$name;
 8748: 		push(@{$name_to_host{$name}}, $id);
 8749: 		$hostdom{$id}=$domain;
 8750: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8751:                 if (defined($protocol)) {
 8752:                     if ($protocol eq 'https') {
 8753:                         $protocol{$id} = $protocol;
 8754:                     } else {
 8755:                         $protocol{$id} = 'http'; 
 8756:                     }
 8757:                 } else {
 8758:                     $protocol{$id} = 'http';
 8759:                 }
 8760: 	    }
 8761: 	}
 8762:     }
 8763:     
 8764:     sub reset_hosts_info {
 8765: 	&purge_remembered();
 8766: 	&reset_domain_info();
 8767: 	&reset_hosts_ip_info();
 8768: 	undef(%name_to_host);
 8769: 	undef(%hostname);
 8770: 	undef(%hostdom);
 8771: 	undef(%libserv);
 8772: 	undef($loaded);
 8773:     }
 8774: 
 8775:     sub load_hosts_tab {
 8776: 	my ($ignore_cache) = @_;
 8777: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8778: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8779: 	my @config = <$config>;
 8780: 	&parse_hosts_tab(\@config);
 8781: 	close($config);
 8782: 	$loaded=1;
 8783:     }
 8784: 
 8785:     sub hostname {
 8786: 	&load_hosts_tab() if (!$loaded);
 8787: 
 8788: 	my ($lonid) = @_;
 8789: 	return $hostname{$lonid};
 8790:     }
 8791: 
 8792:     sub all_hostnames {
 8793: 	&load_hosts_tab() if (!$loaded);
 8794: 
 8795: 	return %hostname;
 8796:     }
 8797: 
 8798:     sub all_names {
 8799: 	&load_hosts_tab() if (!$loaded);
 8800: 
 8801: 	return %name_to_host;
 8802:     }
 8803: 
 8804:     sub all_host_domain {
 8805:         &load_hosts_tab() if (!$loaded);
 8806:         return %hostdom;
 8807:     }
 8808: 
 8809:     sub is_library {
 8810: 	&load_hosts_tab() if (!$loaded);
 8811: 
 8812: 	return exists($libserv{$_[0]});
 8813:     }
 8814: 
 8815:     sub all_library {
 8816: 	&load_hosts_tab() if (!$loaded);
 8817: 
 8818: 	return %libserv;
 8819:     }
 8820: 
 8821:     sub get_servers {
 8822: 	&load_hosts_tab() if (!$loaded);
 8823: 
 8824: 	my ($domain,$type) = @_;
 8825: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8826: 	                                          : %hostname;
 8827: 	my %result;
 8828: 	if (ref($domain) eq 'ARRAY') {
 8829: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8830: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8831: 		    $result{$host} = $hostname;
 8832: 		}
 8833: 	    }
 8834: 	} else {
 8835: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8836: 		if ($hostdom{$host} eq $domain) {
 8837: 		    $result{$host} = $hostname;
 8838: 		}
 8839: 	    }
 8840: 	}
 8841: 	return %result;
 8842:     }
 8843: 
 8844:     sub host_domain {
 8845: 	&load_hosts_tab() if (!$loaded);
 8846: 
 8847: 	my ($lonid) = @_;
 8848: 	return $hostdom{$lonid};
 8849:     }
 8850: 
 8851:     sub all_domains {
 8852: 	&load_hosts_tab() if (!$loaded);
 8853: 
 8854: 	my %seen;
 8855: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8856: 	return @uniq;
 8857:     }
 8858: }
 8859: 
 8860: { 
 8861:     my %iphost;
 8862:     my %name_to_ip;
 8863:     my %lonid_to_ip;
 8864: 
 8865:     sub get_hosts_from_ip {
 8866: 	my ($ip) = @_;
 8867: 	my %iphosts = &get_iphost();
 8868: 	if (ref($iphosts{$ip})) {
 8869: 	    return @{$iphosts{$ip}};
 8870: 	}
 8871: 	return;
 8872:     }
 8873:     
 8874:     sub reset_hosts_ip_info {
 8875: 	undef(%iphost);
 8876: 	undef(%name_to_ip);
 8877: 	undef(%lonid_to_ip);
 8878:     }
 8879: 
 8880:     sub get_host_ip {
 8881: 	my ($lonid) = @_;
 8882: 	if (exists($lonid_to_ip{$lonid})) {
 8883: 	    return $lonid_to_ip{$lonid};
 8884: 	}
 8885: 	my $name=&hostname($lonid);
 8886:    	my $ip = gethostbyname($name);
 8887: 	return if (!$ip || length($ip) ne 4);
 8888: 	$ip=inet_ntoa($ip);
 8889: 	$name_to_ip{$name}   = $ip;
 8890: 	$lonid_to_ip{$lonid} = $ip;
 8891: 	return $ip;
 8892:     }
 8893:     
 8894:     sub get_iphost {
 8895: 	my ($ignore_cache) = @_;
 8896: 
 8897: 	if (!$ignore_cache) {
 8898: 	    if (%iphost) {
 8899: 		return %iphost;
 8900: 	    }
 8901: 	    my ($ip_info,$cached)=
 8902: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8903: 	    if ($cached) {
 8904: 		%iphost      = %{$ip_info->[0]};
 8905: 		%name_to_ip  = %{$ip_info->[1]};
 8906: 		%lonid_to_ip = %{$ip_info->[2]};
 8907: 		return %iphost;
 8908: 	    }
 8909: 	}
 8910: 
 8911: 	# get yesterday's info for fallback
 8912: 	my %old_name_to_ip;
 8913: 	my ($ip_info,$cached)=
 8914: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8915: 	if ($cached) {
 8916: 	    %old_name_to_ip = %{$ip_info->[1]};
 8917: 	}
 8918: 
 8919: 	my %name_to_host = &all_names();
 8920: 	foreach my $name (keys(%name_to_host)) {
 8921: 	    my $ip;
 8922: 	    if (!exists($name_to_ip{$name})) {
 8923: 		$ip = gethostbyname($name);
 8924: 		if (!$ip || length($ip) ne 4) {
 8925: 		    if (defined($old_name_to_ip{$name})) {
 8926: 			$ip = $old_name_to_ip{$name};
 8927: 			&logthis("Can't find $name defaulting to old $ip");
 8928: 		    } else {
 8929: 			&logthis("Name $name no IP found");
 8930: 			next;
 8931: 		    }
 8932: 		} else {
 8933: 		    $ip=inet_ntoa($ip);
 8934: 		}
 8935: 		$name_to_ip{$name} = $ip;
 8936: 	    } else {
 8937: 		$ip = $name_to_ip{$name};
 8938: 	    }
 8939: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8940: 		$lonid_to_ip{$id} = $ip;
 8941: 	    }
 8942: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8943: 	}
 8944: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8945: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8946: 				      48*60*60);
 8947: 
 8948: 	return %iphost;
 8949:     }
 8950: }
 8951: 
 8952: BEGIN {
 8953: 
 8954: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8955:     unless ($readit) {
 8956: {
 8957:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8958:     %perlvar = (%perlvar,%{$configvars});
 8959: }
 8960: 
 8961: 
 8962: # ------------------------------------------------------ Read spare server file
 8963: {
 8964:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8965: 
 8966:     while (my $configline=<$config>) {
 8967:        chomp($configline);
 8968:        if ($configline) {
 8969: 	   my ($host,$type) = split(':',$configline,2);
 8970: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8971: 	   push(@{ $spareid{$type} }, $host);
 8972:        }
 8973:     }
 8974:     close($config);
 8975: }
 8976: # ------------------------------------------------------------ Read permissions
 8977: {
 8978:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8979: 
 8980:     while (my $configline=<$config>) {
 8981: 	chomp($configline);
 8982: 	if ($configline) {
 8983: 	    my ($role,$perm)=split(/ /,$configline);
 8984: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8985: 	}
 8986:     }
 8987:     close($config);
 8988: }
 8989: 
 8990: # -------------------------------------------- Read plain texts for permissions
 8991: {
 8992:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8993: 
 8994:     while (my $configline=<$config>) {
 8995: 	chomp($configline);
 8996: 	if ($configline) {
 8997: 	    my ($short,@plain)=split(/:/,$configline);
 8998:             %{$prp{$short}} = ();
 8999: 	    if (@plain > 0) {
 9000:                 $prp{$short}{'std'} = $plain[0];
 9001:                 for (my $i=1; $i<@plain; $i++) {
 9002:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9003:                 }
 9004:             }
 9005: 	}
 9006:     }
 9007:     close($config);
 9008: }
 9009: 
 9010: # ---------------------------------------------------------- Read package table
 9011: {
 9012:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9013: 
 9014:     while (my $configline=<$config>) {
 9015: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9016: 	chomp($configline);
 9017: 	my ($short,$plain)=split(/:/,$configline);
 9018: 	my ($pack,$name)=split(/\&/,$short);
 9019: 	if ($plain ne '') {
 9020: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9021: 	    $packagetab{$short}=$plain; 
 9022: 	}
 9023:     }
 9024:     close($config);
 9025: }
 9026: 
 9027: # ------------- set up temporary directory
 9028: {
 9029:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9030: 
 9031: }
 9032: 
 9033: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9034: 				'compress_threshold'=> 20_000,
 9035:  			        });
 9036: 
 9037: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9038: $dumpcount=0;
 9039: $locknum=0;
 9040: 
 9041: &logtouch();
 9042: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9043: $readit=1;
 9044:     {
 9045: 	use integer;
 9046: 	my $test=(2**32)+1;
 9047: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9048: 	&logthis(" Detected 64bit platform ($_64bit)");
 9049:     }
 9050: }
 9051: }
 9052: 
 9053: 1;
 9054: __END__
 9055: 
 9056: =pod
 9057: 
 9058: =head1 NAME
 9059: 
 9060: Apache::lonnet - Subroutines to ask questions about things in the network.
 9061: 
 9062: =head1 SYNOPSIS
 9063: 
 9064: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9065: 
 9066:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9067: 
 9068: Common parameters:
 9069: 
 9070: =over 4
 9071: 
 9072: =item *
 9073: 
 9074: $uname : an internal username (if $cname expecting a course Id specifically)
 9075: 
 9076: =item *
 9077: 
 9078: $udom : a domain (if $cdom expecting a course's domain specifically)
 9079: 
 9080: =item *
 9081: 
 9082: $symb : a resource instance identifier
 9083: 
 9084: =item *
 9085: 
 9086: $namespace : the name of a .db file that contains the data needed or
 9087: being set.
 9088: 
 9089: =back
 9090: 
 9091: =head1 OVERVIEW
 9092: 
 9093: lonnet provides subroutines which interact with the
 9094: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9095: about classes, users, and resources.
 9096: 
 9097: For many of these objects you can also use this to store data about
 9098: them or modify them in various ways.
 9099: 
 9100: =head2 Symbs
 9101: 
 9102: To identify a specific instance of a resource, LON-CAPA uses symbols
 9103: or "symbs"X<symb>. These identifiers are built from the URL of the
 9104: map, the resource number of the resource in the map, and the URL of
 9105: the resource itself. The latter is somewhat redundant, but might help
 9106: if maps change.
 9107: 
 9108: An example is
 9109: 
 9110:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9111: 
 9112: The respective map entry is
 9113: 
 9114:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9115:   title="Problem 2">
 9116:  </resource>
 9117: 
 9118: Symbs are used by the random number generator, as well as to store and
 9119: restore data specific to a certain instance of for example a problem.
 9120: 
 9121: =head2 Storing And Retrieving Data
 9122: 
 9123: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9124: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9125: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9126: is is the non-critical message twin of cstore. These functions are for
 9127: handlers to store a perl hash to a user's permanent data space in an
 9128: easy manner, and to retrieve it again on another call. It is expected
 9129: that a handler would use this once at the beginning to retrieve data,
 9130: and then again once at the end to send only the new data back.
 9131: 
 9132: The data is stored in the user's data directory on the user's
 9133: homeserver under the ID of the course.
 9134: 
 9135: The hash that is returned by restore will have all of the previous
 9136: value for all of the elements of the hash.
 9137: 
 9138: Example:
 9139: 
 9140:  #creating a hash
 9141:  my %hash;
 9142:  $hash{'foo'}='bar';
 9143: 
 9144:  #storing it
 9145:  &Apache::lonnet::cstore(\%hash);
 9146: 
 9147:  #changing a value
 9148:  $hash{'foo'}='notbar';
 9149: 
 9150:  #adding a new value
 9151:  $hash{'bar'}='foo';
 9152:  &Apache::lonnet::cstore(\%hash);
 9153: 
 9154:  #retrieving the hash
 9155:  my %history=&Apache::lonnet::restore();
 9156: 
 9157:  #print the hash
 9158:  foreach my $key (sort(keys(%history))) {
 9159:    print("\%history{$key} = $history{$key}");
 9160:  }
 9161: 
 9162: Will print out:
 9163: 
 9164:  %history{1:foo} = bar
 9165:  %history{1:keys} = foo:timestamp
 9166:  %history{1:timestamp} = 990455579
 9167:  %history{2:bar} = foo
 9168:  %history{2:foo} = notbar
 9169:  %history{2:keys} = foo:bar:timestamp
 9170:  %history{2:timestamp} = 990455580
 9171:  %history{bar} = foo
 9172:  %history{foo} = notbar
 9173:  %history{timestamp} = 990455580
 9174:  %history{version} = 2
 9175: 
 9176: Note that the special hash entries C<keys>, C<version> and
 9177: C<timestamp> were added to the hash. C<version> will be equal to the
 9178: total number of versions of the data that have been stored. The
 9179: C<timestamp> attribute will be the UNIX time the hash was
 9180: stored. C<keys> is available in every historical section to list which
 9181: keys were added or changed at a specific historical revision of a
 9182: hash.
 9183: 
 9184: B<Warning>: do not store the hash that restore returns directly. This
 9185: will cause a mess since it will restore the historical keys as if the
 9186: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9187: 
 9188: Calling convention:
 9189: 
 9190:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9191:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9192: 
 9193: For more detailed information, see lonnet specific documentation.
 9194: 
 9195: =head1 RETURN MESSAGES
 9196: 
 9197: =over 4
 9198: 
 9199: =item * B<con_lost>: unable to contact remote host
 9200: 
 9201: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9202: when the connection is brought back up
 9203: 
 9204: =item * B<con_failed>: unable to contact remote host and unable to save message
 9205: for later delivery
 9206: 
 9207: =item * B<error:>: an error a occurred, a description of the error follows the :
 9208: 
 9209: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9210: that was requested
 9211: 
 9212: =back
 9213: 
 9214: =head1 PUBLIC SUBROUTINES
 9215: 
 9216: =head2 Session Environment Functions
 9217: 
 9218: =over 4
 9219: 
 9220: =item * 
 9221: X<appenv()>
 9222: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9223: the user envirnoment file, and will be restored for each access this
 9224: user makes during this session, also modifies the %env for the current
 9225: process. Optional rolesarrayref - if defined contains a reference to an array
 9226: of roles which are exempt from the restriction on modifying user.role entries 
 9227: in the user's environment.db and in %env.    
 9228: 
 9229: =item *
 9230: X<delenv()>
 9231: B<delenv($regexp)>: removes all items from the session
 9232: environment file that matches the regular expression in $regexp. The
 9233: values are also delted from the current processes %env.
 9234: 
 9235: =item * get_env_multiple($name) 
 9236: 
 9237: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9238: values may be defined and end up as an array ref.
 9239: 
 9240: returns an array of values
 9241: 
 9242: =back
 9243: 
 9244: =head2 User Information
 9245: 
 9246: =over 4
 9247: 
 9248: =item *
 9249: X<queryauthenticate()>
 9250: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9251: authentication scheme
 9252: 
 9253: =item *
 9254: X<authenticate()>
 9255: B<authenticate($uname,$upass,$udom)>: try to
 9256: authenticate user from domain's lib servers (first use the current
 9257: one). C<$upass> should be the users password.
 9258: 
 9259: =item *
 9260: X<homeserver()>
 9261: B<homeserver($uname,$udom)>: find the server which has
 9262: the user's directory and files (there must be only one), this caches
 9263: the answer, and also caches if there is a borken connection.
 9264: 
 9265: =item *
 9266: X<idget()>
 9267: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9268: (IDs are a unique resource in a domain, there must be only 1 ID per
 9269: username, and only 1 username per ID in a specific domain) (returns
 9270: hash: id=>name,id=>name)
 9271: 
 9272: =item *
 9273: X<idrget()>
 9274: B<idrget($udom,@unames)>: find the IDs behind a list of
 9275: usernames (returns hash: name=>id,name=>id)
 9276: 
 9277: =item *
 9278: X<idput()>
 9279: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9280: 
 9281: =item *
 9282: X<rolesinit()>
 9283: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9284: 
 9285: =item *
 9286: X<getsection()>
 9287: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9288: course $cname, return section name/number or '' for "not in course"
 9289: and '-1' for "no section"
 9290: 
 9291: =item *
 9292: X<userenvironment()>
 9293: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9294: passed in @what from the requested user's environment, returns a hash
 9295: 
 9296: =item * 
 9297: X<userlog_query()>
 9298: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9299: activity.log file. %filters defines filters applied when parsing the
 9300: log file. These can be start or end timestamps, or the type of action
 9301: - log to look for Login or Logout events, check for Checkin or
 9302: Checkout, role for role selection. The response is in the form
 9303: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9304: escaped strings of the action recorded in the activity.log file.
 9305: 
 9306: =back
 9307: 
 9308: =head2 User Roles
 9309: 
 9310: =over 4
 9311: 
 9312: =item *
 9313: 
 9314: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9315:  F: full access
 9316:  U,I,K: authentication modes (cxx only)
 9317:  '': forbidden
 9318:  1: user needs to choose course
 9319:  2: browse allowed
 9320:  A: passphrase authentication needed
 9321: 
 9322: =item *
 9323: 
 9324: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9325: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9326: and course level
 9327: 
 9328: =item *
 9329: 
 9330: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9331: explanation of a user role term
 9332: 
 9333: =item *
 9334: 
 9335: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9336: All arguments are optional. Returns a hash of a roles, either for
 9337: co-author/assistant author roles for a user's Construction Space
 9338: (default), or if $context is 'userroles', roles for the user himself,
 9339: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9340: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9341: For each key, value is set to colon-separated start and end times for
 9342: the role.  If no username and domain are specified, will default to
 9343: current user/domain. Types, roles, and roledoms are references to arrays
 9344: of role statuses (active, future or previous), roles 
 9345: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9346: to restrict the list of roles reported. If no array ref is 
 9347: provided for types, will default to return only active roles.
 9348: 
 9349: =back
 9350: 
 9351: =head2 User Modification
 9352: 
 9353: =over 4
 9354: 
 9355: =item *
 9356: 
 9357: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9358: user for the level given by URL.  Optional start and end dates (leave empty
 9359: string or zero for "no date")
 9360: 
 9361: =item *
 9362: 
 9363: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9364: change a users, password, possible return values are: ok,
 9365: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9366: refused
 9367: 
 9368: =item *
 9369: 
 9370: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9371: 
 9372: =item *
 9373: 
 9374: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9375:            $forceid,$desiredhome,$email,$inststatus) : 
 9376: modify user
 9377: 
 9378: =item *
 9379: 
 9380: modifystudent
 9381: 
 9382: modify a student's enrollment and identification information.
 9383: The course id is resolved based on the current users environment.  
 9384: This means the envoking user must be a course coordinator or otherwise
 9385: associated with a course.
 9386: 
 9387: This call is essentially a wrapper for lonnet::modifyuser and
 9388: lonnet::modify_student_enrollment
 9389: 
 9390: Inputs: 
 9391: 
 9392: =over 4
 9393: 
 9394: =item B<$udom> Student's loncapa domain
 9395: 
 9396: =item B<$uname> Student's loncapa login name
 9397: 
 9398: =item B<$uid> Student/Employee ID
 9399: 
 9400: =item B<$umode> Student's authentication mode
 9401: 
 9402: =item B<$upass> Student's password
 9403: 
 9404: =item B<$first> Student's first name
 9405: 
 9406: =item B<$middle> Student's middle name
 9407: 
 9408: =item B<$last> Student's last name
 9409: 
 9410: =item B<$gene> Student's generation
 9411: 
 9412: =item B<$usec> Student's section in course
 9413: 
 9414: =item B<$end> Unix time of the roles expiration
 9415: 
 9416: =item B<$start> Unix time of the roles start date
 9417: 
 9418: =item B<$forceid> If defined, allow $uid to be changed
 9419: 
 9420: =item B<$desiredhome> server to use as home server for student
 9421: 
 9422: =item B<$email> Student's permanent e-mail address
 9423: 
 9424: =item B<$type> Type of enrollment (auto or manual)
 9425: 
 9426: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9427: 
 9428: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9429: 
 9430: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9431: 
 9432: =item B<$context> role change context (shown in User Management Logs display in a course)
 9433: 
 9434: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9435: 
 9436: =back
 9437: 
 9438: =item *
 9439: 
 9440: modify_student_enrollment
 9441: 
 9442: Change a students enrollment status in a class.  The environment variable
 9443: 'role.request.course' must be defined for this function to proceed.
 9444: 
 9445: Inputs:
 9446: 
 9447: =over 4
 9448: 
 9449: =item $udom, students domain
 9450: 
 9451: =item $uname, students name
 9452: 
 9453: =item $uid, students user id
 9454: 
 9455: =item $first, students first name
 9456: 
 9457: =item $middle
 9458: 
 9459: =item $last
 9460: 
 9461: =item $gene
 9462: 
 9463: =item $usec
 9464: 
 9465: =item $end
 9466: 
 9467: =item $start
 9468: 
 9469: =item $type
 9470: 
 9471: =item $locktype
 9472: 
 9473: =item $cid
 9474: 
 9475: =item $selfenroll
 9476: 
 9477: =item $context
 9478: 
 9479: =back
 9480: 
 9481: 
 9482: =item *
 9483: 
 9484: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9485: custom role; give a custom role to a user for the level given by URL.  Specify
 9486: name and domain of role author, and role name
 9487: 
 9488: =item *
 9489: 
 9490: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9491: 
 9492: =item *
 9493: 
 9494: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9495: 
 9496: =back
 9497: 
 9498: =head2 Course Infomation
 9499: 
 9500: =over 4
 9501: 
 9502: =item *
 9503: 
 9504: coursedescription($courseid) : returns a hash of information about the
 9505: specified course id, including all environment settings for the
 9506: course, the description of the course will be in the hash under the
 9507: key 'description'
 9508: 
 9509: =item *
 9510: 
 9511: resdata($name,$domain,$type,@which) : request for current parameter
 9512: setting for a specific $type, where $type is either 'course' or 'user',
 9513: @what should be a list of parameters to ask about. This routine caches
 9514: answers for 5 minutes.
 9515: 
 9516: =item *
 9517: 
 9518: get_courseresdata($courseid, $domain) : dump the entire course resource
 9519: data base, returning a hash that is keyed by the resource name and has
 9520: values that are the resource value.  I believe that the timestamps and
 9521: versions are also returned.
 9522: 
 9523: 
 9524: =back
 9525: 
 9526: =head2 Course Modification
 9527: 
 9528: =over 4
 9529: 
 9530: =item *
 9531: 
 9532: writecoursepref($courseid,%prefs) : write preferences (environment
 9533: database) for a course
 9534: 
 9535: =item *
 9536: 
 9537: createcourse($udom,$description,$url) : make/modify course
 9538: 
 9539: =back
 9540: 
 9541: =head2 Resource Subroutines
 9542: 
 9543: =over 4
 9544: 
 9545: =item *
 9546: 
 9547: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9548: 
 9549: =item *
 9550: 
 9551: repcopy($filename) : subscribes to the requested file, and attempts to
 9552: replicate from the owning library server, Might return
 9553: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9554: 'bad_request', also attempts to grab the metadata for the
 9555: resource. Expects the local filesystem pathname
 9556: (/home/httpd/html/res/....)
 9557: 
 9558: =back
 9559: 
 9560: =head2 Resource Information
 9561: 
 9562: =over 4
 9563: 
 9564: =item *
 9565: 
 9566: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9567: a vairety of different possible values, $varname should be a request
 9568: string, and the other parameters can be used to specify who and what
 9569: one is asking about.
 9570: 
 9571: Possible values for $varname are environment.lastname (or other item
 9572: from the envirnment hash), user.name (or someother aspect about the
 9573: user), resource.0.maxtries (or some other part and parameter of a
 9574: resource)
 9575: 
 9576: =item *
 9577: 
 9578: directcondval($number) : get current value of a condition; reads from a state
 9579: string
 9580: 
 9581: =item *
 9582: 
 9583: condval($condidx) : value of condition index based on state
 9584: 
 9585: =item *
 9586: 
 9587: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9588: resource's metadata, $what should be either a specific key, or either
 9589: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9590: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9591: 
 9592: this function automatically caches all requests
 9593: 
 9594: =item *
 9595: 
 9596: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9597: network of library servers; returns file handle of where SQL and regex results
 9598: will be stored for query
 9599: 
 9600: =item *
 9601: 
 9602: symbread($filename) : return symbolic list entry (filename argument optional);
 9603: returns the data handle
 9604: 
 9605: =item *
 9606: 
 9607: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9608: a possible symb for the URL in $thisfn, and if is an encryypted
 9609: resource that the user accessed using /enc/ returns a 1 on success, 0
 9610: on failure, user must be in a course, as it assumes the existance of
 9611: the course initial hash, and uses $env('request.course.id'}
 9612: 
 9613: 
 9614: =item *
 9615: 
 9616: symbclean($symb) : removes versions numbers from a symb, returns the
 9617: cleaned symb
 9618: 
 9619: =item *
 9620: 
 9621: is_on_map($uri) : checks if the $uri is somewhere on the current
 9622: course map, user must be in a course for it to work.
 9623: 
 9624: =item *
 9625: 
 9626: numval($salt) : return random seed value (addend for rndseed)
 9627: 
 9628: =item *
 9629: 
 9630: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9631: a random seed, all arguments are optional, if they aren't sent it uses the
 9632: environment to derive them. Note: if symb isn't sent and it can't get one
 9633: from &symbread it will use the current time as its return value
 9634: 
 9635: =item *
 9636: 
 9637: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9638: unfakeable, receipt
 9639: 
 9640: =item *
 9641: 
 9642: receipt() : API to ireceipt working off of env values; given out to users
 9643: 
 9644: =item *
 9645: 
 9646: countacc($url) : count the number of accesses to a given URL
 9647: 
 9648: =item *
 9649: 
 9650: 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
 9651: 
 9652: =item *
 9653: 
 9654: 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)
 9655: 
 9656: =item *
 9657: 
 9658: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9659: 
 9660: =item *
 9661: 
 9662: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9663: forcing spreadsheet to reevaluate the resource scores next time.
 9664: 
 9665: =back
 9666: 
 9667: =head2 Storing/Retreiving Data
 9668: 
 9669: =over 4
 9670: 
 9671: =item *
 9672: 
 9673: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9674: for this url; hashref needs to be given and should be a \%hashname; the
 9675: remaining args aren't required and if they aren't passed or are '' they will
 9676: be derived from the env
 9677: 
 9678: =item *
 9679: 
 9680: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9681: uses critical subroutine
 9682: 
 9683: =item *
 9684: 
 9685: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9686: all args are optional
 9687: 
 9688: =item *
 9689: 
 9690: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9691: dumps the complete (or key matching regexp) namespace into a hash
 9692: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9693: normally &store()ed into
 9694: 
 9695: $range should be either an integer '100' (give me the first 100
 9696:                                            matching records)
 9697:               or be  two integers sperated by a - with no spaces
 9698:                  '30-50' (give me the 30th through the 50th matching
 9699:                           records)
 9700: 
 9701: 
 9702: =item *
 9703: 
 9704: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9705: replaces a &store() version of data with a replacement set of data
 9706: for a particular resource in a namespace passed in the $storehash hash 
 9707: reference
 9708: 
 9709: =item *
 9710: 
 9711: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9712: works very similar to store/cstore, but all data is stored in a
 9713: temporary location and can be reset using tmpreset, $storehash should
 9714: be a hash reference, returns nothing on success
 9715: 
 9716: =item *
 9717: 
 9718: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9719: similar to restore, but all data is stored in a temporary location and
 9720: can be reset using tmpreset. Returns a hash of values on success,
 9721: error string otherwise.
 9722: 
 9723: =item *
 9724: 
 9725: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9726: deltes all keys for $symb form the temporary storage hash.
 9727: 
 9728: =item *
 9729: 
 9730: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9731: reference filled in from namesp ($udom and $uname are optional)
 9732: 
 9733: =item *
 9734: 
 9735: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9736: namesp ($udom and $uname are optional)
 9737: 
 9738: =item *
 9739: 
 9740: dump($namespace,$udom,$uname,$regexp,$range) : 
 9741: dumps the complete (or key matching regexp) namespace into a hash
 9742: ($udom, $uname, $regexp, $range are optional)
 9743: 
 9744: $range should be either an integer '100' (give me the first 100
 9745:                                            matching records)
 9746:               or be  two integers sperated by a - with no spaces
 9747:                  '30-50' (give me the 30th through the 50th matching
 9748:                           records)
 9749: =item *
 9750: 
 9751: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9752: $store can be a scalar, an array reference, or if the amount to be 
 9753: incremented is > 1, a hash reference.
 9754: 
 9755: ($udom and $uname are optional)
 9756: 
 9757: =item *
 9758: 
 9759: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9760: ($udom and $uname are optional)
 9761: 
 9762: =item *
 9763: 
 9764: cput($namespace,$storehash,$udom,$uname) : critical put
 9765: ($udom and $uname are optional)
 9766: 
 9767: =item *
 9768: 
 9769: newput($namespace,$storehash,$udom,$uname) :
 9770: 
 9771: Attempts to store the items in the $storehash, but only if they don't
 9772: currently exist, if this succeeds you can be certain that you have 
 9773: successfully created a new key value pair in the $namespace db.
 9774: 
 9775: 
 9776: Args:
 9777:  $namespace: name of database to store values to
 9778:  $storehash: hashref to store to the db
 9779:  $udom: (optional) domain of user containing the db
 9780:  $uname: (optional) name of user caontaining the db
 9781: 
 9782: Returns:
 9783:  'ok' -> succeeded in storing all keys of $storehash
 9784:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9785:                         least <key> already existed in the db (other
 9786:                         requested keys may also already exist)
 9787:  'error: <msg>' -> unable to tie the DB or other error occurred
 9788:  'con_lost' -> unable to contact request server
 9789:  'refused' -> action was not allowed by remote machine
 9790: 
 9791: 
 9792: =item *
 9793: 
 9794: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9795: reference filled in from namesp (encrypts the return communication)
 9796: ($udom and $uname are optional)
 9797: 
 9798: =item *
 9799: 
 9800: log($udom,$name,$home,$message) : write to permanent log for user; use
 9801: critical subroutine
 9802: 
 9803: =item *
 9804: 
 9805: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9806: array reference filled in from namespace found in domain level on either
 9807: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9808: 
 9809: =item *
 9810: 
 9811: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9812: domain level either on specified domain server ($uhome) or primary domain 
 9813: server ($udom and $uhome are optional)
 9814: 
 9815: =item * 
 9816: 
 9817: get_domain_defaults($target_domain) : returns hash with defaults for
 9818: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9819: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9820: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9821: Values are retrieved from cache (if current), or from domain's configuration.db
 9822: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9823: or lonTabs/domain.tab. 
 9824: 
 9825: %domdefaults = &get_auth_defaults($target_domain);
 9826: 
 9827: =back
 9828: 
 9829: =head2 Network Status Functions
 9830: 
 9831: =over 4
 9832: 
 9833: =item *
 9834: 
 9835: dirlist($uri) : return directory list based on URI
 9836: 
 9837: =item *
 9838: 
 9839: spareserver() : find server with least workload from spare.tab
 9840: 
 9841: =back
 9842: 
 9843: =head2 Apache Request
 9844: 
 9845: =over 4
 9846: 
 9847: =item *
 9848: 
 9849: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9850: localhost, posts hash
 9851: 
 9852: =back
 9853: 
 9854: =head2 Data to String to Data
 9855: 
 9856: =over 4
 9857: 
 9858: =item *
 9859: 
 9860: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9861: and '&' separators, supports elements that are arrayrefs and hashrefs
 9862: 
 9863: =item *
 9864: 
 9865: hashref2str($hashref) : convert a hashref into a string complete with
 9866: escaping and '=' and '&' separators, supports elements that are
 9867: arrayrefs and hashrefs
 9868: 
 9869: =item *
 9870: 
 9871: arrayref2str($arrayref) : convert an arrayref into a string complete
 9872: with escaping and '&' separators, supports elements that are arrayrefs
 9873: and hashrefs
 9874: 
 9875: =item *
 9876: 
 9877: str2hash($string) : convert string to hash using unescaping and
 9878: splitting on '=' and '&', supports elements that are arrayrefs and
 9879: hashrefs
 9880: 
 9881: =item *
 9882: 
 9883: str2array($string) : convert string to hash using unescaping and
 9884: splitting on '&', supports elements that are arrayrefs and hashrefs
 9885: 
 9886: =back
 9887: 
 9888: =head2 Logging Routines
 9889: 
 9890: =over 4
 9891: 
 9892: These routines allow one to make log messages in the lonnet.log and
 9893: lonnet.perm logfiles.
 9894: 
 9895: =item *
 9896: 
 9897: logtouch() : make sure the logfile, lonnet.log, exists
 9898: 
 9899: =item *
 9900: 
 9901: logthis() : append message to the normal lonnet.log file, it gets
 9902: preiodically rolled over and deleted.
 9903: 
 9904: =item *
 9905: 
 9906: logperm() : append a permanent message to lonnet.perm.log, this log
 9907: file never gets deleted by any automated portion of the system, only
 9908: messages of critical importance should go in here.
 9909: 
 9910: =back
 9911: 
 9912: =head2 General File Helper Routines
 9913: 
 9914: =over 4
 9915: 
 9916: =item *
 9917: 
 9918: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9919: (a) files in /uploaded
 9920:   (i) If a local copy of the file exists - 
 9921:       compares modification date of local copy with last-modified date for 
 9922:       definitive version stored on home server for course. If local copy is 
 9923:       stale, requests a new version from the home server and stores it. 
 9924:       If the original has been removed from the home server, then local copy 
 9925:       is unlinked.
 9926:   (ii) If local copy does not exist -
 9927:       requests the file from the home server and stores it. 
 9928:   
 9929:   If $caller is 'uploadrep':  
 9930:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9931:     for request for files originally uploaded via DOCS. 
 9932:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9933:   
 9934:   Otherwise:
 9935:      This indicates a call from the content generation phase of the request.
 9936:      -  returns the entire contents of the file or -1.
 9937:      
 9938: (b) files in /res
 9939:    - returns the entire contents of a file or -1; 
 9940:    it properly subscribes to and replicates the file if neccessary.
 9941: 
 9942: 
 9943: =item *
 9944: 
 9945: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9946:                   reference
 9947: 
 9948: returns either a stat() list of data about the file or an empty list
 9949: if the file doesn't exist or couldn't find out about it (connection
 9950: problems or user unknown)
 9951: 
 9952: =item *
 9953: 
 9954: filelocation($dir,$file) : returns file system location of a file
 9955: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9956: directory that relative $file lookups are to looked in ($dir of /a/dir
 9957: and a file of ../bob will become /a/bob)
 9958: 
 9959: =item *
 9960: 
 9961: hreflocation($dir,$file) : returns file system location or a URL; same as
 9962: filelocation except for hrefs
 9963: 
 9964: =item *
 9965: 
 9966: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9967: 
 9968: =back
 9969: 
 9970: =head2 Usererfile file routines (/uploaded*)
 9971: 
 9972: =over 4
 9973: 
 9974: =item *
 9975: 
 9976: userfileupload(): main rotine for putting a file in a user or course's
 9977:                   filespace, arguments are,
 9978: 
 9979:  formname - required - this is the name of the element in $env where the
 9980:            filename, and the contents of the file to create/modifed exist
 9981:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9982:            contents of the file is located in $env{'form.'.$formname}
 9983:  coursedoc - if true, store the file in the course of the active role
 9984:              of the current user
 9985:  subdir - required - subdirectory to put the file in under ../userfiles/
 9986:          if undefined, it will be placed in "unknown"
 9987: 
 9988:  (This routine calls clean_filename() to remove any dangerous
 9989:  characters from the filename, and then calls finuserfileupload() to
 9990:  complete the transaction)
 9991: 
 9992:  returns either the url of the uploaded file (/uploaded/....) if successful
 9993:  and /adm/notfound.html if unsuccessful
 9994: 
 9995: =item *
 9996: 
 9997: clean_filename(): routine for cleaing a filename up for storage in
 9998:                  userfile space, argument is:
 9999: 
10000:  filename - proposed filename
10001: 
10002: returns: the new clean filename
10003: 
10004: =item *
10005: 
10006: finishuserfileupload(): routine that creaes and sends the file to
10007: userspace, probably shouldn't be called directly
10008: 
10009:   docuname: username or courseid of destination for the file
10010:   docudom: domain of user/course of destination for the file
10011:   formname: same as for userfileupload()
10012:   fname: filename (inculding subdirectories) for the file
10013: 
10014:  returns either the url of the uploaded file (/uploaded/....) if successful
10015:  and /adm/notfound.html if unsuccessful
10016: 
10017: =item *
10018: 
10019: renameuserfile(): renames an existing userfile to a new name
10020: 
10021:   Args:
10022:    docuname: username or courseid of destination for the file
10023:    docudom: domain of user/course of destination for the file
10024:    old: current file name (including any subdirs under userfiles)
10025:    new: desired file name (including any subdirs under userfiles)
10026: 
10027: =item *
10028: 
10029: mkdiruserfile(): creates a directory is a userfiles dir
10030: 
10031:   Args:
10032:    docuname: username or courseid of destination for the file
10033:    docudom: domain of user/course of destination for the file
10034:    dir: dir to create (including any subdirs under userfiles)
10035: 
10036: =item *
10037: 
10038: removeuserfile(): removes a file that exists in userfiles
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:    fname: filname to delete (including any subdirs under userfiles)
10044: 
10045: =item *
10046: 
10047: removeuploadedurl(): convience function for removeuserfile()
10048: 
10049:   Args:
10050:    url:  a full /uploaded/... url to delete
10051: 
10052: =item * 
10053: 
10054: get_portfile_permissions():
10055:   Args:
10056:     domain: domain of user or course contain the portfolio files
10057:     user: name of user or num of course contain the portfolio files
10058:   Returns:
10059:     hashref of a dump of the proper file_permissions.db
10060:    
10061: 
10062: =item * 
10063: 
10064: get_access_controls():
10065: 
10066: Args:
10067:   current_permissions: the hash ref returned from get_portfile_permissions()
10068:   group: (optional) the group you want the files associated with
10069:   file: (optional) the file you want access info on
10070: 
10071: Returns:
10072:     a hash (keys are file names) of hashes containing
10073:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10074:         values are XML containing access control settings (see below) 
10075: 
10076: Internal notes:
10077: 
10078:  access controls are stored in file_permissions.db as key=value pairs.
10079:     key -> path to file/file_name\0uniqueID:scope_end_start
10080:         where scope -> public,guest,course,group,domains or users.
10081:               end -> UNIX time for end of access (0 -> no end date)
10082:               start -> UNIX time for start of access
10083: 
10084:     value -> XML description of access control
10085:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10086:             <start></start>
10087:             <end></end>
10088: 
10089:             <password></password>  for scope type = guest
10090: 
10091:             <domain></domain>     for scope type = course or group
10092:             <number></number>
10093:             <roles id="">
10094:              <role></role>
10095:              <access></access>
10096:              <section></section>
10097:              <group></group>
10098:             </roles>
10099: 
10100:             <dom></dom>         for scope type = domains
10101: 
10102:             <users>             for scope type = users
10103:              <user>
10104:               <uname></uname>
10105:               <udom></udom>
10106:              </user>
10107:             </users>
10108:            </scope> 
10109:               
10110:  Access data is also aggregated for each file in an additional key=value pair:
10111:  key -> path to file/file_name\0accesscontrol 
10112:  value -> reference to hash
10113:           hash contains key = value pairs
10114:           where key = uniqueID:scope_end_start
10115:                 value = UNIX time record was last updated
10116: 
10117:           Used to improve speed of look-ups of access controls for each file.  
10118:  
10119:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10120: 
10121: modify_access_controls():
10122: 
10123: Modifies access controls for a portfolio file
10124: Args
10125: 1. file name
10126: 2. reference to hash of required changes,
10127: 3. domain
10128: 4. username
10129:   where domain,username are the domain of the portfolio owner 
10130:   (either a user or a course) 
10131: 
10132: Returns:
10133: 1. result of additions or updates ('ok' or 'error', with error message). 
10134: 2. result of deletions ('ok' or 'error', with error message).
10135: 3. reference to hash of any new or updated access controls.
10136: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10137:    key = integer (inbound ID)
10138:    value = uniqueID  
10139: 
10140: =back
10141: 
10142: =head2 HTTP Helper Routines
10143: 
10144: =over 4
10145: 
10146: =item *
10147: 
10148: escape() : unpack non-word characters into CGI-compatible hex codes
10149: 
10150: =item *
10151: 
10152: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10153: 
10154: =back
10155: 
10156: =head1 PRIVATE SUBROUTINES
10157: 
10158: =head2 Underlying communication routines (Shouldn't call)
10159: 
10160: =over 4
10161: 
10162: =item *
10163: 
10164: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10165: 
10166: =item *
10167: 
10168: reply() : uses subreply to send a message to remote machine, logs all failures
10169: 
10170: =item *
10171: 
10172: critical() : passes a critical message to another server; if cannot
10173: get through then place message in connection buffer directory and
10174: returns con_delayed, if incapable of saving message, returns
10175: con_failed
10176: 
10177: =item *
10178: 
10179: reconlonc() : tries to reconnect lonc client processes.
10180: 
10181: =back
10182: 
10183: =head2 Resource Access Logging
10184: 
10185: =over 4
10186: 
10187: =item *
10188: 
10189: flushcourselogs() : flush (save) buffer logs and access logs
10190: 
10191: =item *
10192: 
10193: courselog($what) : save message for course in hash
10194: 
10195: =item *
10196: 
10197: courseacclog($what) : save message for course using &courselog().  Perform
10198: special processing for specific resource types (problems, exams, quizzes, etc).
10199: 
10200: =item *
10201: 
10202: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10203: as a PerlChildExitHandler
10204: 
10205: =back
10206: 
10207: =head2 Other
10208: 
10209: =over 4
10210: 
10211: =item *
10212: 
10213: symblist($mapname,%newhash) : update symbolic storage links
10214: 
10215: =back
10216: 
10217: =cut
10218: 

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