File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.976.2.10: download - view: text, annotated - select for diffs
Fri Oct 9 12:42:36 2009 UTC (14 years, 9 months ago) by raeburn
Branches: version_2_8_X
Diff to branchpoint 1.976: preferred, unified
- Backport 1.1030.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.976.2.10 2009/10/09 12:42:36 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: # use Date::Parse;
   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   78:             $_64bit %env %protocol);
   79: 
   80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   83:     %courseownerbuf, %coursetypebuf,$locknum);
   84: 
   85: use IO::Socket;
   86: use GDBM_File;
   87: use HTML::LCParser;
   88: use Fcntl qw(:flock);
   89: use Storable qw(thaw nfreeze);
   90: use Time::HiRes qw( gettimeofday tv_interval );
   91: use Cache::Memcached;
   92: use Digest::MD5;
   93: use Math::Random;
   94: use LONCAPA qw(:DEFAULT :match);
   95: use LONCAPA::Configuration;
   96: 
   97: my $readit;
   98: my $max_connection_retries = 10;     # Or some such value.
   99: 
  100: require Exporter;
  101: 
  102: our @ISA = qw (Exporter);
  103: our @EXPORT = qw(%env);
  104: 
  105: 
  106: # --------------------------------------------------------------------- Logging
  107: {
  108:     my $logid;
  109:     sub instructor_log {
  110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  111:         if (($cnum eq '') || ($cdom eq '')) {
  112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  114:         }
  115: 	$logid++;
  116:         my $now = time();
  117: 	my $id=$now.'00000'.$$.'00000'.$logid;
  118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  119: 				    { $id => {
  120: 					'exe_uname' => $env{'user.name'},
  121: 					'exe_udom'  => $env{'user.domain'},
  122: 					'exe_time'  => $now,
  123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  124: 					'delflag'   => $delflag,
  125: 					'logentry'  => $storehash,
  126: 					'uname'     => $uname,
  127: 					'udom'      => $udom,
  128: 				    }
  129: 				  },$cdom,$cnum);
  130:     }
  131: }
  132: 
  133: sub logtouch {
  134:     my $execdir=$perlvar{'lonDaemons'};
  135:     unless (-e "$execdir/logs/lonnet.log") {	
  136: 	open(my $fh,">>$execdir/logs/lonnet.log");
  137: 	close $fh;
  138:     }
  139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  141: }
  142: 
  143: sub logthis {
  144:     my $message=shift;
  145:     my $execdir=$perlvar{'lonDaemons'};
  146:     my $now=time;
  147:     my $local=localtime($now);
  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  149: 	print $fh "$local ($$): $message\n";
  150: 	close($fh);
  151:     }
  152:     return 1;
  153: }
  154: 
  155: sub logperm {
  156:     my $message=shift;
  157:     my $execdir=$perlvar{'lonDaemons'};
  158:     my $now=time;
  159:     my $local=localtime($now);
  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  161: 	print $fh "$now:$message:$local\n";
  162: 	close($fh);
  163:     }
  164:     return 1;
  165: }
  166: 
  167: sub create_connection {
  168:     my ($hostname,$lonid) = @_;
  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  170: 				     Type    => SOCK_STREAM,
  171: 				     Timeout => 10);
  172:     return 0 if (!$client);
  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  174:     my $result = <$client>;
  175:     chomp($result);
  176:     return 1 if ($result eq 'done');
  177:     return 0;
  178: }
  179: 
  180: sub get_server_timezone {
  181:     my ($cnum,$cdom) = @_;
  182:     my $home=&homeserver($cnum,$cdom);
  183:     if ($home ne 'no_host') {
  184:         my $cachetime = 24*3600;
  185:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  186:         if (defined($cached)) {
  187:             return $timezone;
  188:         } else {
  189:             my $timezone = &reply('servertimezone',$home);
  190:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  191:         }
  192:     }
  193: }
  194: 
  195: # -------------------------------------------------- Non-critical communication
  196: sub subreply {
  197:     my ($cmd,$server)=@_;
  198:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  199:     #
  200:     #  With loncnew process trimming, there's a timing hole between lonc server
  201:     #  process exit and the master server picking up the listen on the AF_UNIX
  202:     #  socket.  In that time interval, a lock file will exist:
  203: 
  204:     my $lockfile=$peerfile.".lock";
  205:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  206: 	sleep(1);
  207:     }
  208:     # At this point, either a loncnew parent is listening or an old lonc
  209:     # or loncnew child is listening so we can connect or everything's dead.
  210:     #
  211:     #   We'll give the connection a few tries before abandoning it.  If
  212:     #   connection is not possible, we'll con_lost back to the client.
  213:     #   
  214:     my $client;
  215:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  216: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  217: 				      Type    => SOCK_STREAM,
  218: 				      Timeout => 10);
  219: 	if ($client) {
  220: 	    last;		# Connected!
  221: 	} else {
  222: 	    &create_connection(&hostname($server),$server);
  223: 	}
  224:         sleep(1);		# Try again later if failed connection.
  225:     }
  226:     my $answer;
  227:     if ($client) {
  228: 	print $client "sethost:$server:$cmd\n";
  229: 	$answer=<$client>;
  230: 	if (!$answer) { $answer="con_lost"; }
  231: 	chomp($answer);
  232:     } else {
  233: 	$answer = 'con_lost';	# Failed connection.
  234:     }
  235:     return $answer;
  236: }
  237: 
  238: sub reply {
  239:     my ($cmd,$server)=@_;
  240:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  241:     my $answer=subreply($cmd,$server);
  242:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  243:        &logthis("<font color=\"blue\">WARNING:".
  244:                 " $cmd to $server returned $answer</font>");
  245:     }
  246:     return $answer;
  247: }
  248: 
  249: # ----------------------------------------------------------- Send USR1 to lonc
  250: 
  251: sub reconlonc {
  252:     my ($lonid) = @_;
  253:     my $hostname = &hostname($lonid);
  254:     if ($lonid) {
  255: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  256: 	if ($hostname && -e $peerfile) {
  257: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  258: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  259: 					     Type    => SOCK_STREAM,
  260: 					     Timeout => 10);
  261: 	    if ($client) {
  262: 		print $client ("reset_retries\n");
  263: 		my $answer=<$client>;
  264: 		#reset just this one.
  265: 	    }
  266: 	}
  267: 	return;
  268:     }
  269: 
  270:     &logthis("Trying to reconnect lonc");
  271:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  272:     if (open(my $fh,"<$loncfile")) {
  273: 	my $loncpid=<$fh>;
  274:         chomp($loncpid);
  275:         if (kill 0 => $loncpid) {
  276: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  277:             kill USR1 => $loncpid;
  278:             sleep 1;
  279:          } else {
  280: 	    &logthis(
  281:                "<font color=\"blue\">WARNING:".
  282:                " lonc at pid $loncpid not responding, giving up</font>");
  283:         }
  284:     } else {
  285: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  286:     }
  287: }
  288: 
  289: # ------------------------------------------------------ Critical communication
  290: 
  291: sub critical {
  292:     my ($cmd,$server)=@_;
  293:     unless (&hostname($server)) {
  294:         &logthis("<font color=\"blue\">WARNING:".
  295:                " Critical message to unknown server ($server)</font>");
  296:         return 'no_such_host';
  297:     }
  298:     my $answer=reply($cmd,$server);
  299:     if ($answer eq 'con_lost') {
  300: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  301: 	my $answer=reply($cmd,$server);
  302:         if ($answer eq 'con_lost') {
  303:             my $now=time;
  304:             my $middlename=$cmd;
  305:             $middlename=substr($middlename,0,16);
  306:             $middlename=~s/\W//g;
  307:             my $dfilename=
  308:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  309:             $dumpcount++;
  310:             {
  311: 		my $dfh;
  312: 		if (open($dfh,">$dfilename")) {
  313: 		    print $dfh "$cmd\n"; 
  314: 		    close($dfh);
  315: 		}
  316:             }
  317:             sleep 2;
  318:             my $wcmd='';
  319:             {
  320: 		my $dfh;
  321: 		if (open($dfh,"<$dfilename")) {
  322: 		    $wcmd=<$dfh>; 
  323: 		    close($dfh);
  324: 		}
  325:             }
  326:             chomp($wcmd);
  327:             if ($wcmd eq $cmd) {
  328: 		&logthis("<font color=\"blue\">WARNING: ".
  329:                          "Connection buffer $dfilename: $cmd</font>");
  330:                 &logperm("D:$server:$cmd");
  331: 	        return 'con_delayed';
  332:             } else {
  333:                 &logthis("<font color=\"red\">CRITICAL:"
  334:                         ." Critical connection failed: $server $cmd</font>");
  335:                 &logperm("F:$server:$cmd");
  336:                 return 'con_failed';
  337:             }
  338:         }
  339:     }
  340:     return $answer;
  341: }
  342: 
  343: # ------------------------------------------- check if return value is an error
  344: 
  345: sub error {
  346:     my ($result) = @_;
  347:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  348: 	if ($2 == 2) { return undef; }
  349: 	return $1;
  350:     }
  351:     return undef;
  352: }
  353: 
  354: sub convert_and_load_session_env {
  355:     my ($lonidsdir,$handle)=@_;
  356:     my @profile;
  357:     {
  358: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  359: 	if (!$opened) {
  360: 	    return 0;
  361: 	}
  362: 	flock($idf,LOCK_SH);
  363: 	@profile=<$idf>;
  364: 	close($idf);
  365:     }
  366:     my %temp_env;
  367:     foreach my $line (@profile) {
  368: 	if ($line !~ m/=/) {
  369: 	    return 0;
  370: 	}
  371: 	chomp($line);
  372: 	my ($envname,$envvalue)=split(/=/,$line,2);
  373: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  374:     }
  375:     unlink("$lonidsdir/$handle.id");
  376:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  377: 	    0640)) {
  378: 	%disk_env = %temp_env;
  379: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  380: 	untie(%disk_env);
  381:     }
  382:     return 1;
  383: }
  384: 
  385: # ------------------------------------------- Transfer profile into environment
  386: my $env_loaded;
  387: sub transfer_profile_to_env {
  388:     my ($lonidsdir,$handle,$force_transfer) = @_;
  389:     if (!$force_transfer && $env_loaded) { return; } 
  390: 
  391:     if (!defined($lonidsdir)) {
  392: 	$lonidsdir = $perlvar{'lonIDsDir'};
  393:     }
  394:     if (!defined($handle)) {
  395:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  396:     }
  397: 
  398:     my $convert;
  399:     {
  400:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  401: 	if (!$opened) {
  402: 	    return;
  403: 	}
  404: 	flock($idf,LOCK_SH);
  405: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  406: 		&GDBM_READER(),0640)) {
  407: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  408: 	    untie(%disk_env);
  409: 	} else {
  410: 	    $convert = 1;
  411: 	}
  412:     }
  413:     if ($convert) {
  414: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  415: 	    &logthis("Failed to load session, or convert session.");
  416: 	}
  417:     }
  418: 
  419:     my %remove;
  420:     while ( my $envname = each(%env) ) {
  421:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  422:             if ($time < time-300) {
  423:                 $remove{$key}++;
  424:             }
  425:         }
  426:     }
  427: 
  428:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  429:     $env_loaded=1;
  430:     foreach my $expired_key (keys(%remove)) {
  431:         &delenv($expired_key);
  432:     }
  433: }
  434: 
  435: # ---------------------------------------------------- Check for valid session 
  436: sub check_for_valid_session {
  437:     my ($r) = @_;
  438:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  439:     my $lonid=$cookies{'lonID'};
  440:     return undef if (!$lonid);
  441: 
  442:     my $handle=&LONCAPA::clean_handle($lonid->value);
  443:     my $lonidsdir=$r->dir_config('lonIDsDir');
  444:     return undef if (!-e "$lonidsdir/$handle.id");
  445: 
  446:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  447:     return undef if (!$opened);
  448: 
  449:     flock($idf,LOCK_SH);
  450:     my %disk_env;
  451:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  452: 	    &GDBM_READER(),0640)) {
  453: 	return undef;	
  454:     }
  455: 
  456:     if (!defined($disk_env{'user.name'})
  457: 	|| !defined($disk_env{'user.domain'})) {
  458: 	return undef;
  459:     }
  460:     return $handle;
  461: }
  462: 
  463: sub timed_flock {
  464:     my ($file,$lock_type) = @_;
  465:     my $failed=0;
  466:     eval {
  467: 	local $SIG{__DIE__}='DEFAULT';
  468: 	local $SIG{ALRM}=sub {
  469: 	    $failed=1;
  470: 	    die("failed lock");
  471: 	};
  472: 	alarm(13);
  473: 	flock($file,$lock_type);
  474: 	alarm(0);
  475:     };
  476:     if ($failed) {
  477: 	return undef;
  478:     } else {
  479: 	return 1;
  480:     }
  481: }
  482: 
  483: # ---------------------------------------------------------- Append Environment
  484: 
  485: sub appenv {
  486:     my ($newenv,$roles) = @_;
  487:     if (ref($newenv) eq 'HASH') {
  488:         foreach my $key (keys(%{$newenv})) {
  489:             my $refused = 0;
  490: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  491:                 $refused = 1;
  492:                 if (ref($roles) eq 'ARRAY') {
  493:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  494:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  495:                         $refused = 0;
  496:                     }
  497:                 }
  498:             }
  499:             if ($refused) {
  500:                 &logthis("<font color=\"blue\">WARNING: ".
  501:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  502:                          .'</font>');
  503: 	        delete($newenv->{$key});
  504:             } else {
  505:                 $env{$key}=$newenv->{$key};
  506:             }
  507:         }
  508:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  509:         if ($opened
  510: 	    && &timed_flock($env_file,LOCK_EX)
  511: 	    &&
  512: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  513: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  514: 	    while (my ($key,$value) = each(%{$newenv})) {
  515: 	        $disk_env{$key} = $value;
  516: 	    }
  517: 	    untie(%disk_env);
  518:         }
  519:     }
  520:     return 'ok';
  521: }
  522: # ----------------------------------------------------- Delete from Environment
  523: 
  524: sub delenv {
  525:     my ($delthis,$regexp) = @_;
  526:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  527:         &logthis("<font color=\"blue\">WARNING: ".
  528:                 "Attempt to delete from environment ".$delthis);
  529:         return 'error';
  530:     }
  531:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  532:     if ($opened
  533: 	&& &timed_flock($env_file,LOCK_EX)
  534: 	&&
  535: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  536: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  537: 	foreach my $key (keys(%disk_env)) {
  538:             if ($regexp) {
  539:                 if ($key=~/^$delthis/) {
  540:                     delete($env{$key});
  541:                     delete($disk_env{$key});
  542:                 }
  543:             } else {
  544:                 if ($key=~/^\Q$delthis\E/) {
  545:                     delete($env{$key});
  546:                     delete($disk_env{$key});
  547:                 }
  548:             }
  549: 	}
  550: 	untie(%disk_env);
  551:     }
  552:     return 'ok';
  553: }
  554: 
  555: sub get_env_multiple {
  556:     my ($name) = @_;
  557:     my @values;
  558:     if (defined($env{$name})) {
  559:         # exists is it an array
  560:         if (ref($env{$name})) {
  561:             @values=@{ $env{$name} };
  562:         } else {
  563:             $values[0]=$env{$name};
  564:         }
  565:     }
  566:     return(@values);
  567: }
  568: 
  569: # ------------------------------------------------------------------- Locking
  570: 
  571: sub set_lock {
  572:     my ($text)=@_;
  573:     $locknum++;
  574:     my $id=$$.'-'.$locknum;
  575:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  576:              'session.lock.'.$id => $text});
  577:     return $id;
  578: }
  579: 
  580: sub get_locks {
  581:     my $num=0;
  582:     my %texts=();
  583:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  584:        if ($lock=~/\w/) {
  585:           $num++;
  586:           $texts{$lock}=$env{'session.lock.'.$lock};
  587:        }
  588:    }
  589:    return ($num,%texts);
  590: }
  591: 
  592: sub remove_lock {
  593:     my ($id)=@_;
  594:     my $newlocks='';
  595:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  596:        if (($lock=~/\w/) && ($lock ne $id)) {
  597:           $newlocks.=','.$lock;
  598:        }
  599:     }
  600:     &appenv({'session.locks' => $newlocks});
  601:     &delenv('session.lock.'.$id);
  602: }
  603: 
  604: sub remove_all_locks {
  605:     my $activelocks=$env{'session.locks'};
  606:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  607:        if ($lock=~/\w/) {
  608:           &remove_lock($lock);
  609:        }
  610:     }
  611: }
  612: 
  613: 
  614: # ------------------------------------------ Find out current server userload
  615: sub userload {
  616:     my $numusers=0;
  617:     {
  618: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  619: 	my $filename;
  620: 	my $curtime=time;
  621: 	while ($filename=readdir(LONIDS)) {
  622: 	    next if ($filename eq '.' || $filename eq '..');
  623: 	    next if ($filename =~ /publicuser_\d+\.id/);
  624: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  625: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  626: 	}
  627: 	closedir(LONIDS);
  628:     }
  629:     my $userloadpercent=0;
  630:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  631:     if ($maxuserload) {
  632: 	$userloadpercent=100*$numusers/$maxuserload;
  633:     }
  634:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  635:     return $userloadpercent;
  636: }
  637: 
  638: # ------------------------------------------ Fight off request when overloaded
  639: 
  640: sub overloaderror {
  641:     my ($r,$checkserver)=@_;
  642:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  643:     my $loadavg;
  644:     if ($checkserver eq $perlvar{'lonHostID'}) {
  645:        open(my $loadfile,'/proc/loadavg');
  646:        $loadavg=<$loadfile>;
  647:        $loadavg =~ s/\s.*//g;
  648:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  649:        close($loadfile);
  650:     } else {
  651:        $loadavg=&reply('load',$checkserver);
  652:     }
  653:     my $overload=$loadavg-100;
  654:     if ($overload>0) {
  655: 	$r->err_headers_out->{'Retry-After'}=$overload;
  656:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  657:         return 413;
  658:     }    
  659:     return '';
  660: }
  661: 
  662: # ------------------------------ Find server with least workload from spare.tab
  663: 
  664: sub spareserver {
  665:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  666:     my $spare_server;
  667:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  668:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  669:                                                      :  $userloadpercent;
  670:     
  671:     foreach my $try_server (@{ $spareid{'primary'} }) {
  672: 	($spare_server, $lowest_load) =
  673: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  674:     }
  675: 
  676:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  677: 
  678:     if (!$found_server) {
  679: 	foreach my $try_server (@{ $spareid{'default'} }) {
  680: 	    ($spare_server, $lowest_load) =
  681: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  682: 	}
  683:     }
  684: 
  685:     if (!$want_server_name) {
  686:         my $protocol = 'http';
  687:         if ($protocol{$spare_server} eq 'https') {
  688:             $protocol = $protocol{$spare_server};
  689:         }
  690: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  691:     }
  692:     return $spare_server;
  693: }
  694: 
  695: sub compare_server_load {
  696:     my ($try_server, $spare_server, $lowest_load) = @_;
  697: 
  698:     my $loadans     = &reply('load',    $try_server);
  699:     my $userloadans = &reply('userload',$try_server);
  700: 
  701:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  702: 	next; #didn't get a number from the server
  703:     }
  704: 
  705:     my $load;
  706:     if ($loadans =~ /\d/) {
  707: 	if ($userloadans =~ /\d/) {
  708: 	    #both are numbers, pick the bigger one
  709: 	    $load = ($loadans > $userloadans) ? $loadans 
  710: 		                              : $userloadans;
  711: 	} else {
  712: 	    $load = $loadans;
  713: 	}
  714:     } else {
  715: 	$load = $userloadans;
  716:     }
  717: 
  718:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  719: 	$spare_server = $try_server;
  720: 	$lowest_load  = $load;
  721:     }
  722:     return ($spare_server,$lowest_load);
  723: }
  724: 
  725: # --------------------------- ask offload servers if user already has a session
  726: sub find_existing_session {
  727:     my ($udom,$uname) = @_;
  728:     foreach my $try_server (@{ $spareid{'primary'} },
  729: 			    @{ $spareid{'default'} }) {
  730: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  731:     }
  732:     return;
  733: }
  734: 
  735: # -------------------------------- ask if server already has a session for user
  736: sub has_user_session {
  737:     my ($lonid,$udom,$uname) = @_;
  738:     my $result = &reply(join(':','userhassession',
  739: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  740:     return 1 if ($result eq 'ok');
  741: 
  742:     return 0;
  743: }
  744: 
  745: # --------------------------------------------- Try to change a user's password
  746: 
  747: sub changepass {
  748:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  749:     $currentpass = &escape($currentpass);
  750:     $newpass     = &escape($newpass);
  751:     my $lonhost = $perlvar{'lonHostID'};
  752:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  753: 		       $server);
  754:     if (! $answer) {
  755: 	&logthis("No reply on password change request to $server ".
  756: 		 "by $uname in domain $udom.");
  757:     } elsif ($answer =~ "^ok") {
  758:         &logthis("$uname in $udom successfully changed their password ".
  759: 		 "on $server.");
  760:     } elsif ($answer =~ "^pwchange_failure") {
  761: 	&logthis("$uname in $udom was unable to change their password ".
  762: 		 "on $server.  The action was blocked by either lcpasswd ".
  763: 		 "or pwchange");
  764:     } elsif ($answer =~ "^non_authorized") {
  765:         &logthis("$uname in $udom did not get their password correct when ".
  766: 		 "attempting to change it on $server.");
  767:     } elsif ($answer =~ "^auth_mode_error") {
  768:         &logthis("$uname in $udom attempted to change their password despite ".
  769: 		 "not being locally or internally authenticated on $server.");
  770:     } elsif ($answer =~ "^unknown_user") {
  771:         &logthis("$uname in $udom attempted to change their password ".
  772: 		 "on $server but were unable to because $server is not ".
  773: 		 "their home server.");
  774:     } elsif ($answer =~ "^refused") {
  775: 	&logthis("$server refused to change $uname in $udom password because ".
  776: 		 "it was sent an unencrypted request to change the password.");
  777:     } elsif ($answer =~ "invalid_client") {
  778:         &logthis("$server refused to change $uname in $udom password because ".
  779:                  "it was a reset by e-mail originating from an invalid server.");
  780:     }
  781:     return $answer;
  782: }
  783: 
  784: # ----------------------- Try to determine user's current authentication scheme
  785: 
  786: sub queryauthenticate {
  787:     my ($uname,$udom)=@_;
  788:     my $uhome=&homeserver($uname,$udom);
  789:     if (!$uhome) {
  790: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  791: 	return 'no_host';
  792:     }
  793:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  794:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  795: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  796:     }
  797:     return $answer;
  798: }
  799: 
  800: # --------- Try to authenticate user from domain's lib servers (first this one)
  801: 
  802: sub authenticate {
  803:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  804:     $upass=&escape($upass);
  805:     $uname= &LONCAPA::clean_username($uname);
  806:     my $uhome=&homeserver($uname,$udom,1);
  807:     my $newhome;
  808:     if ((!$uhome) || ($uhome eq 'no_host')) {
  809: # Maybe the machine was offline and only re-appeared again recently?
  810:         &reconlonc();
  811: # One more
  812: 	$uhome=&homeserver($uname,$udom,1);
  813:         if (($uhome eq 'no_host') && $checkdefauth) {
  814:             if (defined(&domain($udom,'primary'))) {
  815:                 $newhome=&domain($udom,'primary');
  816:             }
  817:             if ($newhome ne '') {
  818:                 $uhome = $newhome;
  819:             }
  820:         }
  821: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  822: 	    &logthis("User $uname at $udom is unknown in authenticate");
  823: 	    return 'no_host';
  824:         }
  825:     }
  826:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  827:     if ($answer eq 'authorized') {
  828:         if ($newhome) {
  829:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  830:             return 'no_account_on_host'; 
  831:         } else {
  832:             &logthis("User $uname at $udom authorized by $uhome");
  833:             return $uhome;
  834:         }
  835:     }
  836:     if ($answer eq 'non_authorized') {
  837: 	&logthis("User $uname at $udom rejected by $uhome");
  838: 	return 'no_host'; 
  839:     }
  840:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  841:     return 'no_host';
  842: }
  843: 
  844: # ---------------------- Find the homebase for a user from domain's lib servers
  845: 
  846: my %homecache;
  847: sub homeserver {
  848:     my ($uname,$udom,$ignoreBadCache)=@_;
  849:     my $index="$uname:$udom";
  850: 
  851:     if (exists($homecache{$index})) { return $homecache{$index}; }
  852: 
  853:     my %servers = &get_servers($udom,'library');
  854:     foreach my $tryserver (keys(%servers)) {
  855:         next if ($ignoreBadCache ne 'true' && 
  856: 		 exists($badServerCache{$tryserver}));
  857: 
  858: 	my $answer=reply("home:$udom:$uname",$tryserver);
  859: 	if ($answer eq 'found') {
  860: 	    delete($badServerCache{$tryserver}); 
  861: 	    return $homecache{$index}=$tryserver;
  862: 	} elsif ($answer eq 'no_host') {
  863: 	    $badServerCache{$tryserver}=1;
  864: 	}
  865:     }    
  866:     return 'no_host';
  867: }
  868: 
  869: # ------------------------------------- Find the usernames behind a list of IDs
  870: 
  871: sub idget {
  872:     my ($udom,@ids)=@_;
  873:     my %returnhash=();
  874:     
  875:     my %servers = &get_servers($udom,'library');
  876:     foreach my $tryserver (keys(%servers)) {
  877: 	my $idlist=join('&',@ids);
  878: 	$idlist=~tr/A-Z/a-z/; 
  879: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  880: 	my @answer=();
  881: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  882: 	    @answer=split(/\&/,$reply);
  883: 	}                    ;
  884: 	my $i;
  885: 	for ($i=0;$i<=$#ids;$i++) {
  886: 	    if ($answer[$i]) {
  887: 		$returnhash{$ids[$i]}=$answer[$i];
  888: 	    } 
  889: 	}
  890:     } 
  891:     return %returnhash;
  892: }
  893: 
  894: # ------------------------------------- Find the IDs behind a list of usernames
  895: 
  896: sub idrget {
  897:     my ($udom,@unames)=@_;
  898:     my %returnhash=();
  899:     foreach my $uname (@unames) {
  900:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  901:     }
  902:     return %returnhash;
  903: }
  904: 
  905: # ------------------------------- Store away a list of names and associated IDs
  906: 
  907: sub idput {
  908:     my ($udom,%ids)=@_;
  909:     my %servers=();
  910:     foreach my $uname (keys(%ids)) {
  911: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  912:         my $uhom=&homeserver($uname,$udom);
  913:         if ($uhom ne 'no_host') {
  914:             my $id=&escape($ids{$uname});
  915:             $id=~tr/A-Z/a-z/;
  916:             my $esc_unam=&escape($uname);
  917: 	    if ($servers{$uhom}) {
  918: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  919:             } else {
  920:                 $servers{$uhom}=$id.'='.$esc_unam;
  921:             }
  922:         }
  923:     }
  924:     foreach my $server (keys(%servers)) {
  925:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  926:     }
  927: }
  928: 
  929: # ------------------------------------------- get items from domain db files   
  930: 
  931: sub get_dom {
  932:     my ($namespace,$storearr,$udom,$uhome)=@_;
  933:     my $items='';
  934:     foreach my $item (@$storearr) {
  935:         $items.=&escape($item).'&';
  936:     }
  937:     $items=~s/\&$//;
  938:     if (!$udom) {
  939:         $udom=$env{'user.domain'};
  940:         if (defined(&domain($udom,'primary'))) {
  941:             $uhome=&domain($udom,'primary');
  942:         } else {
  943:             undef($uhome);
  944:         }
  945:     } else {
  946:         if (!$uhome) {
  947:             if (defined(&domain($udom,'primary'))) {
  948:                 $uhome=&domain($udom,'primary');
  949:             }
  950:         }
  951:     }
  952:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  953:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  954:         my %returnhash;
  955:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  956:             return %returnhash;
  957:         }
  958:         my @pairs=split(/\&/,$rep);
  959:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  960:             return @pairs;
  961:         }
  962:         my $i=0;
  963:         foreach my $item (@$storearr) {
  964:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  965:             $i++;
  966:         }
  967:         return %returnhash;
  968:     } else {
  969:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  970:     }
  971: }
  972: 
  973: # -------------------------------------------- put items in domain db files 
  974: 
  975: sub put_dom {
  976:     my ($namespace,$storehash,$udom,$uhome)=@_;
  977:     if (!$udom) {
  978:         $udom=$env{'user.domain'};
  979:         if (defined(&domain($udom,'primary'))) {
  980:             $uhome=&domain($udom,'primary');
  981:         } else {
  982:             undef($uhome);
  983:         }
  984:     } else {
  985:         if (!$uhome) {
  986:             if (defined(&domain($udom,'primary'))) {
  987:                 $uhome=&domain($udom,'primary');
  988:             }
  989:         }
  990:     } 
  991:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  992:         my $items='';
  993:         foreach my $item (keys(%$storehash)) {
  994:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  995:         }
  996:         $items=~s/\&$//;
  997:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  998:     } else {
  999:         &logthis("put_dom failed - no homeserver and/or domain");
 1000:     }
 1001: }
 1002: 
 1003: sub retrieve_inst_usertypes {
 1004:     my ($udom) = @_;
 1005:     my (%returnhash,@order);
 1006:     if (defined(&domain($udom,'primary'))) {
 1007:         my $uhome=&domain($udom,'primary');
 1008:         my $rep=&reply("inst_usertypes:$udom",$uhome);
 1009:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1010:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1011:             return (\%returnhash,\@order);
 1012:         }
 1013:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1014:         my @pairs=split(/\&/,$hashitems);
 1015:         foreach my $item (@pairs) {
 1016:             my ($key,$value)=split(/=/,$item,2);
 1017:             $key = &unescape($key);
 1018:             next if ($key =~ /^error: 2 /);
 1019:             $returnhash{$key}=&thaw_unescape($value);
 1020:         }
 1021:         my @esc_order = split(/\&/,$orderitems);
 1022:         foreach my $item (@esc_order) {
 1023:             push(@order,&unescape($item));
 1024:         }
 1025:     } else {
 1026:         &logthis("get_dom failed - no primary domain server for $udom");
 1027:     }
 1028:     return (\%returnhash,\@order);
 1029: }
 1030: 
 1031: sub is_domainimage {
 1032:     my ($url) = @_;
 1033:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1034:         if (&domain($1) ne '') {
 1035:             return '1';
 1036:         }
 1037:     }
 1038:     return;
 1039: }
 1040: 
 1041: sub inst_directory_query {
 1042:     my ($srch) = @_;
 1043:     my $udom = $srch->{'srchdomain'};
 1044:     my %results;
 1045:     my $homeserver = &domain($udom,'primary');
 1046:     my $outcome;
 1047:     if ($homeserver ne '') {
 1048: 	my $queryid=&reply("querysend:instdirsearch:".
 1049: 			   &escape($srch->{'srchby'}).':'.
 1050: 			   &escape($srch->{'srchterm'}).':'.
 1051: 			   &escape($srch->{'srchtype'}),$homeserver);
 1052: 	my $host=&hostname($homeserver);
 1053: 	if ($queryid !~/^\Q$host\E\_/) {
 1054: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1055: 	    return;
 1056: 	}
 1057: 	my $response = &get_query_reply($queryid);
 1058: 	my $maxtries = 5;
 1059: 	my $tries = 1;
 1060: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1061: 	    $response = &get_query_reply($queryid);
 1062: 	    $tries ++;
 1063: 	}
 1064: 
 1065:         if (!&error($response) && $response ne 'refused') {
 1066:             if ($response eq 'unavailable') {
 1067:                 $outcome = $response;
 1068:             } else {
 1069:                 $outcome = 'ok';
 1070:                 my @matches = split(/\n/,$response);
 1071:                 foreach my $match (@matches) {
 1072:                     my ($key,$value) = split(/=/,$match);
 1073:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1074:                 }
 1075:             }
 1076:         }
 1077:     }
 1078:     return ($outcome,%results);
 1079: }
 1080: 
 1081: sub usersearch {
 1082:     my ($srch) = @_;
 1083:     my $dom = $srch->{'srchdomain'};
 1084:     my %results;
 1085:     my %libserv = &all_library();
 1086:     my $query = 'usersearch';
 1087:     foreach my $tryserver (keys(%libserv)) {
 1088:         if (&host_domain($tryserver) eq $dom) {
 1089:             my $host=&hostname($tryserver);
 1090:             my $queryid=
 1091:                 &reply("querysend:".&escape($query).':'.
 1092:                        &escape($srch->{'srchby'}).':'.
 1093:                        &escape($srch->{'srchtype'}).':'.
 1094:                        &escape($srch->{'srchterm'}),$tryserver);
 1095:             if ($queryid !~/^\Q$host\E\_/) {
 1096:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1097:                 next;
 1098:             }
 1099:             my $reply = &get_query_reply($queryid);
 1100:             my $maxtries = 1;
 1101:             my $tries = 1;
 1102:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1103:                 $reply = &get_query_reply($queryid);
 1104:                 $tries ++;
 1105:             }
 1106:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1107:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1108:             } else {
 1109:                 my @matches;
 1110:                 if ($reply =~ /\n/) {
 1111:                     @matches = split(/\n/,$reply);
 1112:                 } else {
 1113:                     @matches = split(/\&/,$reply);
 1114:                 }
 1115:                 foreach my $match (@matches) {
 1116:                     my ($uname,$udom,%userhash);
 1117:                     foreach my $entry (split(/:/,$match)) {
 1118:                         my ($key,$value) =
 1119:                             map {&unescape($_);} split(/=/,$entry);
 1120:                         $userhash{$key} = $value;
 1121:                         if ($key eq 'username') {
 1122:                             $uname = $value;
 1123:                         } elsif ($key eq 'domain') {
 1124:                             $udom = $value;
 1125:                         }
 1126:                     }
 1127:                     $results{$uname.':'.$udom} = \%userhash;
 1128:                 }
 1129:             }
 1130:         }
 1131:     }
 1132:     return %results;
 1133: }
 1134: 
 1135: sub get_instuser {
 1136:     my ($udom,$uname,$id) = @_;
 1137:     my $homeserver = &domain($udom,'primary');
 1138:     my ($outcome,%results);
 1139:     if ($homeserver ne '') {
 1140:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1141:                            &escape($id).':'.&escape($udom),$homeserver);
 1142:         my $host=&hostname($homeserver);
 1143:         if ($queryid !~/^\Q$host\E\_/) {
 1144:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1145:             return;
 1146:         }
 1147:         my $response = &get_query_reply($queryid);
 1148:         my $maxtries = 5;
 1149:         my $tries = 1;
 1150:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1151:             $response = &get_query_reply($queryid);
 1152:             $tries ++;
 1153:         }
 1154:         if (!&error($response) && $response ne 'refused') {
 1155:             if ($response eq 'unavailable') {
 1156:                 $outcome = $response;
 1157:             } else {
 1158:                 $outcome = 'ok';
 1159:                 my @matches = split(/\n/,$response);
 1160:                 foreach my $match (@matches) {
 1161:                     my ($key,$value) = split(/=/,$match);
 1162:                     $results{&unescape($key)} = &thaw_unescape($value);
 1163:                 }
 1164:             }
 1165:         }
 1166:     }
 1167:     my %userinfo;
 1168:     if (ref($results{$uname}) eq 'HASH') {
 1169:         %userinfo = %{$results{$uname}};
 1170:     } 
 1171:     return ($outcome,%userinfo);
 1172: }
 1173: 
 1174: sub inst_rulecheck {
 1175:     my ($udom,$uname,$id,$item,$rules) = @_;
 1176:     my %returnhash;
 1177:     if ($udom ne '') {
 1178:         if (ref($rules) eq 'ARRAY') {
 1179:             @{$rules} = map {&escape($_);} (@{$rules});
 1180:             my $rulestr = join(':',@{$rules});
 1181:             my $homeserver=&domain($udom,'primary');
 1182:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1183:                 my $response;
 1184:                 if ($item eq 'username') {                
 1185:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1186:                                               ':'.&escape($uname).':'.$rulestr,
 1187:                                               $homeserver));
 1188:                 } elsif ($item eq 'id') {
 1189:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1190:                                               ':'.&escape($id).':'.$rulestr,
 1191:                                               $homeserver));
 1192:                 } elsif ($item eq 'selfcreate') {
 1193:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1194:                                                &escape($udom).':'.&escape($uname).
 1195:                                               ':'.$rulestr,$homeserver));
 1196:                 }
 1197:                 if ($response ne 'refused') {
 1198:                     my @pairs=split(/\&/,$response);
 1199:                     foreach my $item (@pairs) {
 1200:                         my ($key,$value)=split(/=/,$item,2);
 1201:                         $key = &unescape($key);
 1202:                         next if ($key =~ /^error: 2 /);
 1203:                         $returnhash{$key}=&thaw_unescape($value);
 1204:                     }
 1205:                 }
 1206:             }
 1207:         }
 1208:     }
 1209:     return %returnhash;
 1210: }
 1211: 
 1212: sub inst_userrules {
 1213:     my ($udom,$check) = @_;
 1214:     my (%ruleshash,@ruleorder);
 1215:     if ($udom ne '') {
 1216:         my $homeserver=&domain($udom,'primary');
 1217:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1218:             my $response;
 1219:             if ($check eq 'id') {
 1220:                 $response=&reply('instidrules:'.&escape($udom),
 1221:                                  $homeserver);
 1222:             } elsif ($check eq 'email') {
 1223:                 $response=&reply('instemailrules:'.&escape($udom),
 1224:                                  $homeserver);
 1225:             } else {
 1226:                 $response=&reply('instuserrules:'.&escape($udom),
 1227:                                  $homeserver);
 1228:             }
 1229:             if (($response ne 'refused') && ($response ne 'error') && 
 1230:                 ($response ne 'unknown_cmd') && 
 1231:                 ($response ne 'no_such_host')) {
 1232:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1233:                 my @pairs=split(/\&/,$hashitems);
 1234:                 foreach my $item (@pairs) {
 1235:                     my ($key,$value)=split(/=/,$item,2);
 1236:                     $key = &unescape($key);
 1237:                     next if ($key =~ /^error: 2 /);
 1238:                     $ruleshash{$key}=&thaw_unescape($value);
 1239:                 }
 1240:                 my @esc_order = split(/\&/,$orderitems);
 1241:                 foreach my $item (@esc_order) {
 1242:                     push(@ruleorder,&unescape($item));
 1243:                 }
 1244:             }
 1245:         }
 1246:     }
 1247:     return (\%ruleshash,\@ruleorder);
 1248: }
 1249: 
 1250: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1251: 
 1252: sub get_domain_defaults {
 1253:     my ($domain) = @_;
 1254:     my $cachetime = 60*60*24;
 1255:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1256:     if (defined($cached)) {
 1257:         if (ref($result) eq 'HASH') {
 1258:             return %{$result};
 1259:         }
 1260:     }
 1261:     my %domdefaults;
 1262:     my %domconfig =
 1263:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1264:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1265:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1266:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1267:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1268:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1269:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1270:     } else {
 1271:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1272:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1273:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1274:     }
 1275:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1276:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1277:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1278:         } else {
 1279:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1280:         } 
 1281:         my @usertools = ('aboutme','blog','portfolio');
 1282:         foreach my $item (@usertools) {
 1283:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1284:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1285:             }
 1286:         }
 1287:     }
 1288:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1289:                                   $cachetime);
 1290:     return %domdefaults;
 1291: }
 1292: 
 1293: # --------------------------------------------------- Assign a key to a student
 1294: 
 1295: sub assign_access_key {
 1296: #
 1297: # a valid key looks like uname:udom#comments
 1298: # comments are being appended
 1299: #
 1300:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1301:     $kdom=
 1302:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1303:     $knum=
 1304:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1305:     $cdom=
 1306:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1307:     $cnum=
 1308:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1309:     $udom=$env{'user.name'} unless (defined($udom));
 1310:     $uname=$env{'user.domain'} unless (defined($uname));
 1311:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1312:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1313:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1314:                                                   # assigned to this person
 1315:                                                   # - this should not happen,
 1316:                                                   # unless something went wrong
 1317:                                                   # the first time around
 1318: # ready to assign
 1319:         $logentry=$1.'; '.$logentry;
 1320:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1321:                                                  $kdom,$knum) eq 'ok') {
 1322: # key now belongs to user
 1323: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1324:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1325:                 &appenv({'environment.'.$envkey => $ckey});
 1326:                 return 'ok';
 1327:             } else {
 1328:                 return 
 1329:   'error: Count not permanently assign key, will need to be re-entered later.';
 1330: 	    }
 1331:         } else {
 1332:             return 'error: Could not assign key, try again later.';
 1333:         }
 1334:     } elsif (!$existing{$ckey}) {
 1335: # the key does not exist
 1336: 	return 'error: The key does not exist';
 1337:     } else {
 1338: # the key is somebody else's
 1339: 	return 'error: The key is already in use';
 1340:     }
 1341: }
 1342: 
 1343: # ------------------------------------------ put an additional comment on a key
 1344: 
 1345: sub comment_access_key {
 1346: #
 1347: # a valid key looks like uname:udom#comments
 1348: # comments are being appended
 1349: #
 1350:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1351:     $cdom=
 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1353:     $cnum=
 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1355:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1356:     if ($existing{$ckey}) {
 1357:         $existing{$ckey}.='; '.$logentry;
 1358: # ready to assign
 1359:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1360:                                                  $cdom,$cnum) eq 'ok') {
 1361: 	    return 'ok';
 1362:         } else {
 1363: 	    return 'error: Count not store comment.';
 1364:         }
 1365:     } else {
 1366: # the key does not exist
 1367: 	return 'error: The key does not exist';
 1368:     }
 1369: }
 1370: 
 1371: # ------------------------------------------------------ Generate a set of keys
 1372: 
 1373: sub generate_access_keys {
 1374:     my ($number,$cdom,$cnum,$logentry)=@_;
 1375:     $cdom=
 1376:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1377:     $cnum=
 1378:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1379:     unless (&allowed('mky',$cdom)) { return 0; }
 1380:     unless (($cdom) && ($cnum)) { return 0; }
 1381:     if ($number>10000) { return 0; }
 1382:     sleep(2); # make sure don't get same seed twice
 1383:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1384:     my $total=0;
 1385:     for (my $i=1;$i<=$number;$i++) {
 1386:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1387:                   sprintf("%lx",int(100000*rand)).'-'.
 1388:                   sprintf("%lx",int(100000*rand));
 1389:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1390:        $newkey=~s/0/h/g; # and also 0 and O
 1391:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1392:        if ($existing{$newkey}) {
 1393:            $i--;
 1394:        } else {
 1395: 	  if (&put('accesskeys',
 1396:               { $newkey => '# generated '.localtime().
 1397:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1398:                            '; '.$logentry },
 1399: 		   $cdom,$cnum) eq 'ok') {
 1400:               $total++;
 1401: 	  }
 1402:        }
 1403:     }
 1404:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1405:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1406:     return $total;
 1407: }
 1408: 
 1409: # ------------------------------------------------------- Validate an accesskey
 1410: 
 1411: sub validate_access_key {
 1412:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1413:     $cdom=
 1414:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1415:     $cnum=
 1416:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1417:     $udom=$env{'user.domain'} unless (defined($udom));
 1418:     $uname=$env{'user.name'} unless (defined($uname));
 1419:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1420:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1421: }
 1422: 
 1423: # ------------------------------------- Find the section of student in a course
 1424: sub devalidate_getsection_cache {
 1425:     my ($udom,$unam,$courseid)=@_;
 1426:     my $hashid="$udom:$unam:$courseid";
 1427:     &devalidate_cache_new('getsection',$hashid);
 1428: }
 1429: 
 1430: sub courseid_to_courseurl {
 1431:     my ($courseid) = @_;
 1432:     #already url style courseid
 1433:     return $courseid if ($courseid =~ m{^/});
 1434: 
 1435:     if (exists($env{'course.'.$courseid.'.num'})) {
 1436: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1437: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1438: 	return "/$cdom/$cnum";
 1439:     }
 1440: 
 1441:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1442:     if (exists($courseinfo{'num'})) {
 1443: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1444:     }
 1445: 
 1446:     return undef;
 1447: }
 1448: 
 1449: sub getsection {
 1450:     my ($udom,$unam,$courseid)=@_;
 1451:     my $cachetime=1800;
 1452: 
 1453:     my $hashid="$udom:$unam:$courseid";
 1454:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1455:     if (defined($cached)) { return $result; }
 1456: 
 1457:     my %Pending; 
 1458:     my %Expired;
 1459:     #
 1460:     # Each role can either have not started yet (pending), be active, 
 1461:     #    or have expired.
 1462:     #
 1463:     # If there is an active role, we are done.
 1464:     #
 1465:     # If there is more than one role which has not started yet, 
 1466:     #     choose the one which will start sooner
 1467:     # If there is one role which has not started yet, return it.
 1468:     #
 1469:     # If there is more than one expired role, choose the one which ended last.
 1470:     # If there is a role which has expired, return it.
 1471:     #
 1472:     $courseid = &courseid_to_courseurl($courseid);
 1473:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1474:     foreach my $key (keys(%roleshash)) {
 1475:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1476:         my $section=$1;
 1477:         if ($key eq $courseid.'_st') { $section=''; }
 1478:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1479:         my $now=time;
 1480:         if (defined($end) && $end && ($now > $end)) {
 1481:             $Expired{$end}=$section;
 1482:             next;
 1483:         }
 1484:         if (defined($start) && $start && ($now < $start)) {
 1485:             $Pending{$start}=$section;
 1486:             next;
 1487:         }
 1488:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1489:     }
 1490:     #
 1491:     # Presumedly there will be few matching roles from the above
 1492:     # loop and the sorting time will be negligible.
 1493:     if (scalar(keys(%Pending))) {
 1494:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1495:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1496:     } 
 1497:     if (scalar(keys(%Expired))) {
 1498:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1499:         my $time = pop(@sorted);
 1500:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1501:     }
 1502:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1503: }
 1504: 
 1505: sub save_cache {
 1506:     &purge_remembered();
 1507:     #&Apache::loncommon::validate_page();
 1508:     undef(%env);
 1509:     undef($env_loaded);
 1510: }
 1511: 
 1512: my $to_remember=-1;
 1513: my %remembered;
 1514: my %accessed;
 1515: my $kicks=0;
 1516: my $hits=0;
 1517: sub make_key {
 1518:     my ($name,$id) = @_;
 1519:     if (length($id) > 65 
 1520: 	&& length(&escape($id)) > 200) {
 1521: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1522:     }
 1523:     return &escape($name.':'.$id);
 1524: }
 1525: 
 1526: sub devalidate_cache_new {
 1527:     my ($name,$id,$debug) = @_;
 1528:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1529:     $id=&make_key($name,$id);
 1530:     $memcache->delete($id);
 1531:     delete($remembered{$id});
 1532:     delete($accessed{$id});
 1533: }
 1534: 
 1535: sub is_cached_new {
 1536:     my ($name,$id,$debug) = @_;
 1537:     $id=&make_key($name,$id);
 1538:     if (exists($remembered{$id})) {
 1539: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1540: 	$accessed{$id}=[&gettimeofday()];
 1541: 	$hits++;
 1542: 	return ($remembered{$id},1);
 1543:     }
 1544:     my $value = $memcache->get($id);
 1545:     if (!(defined($value))) {
 1546: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1547: 	return (undef,undef);
 1548:     }
 1549:     if ($value eq '__undef__') {
 1550: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1551: 	$value=undef;
 1552:     }
 1553:     &make_room($id,$value,$debug);
 1554:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1555:     return ($value,1);
 1556: }
 1557: 
 1558: sub do_cache_new {
 1559:     my ($name,$id,$value,$time,$debug) = @_;
 1560:     $id=&make_key($name,$id);
 1561:     my $setvalue=$value;
 1562:     if (!defined($setvalue)) {
 1563: 	$setvalue='__undef__';
 1564:     }
 1565:     if (!defined($time) ) {
 1566: 	$time=600;
 1567:     }
 1568:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1569:     my $result = $memcache->set($id,$setvalue,$time);
 1570:     if (! $result) {
 1571: 	&logthis("caching of id -> $id  failed");
 1572: 	$memcache->disconnect_all();
 1573:     }
 1574:     # need to make a copy of $value
 1575:     &make_room($id,$value,$debug);
 1576:     return $value;
 1577: }
 1578: 
 1579: sub make_room {
 1580:     my ($id,$value,$debug)=@_;
 1581: 
 1582:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1583:                                     : $value;
 1584:     if ($to_remember<0) { return; }
 1585:     $accessed{$id}=[&gettimeofday()];
 1586:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1587:     my $to_kick;
 1588:     my $max_time=0;
 1589:     foreach my $other (keys(%accessed)) {
 1590: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1591: 	    $to_kick=$other;
 1592: 	    $max_time=&tv_interval($accessed{$other});
 1593: 	}
 1594:     }
 1595:     delete($remembered{$to_kick});
 1596:     delete($accessed{$to_kick});
 1597:     $kicks++;
 1598:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1599:     return;
 1600: }
 1601: 
 1602: sub purge_remembered {
 1603:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1604:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1605:     undef(%remembered);
 1606:     undef(%accessed);
 1607: }
 1608: # ------------------------------------- Read an entry from a user's environment
 1609: 
 1610: sub userenvironment {
 1611:     my ($udom,$unam,@what)=@_;
 1612:     my $items;
 1613:     foreach my $item (@what) {
 1614:         $items.=&escape($item).'&';
 1615:     }
 1616:     $items=~s/\&$//;
 1617:     my %returnhash=();
 1618:     my @answer=split(/\&/,
 1619:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1620:                       &homeserver($unam,$udom)));
 1621:     my $i;
 1622:     for ($i=0;$i<=$#what;$i++) {
 1623: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1624:     }
 1625:     return %returnhash;
 1626: }
 1627: 
 1628: # ---------------------------------------------------------- Get a studentphoto
 1629: sub studentphoto {
 1630:     my ($udom,$unam,$ext) = @_;
 1631:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1632:     if (defined($env{'request.course.id'})) {
 1633:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1634:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1635:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1636:             } else {
 1637:                 my ($result,$perm_reqd)=
 1638: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1639:                 if ($result eq 'ok') {
 1640:                     if (!($perm_reqd eq 'yes')) {
 1641:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1642:                     }
 1643:                 }
 1644:             }
 1645:         }
 1646:     } else {
 1647:         my ($result,$perm_reqd) = 
 1648: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1649:         if ($result eq 'ok') {
 1650:             if (!($perm_reqd eq 'yes')) {
 1651:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1652:             }
 1653:         }
 1654:     }
 1655:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1656: }
 1657: 
 1658: sub retrievestudentphoto {
 1659:     my ($udom,$unam,$ext,$type) = @_;
 1660:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1661:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1662:     if ($ret eq 'ok') {
 1663:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1664:         if ($type eq 'thumbnail') {
 1665:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1666:         }
 1667:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1668:         return $tokenurl;
 1669:     } else {
 1670:         if ($type eq 'thumbnail') {
 1671:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1672:         } else { 
 1673:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1674:         }
 1675:     }
 1676: }
 1677: 
 1678: # -------------------------------------------------------------------- New chat
 1679: 
 1680: sub chatsend {
 1681:     my ($newentry,$anon,$group)=@_;
 1682:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1683:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1684:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1685:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1686: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1687: 		   &escape($newentry)).':'.$group,$chome);
 1688: }
 1689: 
 1690: # ------------------------------------------ Find current version of a resource
 1691: 
 1692: sub getversion {
 1693:     my $fname=&clutter(shift);
 1694:     unless ($fname=~/^\/res\//) { return -1; }
 1695:     return &currentversion(&filelocation('',$fname));
 1696: }
 1697: 
 1698: sub currentversion {
 1699:     my $fname=shift;
 1700:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1701:     if (defined($cached)) { return $result; }
 1702:     my $author=$fname;
 1703:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1704:     my ($udom,$uname)=split(/\//,$author);
 1705:     my $home=homeserver($uname,$udom);
 1706:     if ($home eq 'no_host') { 
 1707:         return -1; 
 1708:     }
 1709:     my $answer=reply("currentversion:$fname",$home);
 1710:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1711: 	return -1;
 1712:     }
 1713:     return &do_cache_new('resversion',$fname,$answer,600);
 1714: }
 1715: 
 1716: # ----------------------------- Subscribe to a resource, return URL if possible
 1717: 
 1718: sub subscribe {
 1719:     my $fname=shift;
 1720:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1721:     $fname=~s/[\n\r]//g;
 1722:     my $author=$fname;
 1723:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1724:     my ($udom,$uname)=split(/\//,$author);
 1725:     my $home=homeserver($uname,$udom);
 1726:     if ($home eq 'no_host') {
 1727:         return 'not_found';
 1728:     }
 1729:     my $answer=reply("sub:$fname",$home);
 1730:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1731: 	$answer.=' by '.$home;
 1732:     }
 1733:     return $answer;
 1734: }
 1735:     
 1736: # -------------------------------------------------------------- Replicate file
 1737: 
 1738: sub repcopy {
 1739:     my $filename=shift;
 1740:     $filename=~s/\/+/\//g;
 1741:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1742:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1743:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1744: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1745: 	return &repcopy_userfile($filename);
 1746:     }
 1747:     $filename=~s/[\n\r]//g;
 1748:     my $transname="$filename.in.transfer";
 1749: # FIXME: this should flock
 1750:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1751:     my $remoteurl=subscribe($filename);
 1752:     if ($remoteurl =~ /^con_lost by/) {
 1753: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1754:            return 'unavailable';
 1755:     } elsif ($remoteurl eq 'not_found') {
 1756: 	   #&logthis("Subscribe returned not_found: $filename");
 1757: 	   return 'not_found';
 1758:     } elsif ($remoteurl =~ /^rejected by/) {
 1759: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1760:            return 'forbidden';
 1761:     } elsif ($remoteurl eq 'directory') {
 1762:            return 'ok';
 1763:     } else {
 1764:         my $author=$filename;
 1765:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1766:         my ($udom,$uname)=split(/\//,$author);
 1767:         my $home=homeserver($uname,$udom);
 1768:         unless ($home eq $perlvar{'lonHostID'}) {
 1769:            my @parts=split(/\//,$filename);
 1770:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1771:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1772:                &logthis("Malconfiguration for replication: $filename");
 1773: 	       return 'bad_request';
 1774:            }
 1775:            my $count;
 1776:            for ($count=5;$count<$#parts;$count++) {
 1777:                $path.="/$parts[$count]";
 1778:                if ((-e $path)!=1) {
 1779: 		   mkdir($path,0777);
 1780:                }
 1781:            }
 1782:            my $ua=new LWP::UserAgent;
 1783:            my $request=new HTTP::Request('GET',"$remoteurl");
 1784:            my $response=$ua->request($request,$transname);
 1785:            if ($response->is_error()) {
 1786: 	       unlink($transname);
 1787:                my $message=$response->status_line;
 1788:                &logthis("<font color=\"blue\">WARNING:"
 1789:                        ." LWP get: $message: $filename</font>");
 1790:                return 'unavailable';
 1791:            } else {
 1792: 	       if ($remoteurl!~/\.meta$/) {
 1793:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1794:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1795:                   if ($mresponse->is_error()) {
 1796: 		      unlink($filename.'.meta');
 1797:                       &logthis(
 1798:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1799:                   }
 1800: 	       }
 1801:                rename($transname,$filename);
 1802:                return 'ok';
 1803:            }
 1804:        }
 1805:     }
 1806: }
 1807: 
 1808: # ------------------------------------------------ Get server side include body
 1809: sub ssi_body {
 1810:     my ($filelink,%form)=@_;
 1811:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1812:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1813:     }
 1814:     my $output='';
 1815:     my $response;
 1816:     if ($filelink=~/^https?\:/) {
 1817:        ($output,$response)=&externalssi($filelink);
 1818:     } else {
 1819:        ($output,$response)=&ssi($filelink,%form);
 1820:     }
 1821:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1822:     $output=~s/^.*?\<body[^\>]*\>//si;
 1823:     $output=~s/\<\/body\s*\>.*?$//si;
 1824:     if (wantarray) {
 1825:         return ($output, $response);
 1826:     } else {
 1827:         return $output;
 1828:     }
 1829: }
 1830: 
 1831: # --------------------------------------------------------- Server Side Include
 1832: 
 1833: sub absolute_url {
 1834:     my ($host_name) = @_;
 1835:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1836:     if ($host_name eq '') {
 1837: 	$host_name = $ENV{'SERVER_NAME'};
 1838:     }
 1839:     return $protocol.$host_name;
 1840: }
 1841: 
 1842: #
 1843: #   Server side include.
 1844: # Parameters:
 1845: #  fn     Possibly encrypted resource name/id.
 1846: #  form   Hash that describes how the rendering should be done
 1847: #         and other things.
 1848: # Returns:
 1849: #   Scalar context: The content of the response.
 1850: #   Array context:  2 element list of the content and the full response object.
 1851: #     
 1852: sub ssi {
 1853: 
 1854:     my ($fn,%form)=@_;
 1855:     my $ua=new LWP::UserAgent;
 1856:     my $request;
 1857: 
 1858:     $form{'no_update_last_known'}=1;
 1859:     &Apache::lonenc::check_encrypt(\$fn);
 1860:     if (%form) {
 1861:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1862:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1863:     } else {
 1864:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1865:     }
 1866: 
 1867:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1868:     my $response=$ua->request($request);
 1869: 
 1870:     if (wantarray) {
 1871: 	return ($response->content, $response);
 1872:     } else {
 1873: 	return $response->content;
 1874:     }
 1875: }
 1876: 
 1877: sub externalssi {
 1878:     my ($url)=@_;
 1879:     my $ua=new LWP::UserAgent;
 1880:     my $request=new HTTP::Request('GET',$url);
 1881:     my $response=$ua->request($request);
 1882:     if (wantarray) {
 1883:         return ($response->content, $response);
 1884:     } else {
 1885:         return $response->content;
 1886:     }
 1887: }
 1888: 
 1889: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1890: 
 1891: sub allowuploaded {
 1892:     my ($srcurl,$url)=@_;
 1893:     $url=&clutter(&declutter($url));
 1894:     my $dir=$url;
 1895:     $dir=~s/\/[^\/]+$//;
 1896:     my %httpref=();
 1897:     my $httpurl=&hreflocation('',$url);
 1898:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1899:     &Apache::lonnet::appenv(\%httpref);
 1900: }
 1901: 
 1902: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1903: # input: action, courseID, current domain, intended
 1904: #        path to file, source of file, instruction to parse file for objects,
 1905: #        ref to hash for embedded objects,
 1906: #        ref to hash for codebase of java objects.
 1907: #
 1908: # output: url to file (if action was uploaddoc), 
 1909: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1910: #
 1911: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1912: # course.
 1913: #
 1914: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1915: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1916: #          course's home server.
 1917: #
 1918: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1919: #          be copied from $source (current location) to 
 1920: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1921: #         and will then be copied to
 1922: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1923: #         course's home server.
 1924: #
 1925: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1926: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1927: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1928: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1929: #         in course's home server.
 1930: #
 1931: 
 1932: sub process_coursefile {
 1933:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1934:     my $fetchresult;
 1935:     my $home=&homeserver($docuname,$docudom);
 1936:     if ($action eq 'propagate') {
 1937:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1938: 			     $home);
 1939:     } else {
 1940:         my $fpath = '';
 1941:         my $fname = $file;
 1942:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1943:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1944:         my $filepath = &build_filepath($fpath);
 1945:         if ($action eq 'copy') {
 1946:             if ($source eq '') {
 1947:                 $fetchresult = 'no source file';
 1948:                 return $fetchresult;
 1949:             } else {
 1950:                 my $destination = $filepath.'/'.$fname;
 1951:                 rename($source,$destination);
 1952:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1953:                                  $home);
 1954:             }
 1955:         } elsif ($action eq 'uploaddoc') {
 1956:             open(my $fh,'>'.$filepath.'/'.$fname);
 1957:             print $fh $env{'form.'.$source};
 1958:             close($fh);
 1959:             if ($parser eq 'parse') {
 1960:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1961:                 unless ($parse_result eq 'ok') {
 1962:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1963:                 }
 1964:             }
 1965:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1966:                                  $home);
 1967:             if ($fetchresult eq 'ok') {
 1968:                 return '/uploaded/'.$fpath.'/'.$fname;
 1969:             } else {
 1970:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1971:                         ' to host '.$home.': '.$fetchresult);
 1972:                 return '/adm/notfound.html';
 1973:             }
 1974:         }
 1975:     }
 1976:     unless ( $fetchresult eq 'ok') {
 1977:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1978:              ' to host '.$home.': '.$fetchresult);
 1979:     }
 1980:     return $fetchresult;
 1981: }
 1982: 
 1983: sub build_filepath {
 1984:     my ($fpath) = @_;
 1985:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1986:     unless ($fpath eq '') {
 1987:         my @parts=split('/',$fpath);
 1988:         foreach my $part (@parts) {
 1989:             $filepath.= '/'.$part;
 1990:             if ((-e $filepath)!=1) {
 1991:                 mkdir($filepath,0777);
 1992:             }
 1993:         }
 1994:     }
 1995:     return $filepath;
 1996: }
 1997: 
 1998: sub store_edited_file {
 1999:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2000:     my $file = $primary_url;
 2001:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2002:     my $fpath = '';
 2003:     my $fname = $file;
 2004:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2005:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2006:     my $filepath = &build_filepath($fpath);
 2007:     open(my $fh,'>'.$filepath.'/'.$fname);
 2008:     print $fh $content;
 2009:     close($fh);
 2010:     my $home=&homeserver($docuname,$docudom);
 2011:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2012: 			  $home);
 2013:     if ($$fetchresult eq 'ok') {
 2014:         return '/uploaded/'.$fpath.'/'.$fname;
 2015:     } else {
 2016:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2017: 		 ' to host '.$home.': '.$$fetchresult);
 2018:         return '/adm/notfound.html';
 2019:     }
 2020: }
 2021: 
 2022: sub clean_filename {
 2023:     my ($fname,$args)=@_;
 2024: # Replace Windows backslashes by forward slashes
 2025:     $fname=~s/\\/\//g;
 2026:     if (!$args->{'keep_path'}) {
 2027:         # Get rid of everything but the actual filename
 2028: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2029:     }
 2030: # Replace spaces by underscores
 2031:     $fname=~s/\s+/\_/g;
 2032: # Replace all other weird characters by nothing
 2033:     $fname=~s{[^/\w\.\-]}{}g;
 2034: # Replace all .\d. sequences with _\d. so they no longer look like version
 2035: # numbers
 2036:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2037:     return $fname;
 2038: }
 2039: 
 2040: # --------------- Take an uploaded file and put it into the userfiles directory
 2041: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2042: #                    the desired filenam is in $env{"form.$formname.filename"}
 2043: #        $coursedoc - if true up to the current course
 2044: #                     if false
 2045: #        $subdir - directory in userfile to store the file into
 2046: #        $parser - instruction to parse file for objects ($parser = parse)    
 2047: #        $allfiles - reference to hash for embedded objects
 2048: #        $codebase - reference to hash for codebase of java objects
 2049: #        $desuname - username for permanent storage of uploaded file
 2050: #        $dsetudom - domain for permanaent storage of uploaded file
 2051: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2052: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2053: # 
 2054: # output: url of file in userspace, or error: <message> 
 2055: #             or /adm/notfound.html if failure to upload occurse
 2056: 
 2057: 
 2058: sub userfileupload {
 2059:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2060:         $destudom,$thumbwidth,$thumbheight)=@_;
 2061:     if (!defined($subdir)) { $subdir='unknown'; }
 2062:     my $fname=$env{'form.'.$formname.'.filename'};
 2063:     $fname=&clean_filename($fname);
 2064: # See if there is anything left
 2065:     unless ($fname) { return 'error: no uploaded file'; }
 2066:     chop($env{'form.'.$formname});
 2067:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2068:         my $now = time;
 2069:         my $filepath = 'tmp/helprequests/'.$now;
 2070:         my @parts=split(/\//,$filepath);
 2071:         my $fullpath = $perlvar{'lonDaemons'};
 2072:         for (my $i=0;$i<@parts;$i++) {
 2073:             $fullpath .= '/'.$parts[$i];
 2074:             if ((-e $fullpath)!=1) {
 2075:                 mkdir($fullpath,0777);
 2076:             }
 2077:         }
 2078:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2079:         print $fh $env{'form.'.$formname};
 2080:         close($fh);
 2081:         return $fullpath.'/'.$fname;
 2082:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2083:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2084:                        '_'.$env{'user.domain'}.'/pending';
 2085:         my @parts=split(/\//,$filepath);
 2086:         my $fullpath = $perlvar{'lonDaemons'};
 2087:         for (my $i=0;$i<@parts;$i++) {
 2088:             $fullpath .= '/'.$parts[$i];
 2089:             if ((-e $fullpath)!=1) {
 2090:                 mkdir($fullpath,0777);
 2091:             }
 2092:         }
 2093:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2094:         print $fh $env{'form.'.$formname};
 2095:         close($fh);
 2096:         return $fullpath.'/'.$fname;
 2097:     }
 2098:     
 2099: # Create the directory if not present
 2100:     $fname="$subdir/$fname";
 2101:     if ($coursedoc) {
 2102: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2103: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2104:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2105:             return &finishuserfileupload($docuname,$docudom,
 2106: 					 $formname,$fname,$parser,$allfiles,
 2107: 					 $codebase,$thumbwidth,$thumbheight);
 2108:         } else {
 2109:             $fname=$env{'form.folder'}.'/'.$fname;
 2110:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2111: 				       $fname,$formname,$parser,
 2112: 				       $allfiles,$codebase);
 2113:         }
 2114:     } elsif (defined($destuname)) {
 2115:         my $docuname=$destuname;
 2116:         my $docudom=$destudom;
 2117: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2118: 				     $parser,$allfiles,$codebase,
 2119:                                      $thumbwidth,$thumbheight);
 2120:         
 2121:     } else {
 2122:         my $docuname=$env{'user.name'};
 2123:         my $docudom=$env{'user.domain'};
 2124:         if (exists($env{'form.group'})) {
 2125:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2126:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2127:         }
 2128: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2129: 				     $parser,$allfiles,$codebase,
 2130:                                      $thumbwidth,$thumbheight);
 2131:     }
 2132: }
 2133: 
 2134: sub finishuserfileupload {
 2135:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2136:         $thumbwidth,$thumbheight) = @_;
 2137:     my $path=$docudom.'/'.$docuname.'/';
 2138:     my $filepath=$perlvar{'lonDocRoot'};
 2139:     my ($fnamepath,$file,$fetchthumb);
 2140:     $file=$fname;
 2141:     if ($fname=~m|/|) {
 2142:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2143: 	$path.=$fnamepath.'/';
 2144:     }
 2145:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2146:     my $count;
 2147:     for ($count=4;$count<=$#parts;$count++) {
 2148:         $filepath.="/$parts[$count]";
 2149:         if ((-e $filepath)!=1) {
 2150: 	    mkdir($filepath,0777);
 2151:         }
 2152:     }
 2153: # Save the file
 2154:     {
 2155: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2156: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2157: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2158: 	    return '/adm/notfound.html';
 2159: 	}
 2160: 	if (!print FH ($env{'form.'.$formname})) {
 2161: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2162: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2163: 	    return '/adm/notfound.html';
 2164: 	}
 2165: 	close(FH);
 2166:     }
 2167:     if ($parser eq 'parse') {
 2168:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2169: 						   $codebase);
 2170:         unless ($parse_result eq 'ok') {
 2171:             &logthis('Failed to parse '.$filepath.$file.
 2172: 		     ' for embedded media: '.$parse_result); 
 2173:         }
 2174:     }
 2175:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2176:         my $input = $filepath.'/'.$file;
 2177:         my $output = $filepath.'/'.'tn-'.$file;
 2178:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2179:         system("convert -sample $thumbsize $input $output");
 2180:         if (-e $filepath.'/'.'tn-'.$file) {
 2181:             $fetchthumb  = 1; 
 2182:         }
 2183:     }
 2184:  
 2185: # Notify homeserver to grep it
 2186: #
 2187:     my $docuhome=&homeserver($docuname,$docudom);
 2188:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2189:     if ($fetchresult eq 'ok') {
 2190:         if ($fetchthumb) {
 2191:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2192:             if ($thumbresult ne 'ok') {
 2193:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2194:                          $docuhome.': '.$thumbresult);
 2195:             }
 2196:         }
 2197: #
 2198: # Return the URL to it
 2199:         return '/uploaded/'.$path.$file;
 2200:     } else {
 2201:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2202: 		 ': '.$fetchresult);
 2203:         return '/adm/notfound.html';
 2204:     }
 2205: }
 2206: 
 2207: sub extract_embedded_items {
 2208:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2209:     my @state = ();
 2210:     my %javafiles = (
 2211:                       codebase => '',
 2212:                       code => '',
 2213:                       archive => ''
 2214:                     );
 2215:     my %mediafiles = (
 2216:                       src => '',
 2217:                       movie => '',
 2218:                      );
 2219:     my $p;
 2220:     if ($content) {
 2221:         $p = HTML::LCParser->new($content);
 2222:     } else {
 2223:         $p = HTML::LCParser->new($fullpath);
 2224:     }
 2225:     while (my $t=$p->get_token()) {
 2226: 	if ($t->[0] eq 'S') {
 2227: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2228: 	    push(@state, $tagname);
 2229:             if (lc($tagname) eq 'allow') {
 2230:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2231:             }
 2232: 	    if (lc($tagname) eq 'img') {
 2233: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2234: 	    }
 2235: 	    if (lc($tagname) eq 'a') {
 2236: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2237: 	    }
 2238:             if (lc($tagname) eq 'script') {
 2239:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2240:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2241:                 } else {
 2242:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2243:                 }
 2244:             }
 2245:             if (lc($tagname) eq 'link') {
 2246:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2247:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2248:                 }
 2249:             }
 2250: 	    if (lc($tagname) eq 'object' ||
 2251: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2252: 		foreach my $item (keys(%javafiles)) {
 2253: 		    $javafiles{$item} = '';
 2254: 		}
 2255: 	    }
 2256: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2257: 		my $name = lc($attr->{'name'});
 2258: 		foreach my $item (keys(%javafiles)) {
 2259: 		    if ($name eq $item) {
 2260: 			$javafiles{$item} = $attr->{'value'};
 2261: 			last;
 2262: 		    }
 2263: 		}
 2264: 		foreach my $item (keys(%mediafiles)) {
 2265: 		    if ($name eq $item) {
 2266: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2267: 			last;
 2268: 		    }
 2269: 		}
 2270: 	    }
 2271: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2272: 		foreach my $item (keys(%javafiles)) {
 2273: 		    if ($attr->{$item}) {
 2274: 			$javafiles{$item} = $attr->{$item};
 2275: 			last;
 2276: 		    }
 2277: 		}
 2278: 		foreach my $item (keys(%mediafiles)) {
 2279: 		    if ($attr->{$item}) {
 2280: 			&add_filetype($allfiles,$attr->{$item},$item);
 2281: 			last;
 2282: 		    }
 2283: 		}
 2284: 	    }
 2285: 	} elsif ($t->[0] eq 'E') {
 2286: 	    my ($tagname) = ($t->[1]);
 2287: 	    if ($javafiles{'codebase'} ne '') {
 2288: 		$javafiles{'codebase'} .= '/';
 2289: 	    }  
 2290: 	    if (lc($tagname) eq 'applet' ||
 2291: 		lc($tagname) eq 'object' ||
 2292: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2293: 		) {
 2294: 		foreach my $item (keys(%javafiles)) {
 2295: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2296: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2297: 			&add_filetype($allfiles,$file,$item);
 2298: 		    }
 2299: 		}
 2300: 	    } 
 2301: 	    pop @state;
 2302: 	}
 2303:     }
 2304:     return 'ok';
 2305: }
 2306: 
 2307: sub add_filetype {
 2308:     my ($allfiles,$file,$type)=@_;
 2309:     if (exists($allfiles->{$file})) {
 2310: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2311: 	    push(@{$allfiles->{$file}}, &escape($type));
 2312: 	}
 2313:     } else {
 2314: 	@{$allfiles->{$file}} = (&escape($type));
 2315:     }
 2316: }
 2317: 
 2318: sub removeuploadedurl {
 2319:     my ($url)=@_;
 2320:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2321:     return &removeuserfile($uname,$udom,$fname);
 2322: }
 2323: 
 2324: sub removeuserfile {
 2325:     my ($docuname,$docudom,$fname)=@_;
 2326:     my $home=&homeserver($docuname,$docudom);
 2327:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2328:     if ($result eq 'ok') {
 2329:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2330:             my $metafile = $fname.'.meta';
 2331:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2332: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2333:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2334:             my $sqlresult = 
 2335:                 &update_portfolio_table($docuname,$docudom,$file,
 2336:                                         'portfolio_metadata',$group,
 2337:                                         'delete');
 2338:         }
 2339:     }
 2340:     return $result;
 2341: }
 2342: 
 2343: sub mkdiruserfile {
 2344:     my ($docuname,$docudom,$dir)=@_;
 2345:     my $home=&homeserver($docuname,$docudom);
 2346:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2347: }
 2348: 
 2349: sub renameuserfile {
 2350:     my ($docuname,$docudom,$old,$new)=@_;
 2351:     my $home=&homeserver($docuname,$docudom);
 2352:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2353:                         &escape("$old").':'.&escape("$new"),$home);
 2354:     if ($result eq 'ok') {
 2355:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2356:             my $oldmeta = $old.'.meta';
 2357:             my $newmeta = $new.'.meta';
 2358:             my $metaresult = 
 2359:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2360: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2361:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2362:             my $sqlresult = 
 2363:                 &update_portfolio_table($docuname,$docudom,$file,
 2364:                                         'portfolio_metadata',$group,
 2365:                                         'delete');
 2366:         }
 2367:     }
 2368:     return $result;
 2369: }
 2370: 
 2371: # ------------------------------------------------------------------------- Log
 2372: 
 2373: sub log {
 2374:     my ($dom,$nam,$hom,$what)=@_;
 2375:     return critical("log:$dom:$nam:$what",$hom);
 2376: }
 2377: 
 2378: # ------------------------------------------------------------------ Course Log
 2379: #
 2380: # This routine flushes several buffers of non-mission-critical nature
 2381: #
 2382: 
 2383: sub flushcourselogs {
 2384:     &logthis('Flushing log buffers');
 2385: #
 2386: # course logs
 2387: # This is a log of all transactions in a course, which can be used
 2388: # for data mining purposes
 2389: #
 2390: # It also collects the courseid database, which lists last transaction
 2391: # times and course titles for all courseids
 2392: #
 2393:     my %courseidbuffer=();
 2394:     foreach my $crsid (keys(%courselogs)) {
 2395:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2396: 		          &escape($courselogs{$crsid}),
 2397: 		          $coursehombuf{$crsid}) eq 'ok') {
 2398: 	    delete $courselogs{$crsid};
 2399:         } else {
 2400:             &logthis('Failed to flush log buffer for '.$crsid);
 2401:             if (length($courselogs{$crsid})>40000) {
 2402:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2403:                         " exceeded maximum size, deleting.</font>");
 2404:                delete $courselogs{$crsid};
 2405:             }
 2406:         }
 2407:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2408:             'description' => $coursedescrbuf{$crsid},
 2409:             'inst_code'    => $courseinstcodebuf{$crsid},
 2410:             'type'        => $coursetypebuf{$crsid},
 2411:             'owner'       => $courseownerbuf{$crsid},
 2412:         };
 2413:     }
 2414: #
 2415: # Write course id database (reverse lookup) to homeserver of courses 
 2416: # Is used in pickcourse
 2417: #
 2418:     foreach my $crs_home (keys(%courseidbuffer)) {
 2419:         my $response = &courseidput(&host_domain($crs_home),
 2420:                                     $courseidbuffer{$crs_home},
 2421:                                     $crs_home,'timeonly');
 2422:     }
 2423: #
 2424: # File accesses
 2425: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2426: #
 2427:     foreach my $entry (keys(%accesshash)) {
 2428:         if ($entry =~ /___count$/) {
 2429:             my ($dom,$name);
 2430:             ($dom,$name,undef)=
 2431: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2432:             if (! defined($dom) || $dom eq '' || 
 2433:                 ! defined($name) || $name eq '') {
 2434:                 my $cid = $env{'request.course.id'};
 2435:                 $dom  = $env{'request.'.$cid.'.domain'};
 2436:                 $name = $env{'request.'.$cid.'.num'};
 2437:             }
 2438:             my $value = $accesshash{$entry};
 2439:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2440:             my %temphash=($url => $value);
 2441:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2442:             if ($result eq 'ok') {
 2443:                 delete $accesshash{$entry};
 2444:             } elsif ($result eq 'unknown_cmd') {
 2445:                 # Target server has old code running on it.
 2446:                 my %temphash=($entry => $value);
 2447:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2448:                     delete $accesshash{$entry};
 2449:                 }
 2450:             }
 2451:         } else {
 2452:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2453:             my %temphash=($entry => $accesshash{$entry});
 2454:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2455:                 delete $accesshash{$entry};
 2456:             }
 2457:         }
 2458:     }
 2459: #
 2460: # Roles
 2461: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2462: #
 2463:     foreach my $entry (keys(%userrolehash)) {
 2464:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2465: 	    split(/\:/,$entry);
 2466:         if (&Apache::lonnet::put('nohist_userroles',
 2467:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2468:                 $rudom,$runame) eq 'ok') {
 2469: 	    delete $userrolehash{$entry};
 2470:         }
 2471:     }
 2472: #
 2473: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2474: #
 2475:     my %domrolebuffer = ();
 2476:     foreach my $entry (keys %domainrolehash) {
 2477:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2478:         if ($domrolebuffer{$rudom}) {
 2479:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2480:                       '='.&escape($domainrolehash{$entry});
 2481:         } else {
 2482:             $domrolebuffer{$rudom}.=&escape($entry).
 2483:                       '='.&escape($domainrolehash{$entry});
 2484:         }
 2485:         delete $domainrolehash{$entry};
 2486:     }
 2487:     foreach my $dom (keys(%domrolebuffer)) {
 2488: 	my %servers = &get_servers($dom,'library');
 2489: 	foreach my $tryserver (keys(%servers)) {
 2490: 	    unless (&reply('domroleput:'.$dom.':'.
 2491: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2492: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2493: 	    }
 2494:         }
 2495:     }
 2496:     $dumpcount++;
 2497: }
 2498: 
 2499: sub courselog {
 2500:     my $what=shift;
 2501:     $what=time.':'.$what;
 2502:     unless ($env{'request.course.id'}) { return ''; }
 2503:     $coursedombuf{$env{'request.course.id'}}=
 2504:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2505:     $coursenumbuf{$env{'request.course.id'}}=
 2506:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2507:     $coursehombuf{$env{'request.course.id'}}=
 2508:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2509:     $coursedescrbuf{$env{'request.course.id'}}=
 2510:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2511:     $courseinstcodebuf{$env{'request.course.id'}}=
 2512:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2513:     $courseownerbuf{$env{'request.course.id'}}=
 2514:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2515:     $coursetypebuf{$env{'request.course.id'}}=
 2516:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2517:     if (defined $courselogs{$env{'request.course.id'}}) {
 2518: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2519:     } else {
 2520: 	$courselogs{$env{'request.course.id'}}.=$what;
 2521:     }
 2522:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2523: 	&flushcourselogs();
 2524:     }
 2525: }
 2526: 
 2527: sub courseacclog {
 2528:     my $fnsymb=shift;
 2529:     unless ($env{'request.course.id'}) { return ''; }
 2530:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2531:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2532:         $what.=':POST';
 2533:         # FIXME: Probably ought to escape things....
 2534: 	foreach my $key (keys(%env)) {
 2535:             if ($key=~/^form\.(.*)/) {
 2536:                 my $formitem = $1;
 2537:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2538:                     $what.=':'.$formitem.'='.$env{$key};
 2539:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2540:                     $what.=':'.$formitem.'='.$env{$key};
 2541:                 }
 2542:             }
 2543:         }
 2544:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2545:         # FIXME: We should not be depending on a form parameter that someone
 2546:         # editing lonsearchcat.pm might change in the future.
 2547:         if ($env{'form.phase'} eq 'course_search') {
 2548:             $what.= ':POST';
 2549:             # FIXME: Probably ought to escape things....
 2550:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2551:                                  'crsdiscuss') {
 2552:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2553:             }
 2554:         }
 2555:     }
 2556:     &courselog($what);
 2557: }
 2558: 
 2559: sub countacc {
 2560:     my $url=&declutter(shift);
 2561:     return if (! defined($url) || $url eq '');
 2562:     unless ($env{'request.course.id'}) { return ''; }
 2563:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2564:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2565:     $accesshash{$key}++;
 2566: }
 2567: 
 2568: sub linklog {
 2569:     my ($from,$to)=@_;
 2570:     $from=&declutter($from);
 2571:     $to=&declutter($to);
 2572:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2573:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2574: }
 2575:   
 2576: sub userrolelog {
 2577:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2578:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2579:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2580:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2581:         ($trole=~/^ta/)) {
 2582:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2583:        $userrolehash
 2584:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2585:                     =$tend.':'.$tstart;
 2586:     }
 2587:     if (($env{'request.role'} =~ /dc\./) &&
 2588: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2589: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2590: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2591:        $userrolehash
 2592:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2593:                     =$tend.':'.$tstart;
 2594:     }
 2595:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2596:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2597:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2598:         ($trole=~/^sc/)) {
 2599:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2600:        $domainrolehash
 2601:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2602:                     = $tend.':'.$tstart;
 2603:     }
 2604: }
 2605: 
 2606: sub courserolelog {
 2607:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2608:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2609:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2610:         ($trole eq 'ta') || ($trole eq 'st') ||
 2611:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2612:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2613:             my $cdom = $1;
 2614:             my $cnum = $2;
 2615:             my $sec = $3;
 2616:             my $namespace = 'rolelog';
 2617:             my %storehash = (
 2618:                                role    => $trole,
 2619:                                start   => $tstart,
 2620:                                end     => $tend,
 2621:                                selfenroll => $selfenroll,
 2622:                                context    => $context,
 2623:                             );
 2624:             if ($trole eq 'gr') {
 2625:                 $namespace = 'groupslog';
 2626:                 $storehash{'group'} = $sec;
 2627:             } else {
 2628:                 $storehash{'section'} = $sec;
 2629:             }
 2630:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2631:             if (($trole ne 'st') || ($sec ne '')) {
 2632:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2633:             }
 2634:         }
 2635:     }
 2636:     return;
 2637: }
 2638: 
 2639: sub get_course_adv_roles {
 2640:     my ($cid,$codes) = @_;
 2641:     $cid=$env{'request.course.id'} unless (defined($cid));
 2642:     my %coursehash=&coursedescription($cid);
 2643:     my %nothide=();
 2644:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2645:         if ($user !~ /:/) {
 2646: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2647:         } else {
 2648:             $nothide{$user}=1;
 2649:         }
 2650:     }
 2651:     my %returnhash=();
 2652:     my %dumphash=
 2653:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2654:     my $now=time;
 2655:     my %privileged;
 2656:     foreach my $entry (keys %dumphash) {
 2657: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2658:         if (($tstart) && ($tstart<0)) { next; }
 2659:         if (($tend) && ($tend<$now)) { next; }
 2660:         if (($tstart) && ($now<$tstart)) { next; }
 2661:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2662: 	if ($username eq '' || $domain eq '') { next; }
 2663:         unless (ref($privileged{$domain}) eq 'HASH') {
 2664:             my %dompersonnel =
 2665:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2666:             $privileged{$domain} = {};
 2667:             foreach my $server (keys(%dompersonnel)) {
 2668:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2669:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2670:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2671:                         $privileged{$udom}{$uname} = 1;
 2672:                     }
 2673:                 }
 2674:             }
 2675:         }
 2676:         if ((exists($privileged{$domain}{$username})) &&
 2677:             (!$nothide{$username.':'.$domain})) { next; }
 2678: 	if ($role eq 'cr') { next; }
 2679:         if ($codes) {
 2680:             if ($section) { $role .= ':'.$section; }
 2681:             if ($returnhash{$role}) {
 2682:                 $returnhash{$role}.=','.$username.':'.$domain;
 2683:             } else {
 2684:                 $returnhash{$role}=$username.':'.$domain;
 2685:             }
 2686:         } else {
 2687:             my $key=&plaintext($role);
 2688:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2689:             if ($returnhash{$key}) {
 2690: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2691:             } else {
 2692:                 $returnhash{$key}=$username.':'.$domain;
 2693:             }
 2694:         }
 2695:     }
 2696:     return %returnhash;
 2697: }
 2698: 
 2699: sub get_my_roles {
 2700:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2701:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2702:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2703:     my (%dumphash,%nothide);
 2704:     if ($context eq 'userroles') { 
 2705:         %dumphash = &dump('roles',$udom,$uname);
 2706:     } else {
 2707:         %dumphash=
 2708:             &dump('nohist_userroles',$udom,$uname);
 2709:         if ($hidepriv) {
 2710:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2711:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2712:                 if ($user !~ /:/) {
 2713:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2714:                 } else {
 2715:                     $nothide{$user} = 1;
 2716:                 }
 2717:             }
 2718:         }
 2719:     }
 2720:     my %returnhash=();
 2721:     my $now=time;
 2722:     my %privileged;
 2723:     foreach my $entry (keys(%dumphash)) {
 2724:         my ($role,$tend,$tstart);
 2725:         if ($context eq 'userroles') {
 2726: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2727:         } else {
 2728:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2729:         }
 2730:         if (($tstart) && ($tstart<0)) { next; }
 2731:         my $status = 'active';
 2732:         if (($tend) && ($tend<=$now)) {
 2733:             $status = 'previous';
 2734:         } 
 2735:         if (($tstart) && ($now<$tstart)) {
 2736:             $status = 'future';
 2737:         }
 2738:         if (ref($types) eq 'ARRAY') {
 2739:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2740:                 next;
 2741:             } 
 2742:         } else {
 2743:             if ($status ne 'active') {
 2744:                 next;
 2745:             }
 2746:         }
 2747:         my ($rolecode,$username,$domain,$section,$area);
 2748:         if ($context eq 'userroles') {
 2749:             ($area,$rolecode) = split(/_/,$entry);
 2750:             (undef,$domain,$username,$section) = split(/\//,$area);
 2751:         } else {
 2752:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2753:         }
 2754:         if (ref($roledoms) eq 'ARRAY') {
 2755:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2756:                 next;
 2757:             }
 2758:         }
 2759:         if (ref($roles) eq 'ARRAY') {
 2760:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2761:                 if ($role =~ /^cr\//) {
 2762:                     if (!grep(/^cr$/,@{$roles})) {
 2763:                         next;
 2764:                     }
 2765:                 } else {
 2766:                     next;
 2767:                 }
 2768:             }
 2769:         }
 2770:         if ($hidepriv) {
 2771:             if ($context eq 'userroles') {
 2772:                 if ((&privileged($username,$domain)) &&
 2773:                     (!$nothide{$username.':'.$domain})) {
 2774:                     next;
 2775:                 }
 2776:             } else {
 2777:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2778:                     my %dompersonnel =
 2779:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2780:                     $privileged{$domain} = {};
 2781:                     if (keys(%dompersonnel)) {
 2782:                         foreach my $server (keys(%dompersonnel)) {
 2783:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2784:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2785:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2786:                                     $privileged{$udom}{$uname} = $trole;
 2787:                                 }
 2788:                             }
 2789:                         }
 2790:                     }
 2791:                 }
 2792:                 if (exists($privileged{$domain}{$username})) {
 2793:                     if (!$nothide{$username.':'.$domain}) {
 2794:                         next;
 2795:                     }
 2796:                 }
 2797:             }
 2798:         }
 2799:         if ($withsec) {
 2800:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2801:                 $tstart.':'.$tend;
 2802:         } else {
 2803:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2804:         }
 2805:     }
 2806:     return %returnhash;
 2807: }
 2808: 
 2809: # ----------------------------------------------------- Frontpage Announcements
 2810: #
 2811: #
 2812: 
 2813: sub postannounce {
 2814:     my ($server,$text)=@_;
 2815:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2816:     unless ($text=~/\w/) { $text=''; }
 2817:     return &reply('setannounce:'.&escape($text),$server);
 2818: }
 2819: 
 2820: sub getannounce {
 2821: 
 2822:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2823: 	my $announcement='';
 2824: 	while (my $line = <$fh>) { $announcement .= $line; }
 2825: 	close($fh);
 2826: 	if ($announcement=~/\w/) { 
 2827: 	    return 
 2828:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2829:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2830: 	} else {
 2831: 	    return '';
 2832: 	}
 2833:     } else {
 2834: 	return '';
 2835:     }
 2836: }
 2837: 
 2838: # ---------------------------------------------------------- Course ID routines
 2839: # Deal with domain's nohist_courseid.db files
 2840: #
 2841: 
 2842: sub courseidput {
 2843:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2844:     my $outcome;
 2845:     if ($caller eq 'timeonly') {
 2846:         my $cids = '';
 2847:         foreach my $item (keys(%$storehash)) {
 2848:             $cids.=&escape($item).'&';
 2849:         }
 2850:         $cids=~s/\&$//;
 2851:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2852:                           $coursehome);       
 2853:     } else {
 2854:         my $items = '';
 2855:         foreach my $item (keys(%$storehash)) {
 2856:             $items.= &escape($item).'='.
 2857:                      &freeze_escape($$storehash{$item}).'&';
 2858:         }
 2859:         $items=~s/\&$//;
 2860:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2861:                           $coursehome);
 2862:     }
 2863:     if ($outcome eq 'unknown_cmd') {
 2864:         my $what;
 2865:         foreach my $cid (keys(%$storehash)) {
 2866:             $what .= &escape($cid).'=';
 2867:             foreach my $item ('description','inst_code','owner','type') {
 2868:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2869:             }
 2870:             $what =~ s/\:$/&/;
 2871:         }
 2872:         $what =~ s/\&$//;  
 2873:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2874:     } else {
 2875:         return $outcome;
 2876:     }
 2877: }
 2878: 
 2879: sub courseiddump {
 2880:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2881:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2882:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2883:     my $as_hash = 1;
 2884:     my %returnhash;
 2885:     if (!$domfilter) { $domfilter=''; }
 2886:     my %libserv = &all_library();
 2887:     foreach my $tryserver (keys(%libserv)) {
 2888:         if ( (  $hostidflag == 1 
 2889: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2890: 	     || (!defined($hostidflag)) ) {
 2891: 
 2892: 	    if (($domfilter eq '') ||
 2893: 		(&host_domain($tryserver) eq $domfilter)) {
 2894:                 my $rep = 
 2895:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2896:                          $sincefilter.':'.&escape($descfilter).':'.
 2897:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2898:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2899:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2900:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2901:                          $showhidden.':'.$caller,$tryserver);
 2902:                 my @pairs=split(/\&/,$rep);
 2903:                 foreach my $item (@pairs) {
 2904:                     my ($key,$value)=split(/\=/,$item,2);
 2905:                     $key = &unescape($key);
 2906:                     next if ($key =~ /^error: 2 /);
 2907:                     my $result = &thaw_unescape($value);
 2908:                     if (ref($result) eq 'HASH') {
 2909:                         $returnhash{$key}=$result;
 2910:                     } else {
 2911:                         my @responses = split(/:/,$value);
 2912:                         my @items = ('description','inst_code','owner','type');
 2913:                         for (my $i=0; $i<@responses; $i++) {
 2914:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2915:                         }
 2916:                     } 
 2917:                 }
 2918:             }
 2919:         }
 2920:     }
 2921:     return %returnhash;
 2922: }
 2923: 
 2924: # ---------------------------------------------------------- DC e-mail
 2925: 
 2926: sub dcmailput {
 2927:     my ($domain,$msgid,$message,$server)=@_;
 2928:     my $status = &Apache::lonnet::critical(
 2929:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2930:        &escape($message),$server);
 2931:     return $status;
 2932: }
 2933: 
 2934: sub dcmaildump {
 2935:     my ($dom,$startdate,$enddate,$senders) = @_;
 2936:     my %returnhash=();
 2937: 
 2938:     if (defined(&domain($dom,'primary'))) {
 2939:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2940:                                                          &escape($enddate).':';
 2941: 	my @esc_senders=map { &escape($_)} @$senders;
 2942: 	$cmd.=&escape(join('&',@esc_senders));
 2943: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2944:             my ($key,$value) = split(/\=/,$line,2);
 2945:             if (($key) && ($value)) {
 2946:                 $returnhash{&unescape($key)} = &unescape($value);
 2947:             }
 2948:         }
 2949:     }
 2950:     return %returnhash;
 2951: }
 2952: # ---------------------------------------------------------- Domain roles
 2953: 
 2954: sub get_domain_roles {
 2955:     my ($dom,$roles,$startdate,$enddate)=@_;
 2956:     if (undef($startdate) || $startdate eq '') {
 2957:         $startdate = '.';
 2958:     }
 2959:     if (undef($enddate) || $enddate eq '') {
 2960:         $enddate = '.';
 2961:     }
 2962:     my $rolelist;
 2963:     if (ref($roles) eq 'ARRAY') {
 2964:         $rolelist = join(':',@{$roles});
 2965:     }
 2966:     my %personnel = ();
 2967: 
 2968:     my %servers = &get_servers($dom,'library');
 2969:     foreach my $tryserver (keys(%servers)) {
 2970: 	%{$personnel{$tryserver}}=();
 2971: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2972: 					    &escape($startdate).':'.
 2973: 					    &escape($enddate).':'.
 2974: 					    &escape($rolelist), $tryserver))) {
 2975: 	    my ($key,$value) = split(/\=/,$line,2);
 2976: 	    if (($key) && ($value)) {
 2977: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2978: 	    }
 2979: 	}
 2980:     }
 2981:     return %personnel;
 2982: }
 2983: 
 2984: # ----------------------------------------------------------- Check out an item
 2985: 
 2986: sub get_first_access {
 2987:     my ($type,$argsymb)=@_;
 2988:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2989:     if ($argsymb) { $symb=$argsymb; }
 2990:     my ($map,$id,$res)=&decode_symb($symb);
 2991:     if ($type eq 'course') {
 2992: 	$res='course';
 2993:     } elsif ($type eq 'map') {
 2994: 	$res=&symbread($map);
 2995:     } else {
 2996: 	$res=$symb;
 2997:     }
 2998:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2999:     return $times{"$courseid\0$res"};
 3000: }
 3001: 
 3002: sub set_first_access {
 3003:     my ($type)=@_;
 3004:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3005:     my ($map,$id,$res)=&decode_symb($symb);
 3006:     if ($type eq 'course') {
 3007: 	$res='course';
 3008:     } elsif ($type eq 'map') {
 3009: 	$res=&symbread($map);
 3010:     } else {
 3011: 	$res=$symb;
 3012:     }
 3013:     my $firstaccess=&get_first_access($type,$symb);
 3014:     if (!$firstaccess) {
 3015: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3016:     }
 3017:     return 'already_set';
 3018: }
 3019: 
 3020: sub checkout {
 3021:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3022:     my $now=time;
 3023:     my $lonhost=$perlvar{'lonHostID'};
 3024:     my $infostr=&escape(
 3025:                  'CHECKOUTTOKEN&'.
 3026:                  $tuname.'&'.
 3027:                  $tudom.'&'.
 3028:                  $tcrsid.'&'.
 3029:                  $symb.'&'.
 3030: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3031:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3032:     if ($token=~/^error\:/) { 
 3033:         &logthis("<font color=\"blue\">WARNING: ".
 3034:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3035:                  "</font>");
 3036:         return ''; 
 3037:     }
 3038: 
 3039:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3040:     $token=~tr/a-z/A-Z/;
 3041: 
 3042:     my %infohash=('resource.0.outtoken' => $token,
 3043:                   'resource.0.checkouttime' => $now,
 3044:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3045: 
 3046:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3047:        return '';
 3048:     } else {
 3049:         &logthis("<font color=\"blue\">WARNING: ".
 3050:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3051:                  "</font>");
 3052:     }    
 3053: 
 3054:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3055:                          &escape('Checkout '.$infostr.' - '.
 3056:                                                  $token)) ne 'ok') {
 3057: 	return '';
 3058:     } else {
 3059:         &logthis("<font color=\"blue\">WARNING: ".
 3060:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3061:                  "</font>");
 3062:     }
 3063:     return $token;
 3064: }
 3065: 
 3066: # ------------------------------------------------------------ Check in an item
 3067: 
 3068: sub checkin {
 3069:     my $token=shift;
 3070:     my $now=time;
 3071:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3072:     $lonhost=~tr/A-Z/a-z/;
 3073:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3074:     $dtoken=~s/\W/\_/g;
 3075:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3076:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3077: 
 3078:     unless (($tuname) && ($tudom)) {
 3079:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3080:         return '';
 3081:     }
 3082:     
 3083:     unless (&allowed('mgr',$tcrsid)) {
 3084:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3085:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3086:         return '';
 3087:     }
 3088: 
 3089:     my %infohash=('resource.0.intoken' => $token,
 3090:                   'resource.0.checkintime' => $now,
 3091:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3092: 
 3093:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3094:        return '';
 3095:     }    
 3096: 
 3097:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3098:                          &escape('Checkin - '.$token)) ne 'ok') {
 3099: 	return '';
 3100:     }
 3101: 
 3102:     return ($symb,$tuname,$tudom,$tcrsid);    
 3103: }
 3104: 
 3105: # --------------------------------------------- Set Expire Date for Spreadsheet
 3106: 
 3107: sub expirespread {
 3108:     my ($uname,$udom,$stype,$usymb)=@_;
 3109:     my $cid=$env{'request.course.id'}; 
 3110:     if ($cid) {
 3111:        my $now=time;
 3112:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3113:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3114:                             $env{'course.'.$cid.'.num'}.
 3115: 	        	    ':nohist_expirationdates:'.
 3116:                             &escape($key).'='.$now,
 3117:                             $env{'course.'.$cid.'.home'})
 3118:     }
 3119:     return 'ok';
 3120: }
 3121: 
 3122: # ----------------------------------------------------- Devalidate Spreadsheets
 3123: 
 3124: sub devalidate {
 3125:     my ($symb,$uname,$udom)=@_;
 3126:     my $cid=$env{'request.course.id'}; 
 3127:     if ($cid) {
 3128:         # delete the stored spreadsheets for
 3129:         # - the student level sheet of this user in course's homespace
 3130:         # - the assessment level sheet for this resource 
 3131:         #   for this user in user's homespace
 3132: 	# - current conditional state info
 3133: 	my $key=$uname.':'.$udom.':';
 3134:         my $status=
 3135: 	    &del('nohist_calculatedsheets',
 3136: 		 [$key.'studentcalc:'],
 3137: 		 $env{'course.'.$cid.'.domain'},
 3138: 		 $env{'course.'.$cid.'.num'})
 3139: 		.' '.
 3140: 	    &del('nohist_calculatedsheets_'.$cid,
 3141: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3142:         unless ($status eq 'ok ok') {
 3143:            &logthis('Could not devalidate spreadsheet '.
 3144:                     $uname.' at '.$udom.' for '.
 3145: 		    $symb.': '.$status);
 3146:         }
 3147: 	&delenv('user.state.'.$cid);
 3148:     }
 3149: }
 3150: 
 3151: sub get_scalar {
 3152:     my ($string,$end) = @_;
 3153:     my $value;
 3154:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3155: 	$value = $1;
 3156:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3157: 	$value = $1;
 3158:     }
 3159:     return &unescape($value);
 3160: }
 3161: 
 3162: sub array2str {
 3163:   my (@array) = @_;
 3164:   my $result=&arrayref2str(\@array);
 3165:   $result=~s/^__ARRAY_REF__//;
 3166:   $result=~s/__END_ARRAY_REF__$//;
 3167:   return $result;
 3168: }
 3169: 
 3170: sub arrayref2str {
 3171:   my ($arrayref) = @_;
 3172:   my $result='__ARRAY_REF__';
 3173:   foreach my $elem (@$arrayref) {
 3174:     if(ref($elem) eq 'ARRAY') {
 3175:       $result.=&arrayref2str($elem).'&';
 3176:     } elsif(ref($elem) eq 'HASH') {
 3177:       $result.=&hashref2str($elem).'&';
 3178:     } elsif(ref($elem)) {
 3179:       #print("Got a ref of ".(ref($elem))." skipping.");
 3180:     } else {
 3181:       $result.=&escape($elem).'&';
 3182:     }
 3183:   }
 3184:   $result=~s/\&$//;
 3185:   $result .= '__END_ARRAY_REF__';
 3186:   return $result;
 3187: }
 3188: 
 3189: sub hash2str {
 3190:   my (%hash) = @_;
 3191:   my $result=&hashref2str(\%hash);
 3192:   $result=~s/^__HASH_REF__//;
 3193:   $result=~s/__END_HASH_REF__$//;
 3194:   return $result;
 3195: }
 3196: 
 3197: sub hashref2str {
 3198:   my ($hashref)=@_;
 3199:   my $result='__HASH_REF__';
 3200:   foreach my $key (sort(keys(%$hashref))) {
 3201:     if (ref($key) eq 'ARRAY') {
 3202:       $result.=&arrayref2str($key).'=';
 3203:     } elsif (ref($key) eq 'HASH') {
 3204:       $result.=&hashref2str($key).'=';
 3205:     } elsif (ref($key)) {
 3206:       $result.='=';
 3207:       #print("Got a ref of ".(ref($key))." skipping.");
 3208:     } else {
 3209: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3210:     }
 3211: 
 3212:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3213:       $result.=&arrayref2str($hashref->{$key}).'&';
 3214:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3215:       $result.=&hashref2str($hashref->{$key}).'&';
 3216:     } elsif(ref($hashref->{$key})) {
 3217:        $result.='&';
 3218:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3219:     } else {
 3220:       $result.=&escape($hashref->{$key}).'&';
 3221:     }
 3222:   }
 3223:   $result=~s/\&$//;
 3224:   $result .= '__END_HASH_REF__';
 3225:   return $result;
 3226: }
 3227: 
 3228: sub str2hash {
 3229:     my ($string)=@_;
 3230:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3231:     return %$hash;
 3232: }
 3233: 
 3234: sub str2hashref {
 3235:   my ($string) = @_;
 3236: 
 3237:   my %hash;
 3238: 
 3239:   if($string !~ /^__HASH_REF__/) {
 3240:       if (! ($string eq '' || !defined($string))) {
 3241: 	  $hash{'error'}='Not hash reference';
 3242:       }
 3243:       return (\%hash, $string);
 3244:   }
 3245: 
 3246:   $string =~ s/^__HASH_REF__//;
 3247: 
 3248:   while($string !~ /^__END_HASH_REF__/) {
 3249:       #key
 3250:       my $key='';
 3251:       if($string =~ /^__HASH_REF__/) {
 3252:           ($key, $string)=&str2hashref($string);
 3253:           if(defined($key->{'error'})) {
 3254:               $hash{'error'}='Bad data';
 3255:               return (\%hash, $string);
 3256:           }
 3257:       } elsif($string =~ /^__ARRAY_REF__/) {
 3258:           ($key, $string)=&str2arrayref($string);
 3259:           if($key->[0] eq 'Array reference error') {
 3260:               $hash{'error'}='Bad data';
 3261:               return (\%hash, $string);
 3262:           }
 3263:       } else {
 3264:           $string =~ s/^(.*?)=//;
 3265: 	  $key=&unescape($1);
 3266:       }
 3267:       $string =~ s/^=//;
 3268: 
 3269:       #value
 3270:       my $value='';
 3271:       if($string =~ /^__HASH_REF__/) {
 3272:           ($value, $string)=&str2hashref($string);
 3273:           if(defined($value->{'error'})) {
 3274:               $hash{'error'}='Bad data';
 3275:               return (\%hash, $string);
 3276:           }
 3277:       } elsif($string =~ /^__ARRAY_REF__/) {
 3278:           ($value, $string)=&str2arrayref($string);
 3279:           if($value->[0] eq 'Array reference error') {
 3280:               $hash{'error'}='Bad data';
 3281:               return (\%hash, $string);
 3282:           }
 3283:       } else {
 3284: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3285:       }
 3286:       $string =~ s/^&//;
 3287: 
 3288:       $hash{$key}=$value;
 3289:   }
 3290: 
 3291:   $string =~ s/^__END_HASH_REF__//;
 3292: 
 3293:   return (\%hash, $string);
 3294: }
 3295: 
 3296: sub str2array {
 3297:     my ($string)=@_;
 3298:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3299:     return @$array;
 3300: }
 3301: 
 3302: sub str2arrayref {
 3303:   my ($string) = @_;
 3304:   my @array;
 3305: 
 3306:   if($string !~ /^__ARRAY_REF__/) {
 3307:       if (! ($string eq '' || !defined($string))) {
 3308: 	  $array[0]='Array reference error';
 3309:       }
 3310:       return (\@array, $string);
 3311:   }
 3312: 
 3313:   $string =~ s/^__ARRAY_REF__//;
 3314: 
 3315:   while($string !~ /^__END_ARRAY_REF__/) {
 3316:       my $value='';
 3317:       if($string =~ /^__HASH_REF__/) {
 3318:           ($value, $string)=&str2hashref($string);
 3319:           if(defined($value->{'error'})) {
 3320:               $array[0] ='Array reference error';
 3321:               return (\@array, $string);
 3322:           }
 3323:       } elsif($string =~ /^__ARRAY_REF__/) {
 3324:           ($value, $string)=&str2arrayref($string);
 3325:           if($value->[0] eq 'Array reference error') {
 3326:               $array[0] ='Array reference error';
 3327:               return (\@array, $string);
 3328:           }
 3329:       } else {
 3330: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3331:       }
 3332:       $string =~ s/^&//;
 3333: 
 3334:       push(@array, $value);
 3335:   }
 3336: 
 3337:   $string =~ s/^__END_ARRAY_REF__//;
 3338: 
 3339:   return (\@array, $string);
 3340: }
 3341: 
 3342: # -------------------------------------------------------------------Temp Store
 3343: 
 3344: sub tmpreset {
 3345:   my ($symb,$namespace,$domain,$stuname) = @_;
 3346:   if (!$symb) {
 3347:     $symb=&symbread();
 3348:     if (!$symb) { $symb= $env{'request.url'}; }
 3349:   }
 3350:   $symb=escape($symb);
 3351: 
 3352:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3353:   $namespace=~s/\//\_/g;
 3354:   $namespace=~s/\W//g;
 3355: 
 3356:   if (!$domain) { $domain=$env{'user.domain'}; }
 3357:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3358:   if ($domain eq 'public' && $stuname eq 'public') {
 3359:       $stuname=$ENV{'REMOTE_ADDR'};
 3360:   }
 3361:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3362:   my %hash;
 3363:   if (tie(%hash,'GDBM_File',
 3364: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3365: 	  &GDBM_WRCREAT(),0640)) {
 3366:     foreach my $key (keys %hash) {
 3367:       if ($key=~ /:$symb/) {
 3368: 	delete($hash{$key});
 3369:       }
 3370:     }
 3371:   }
 3372: }
 3373: 
 3374: sub tmpstore {
 3375:   my ($storehash,$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) {
 3384:     # I don't think we would ever want to store this for a course.
 3385:     # it seems this will only be used if we don't have a course.
 3386:     #$namespace=$env{'request.course.id'};
 3387:     #if (!$namespace) {
 3388:       $namespace=$env{'request.state'};
 3389:     #}
 3390:   }
 3391:   $namespace=~s/\//\_/g;
 3392:   $namespace=~s/\W//g;
 3393:   if (!$domain) { $domain=$env{'user.domain'}; }
 3394:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3395:   if ($domain eq 'public' && $stuname eq 'public') {
 3396:       $stuname=$ENV{'REMOTE_ADDR'};
 3397:   }
 3398:   my $now=time;
 3399:   my %hash;
 3400:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3401:   if (tie(%hash,'GDBM_File',
 3402: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3403: 	  &GDBM_WRCREAT(),0640)) {
 3404:     $hash{"version:$symb"}++;
 3405:     my $version=$hash{"version:$symb"};
 3406:     my $allkeys=''; 
 3407:     foreach my $key (keys(%$storehash)) {
 3408:       $allkeys.=$key.':';
 3409:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3410:     }
 3411:     $hash{"$version:$symb:timestamp"}=$now;
 3412:     $allkeys.='timestamp';
 3413:     $hash{"$version:keys:$symb"}=$allkeys;
 3414:     if (untie(%hash)) {
 3415:       return 'ok';
 3416:     } else {
 3417:       return "error:$!";
 3418:     }
 3419:   } else {
 3420:     return "error:$!";
 3421:   }
 3422: }
 3423: 
 3424: # -----------------------------------------------------------------Temp Restore
 3425: 
 3426: sub tmprestore {
 3427:   my ($symb,$namespace,$domain,$stuname) = @_;
 3428: 
 3429:   if (!$symb) {
 3430:     $symb=&symbread();
 3431:     if (!$symb) { $symb= $env{'request.url'}; }
 3432:   }
 3433:   $symb=escape($symb);
 3434: 
 3435:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3436: 
 3437:   if (!$domain) { $domain=$env{'user.domain'}; }
 3438:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3439:   if ($domain eq 'public' && $stuname eq 'public') {
 3440:       $stuname=$ENV{'REMOTE_ADDR'};
 3441:   }
 3442:   my %returnhash;
 3443:   $namespace=~s/\//\_/g;
 3444:   $namespace=~s/\W//g;
 3445:   my %hash;
 3446:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3447:   if (tie(%hash,'GDBM_File',
 3448: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3449: 	  &GDBM_READER(),0640)) {
 3450:     my $version=$hash{"version:$symb"};
 3451:     $returnhash{'version'}=$version;
 3452:     my $scope;
 3453:     for ($scope=1;$scope<=$version;$scope++) {
 3454:       my $vkeys=$hash{"$scope:keys:$symb"};
 3455:       my @keys=split(/:/,$vkeys);
 3456:       my $key;
 3457:       $returnhash{"$scope:keys"}=$vkeys;
 3458:       foreach $key (@keys) {
 3459: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3460: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3461:       }
 3462:     }
 3463:     if (!(untie(%hash))) {
 3464:       return "error:$!";
 3465:     }
 3466:   } else {
 3467:     return "error:$!";
 3468:   }
 3469:   return %returnhash;
 3470: }
 3471: 
 3472: # ----------------------------------------------------------------------- Store
 3473: 
 3474: sub store {
 3475:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3476:     my $home='';
 3477: 
 3478:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3479: 
 3480:     $symb=&symbclean($symb);
 3481:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3482: 
 3483:     if (!$domain) { $domain=$env{'user.domain'}; }
 3484:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3485: 
 3486:     &devalidate($symb,$stuname,$domain);
 3487: 
 3488:     $symb=escape($symb);
 3489:     if (!$namespace) { 
 3490:        unless ($namespace=$env{'request.course.id'}) { 
 3491:           return ''; 
 3492:        } 
 3493:     }
 3494:     if (!$home) { $home=$env{'user.home'}; }
 3495: 
 3496:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3497:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3498: 
 3499:     my $namevalue='';
 3500:     foreach my $key (keys(%$storehash)) {
 3501:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3502:     }
 3503:     $namevalue=~s/\&$//;
 3504:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3505:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3506: }
 3507: 
 3508: # -------------------------------------------------------------- Critical Store
 3509: 
 3510: sub cstore {
 3511:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3512:     my $home='';
 3513: 
 3514:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3515: 
 3516:     $symb=&symbclean($symb);
 3517:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3518: 
 3519:     if (!$domain) { $domain=$env{'user.domain'}; }
 3520:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3521: 
 3522:     &devalidate($symb,$stuname,$domain);
 3523: 
 3524:     $symb=escape($symb);
 3525:     if (!$namespace) { 
 3526:        unless ($namespace=$env{'request.course.id'}) { 
 3527:           return ''; 
 3528:        } 
 3529:     }
 3530:     if (!$home) { $home=$env{'user.home'}; }
 3531: 
 3532:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3533:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3534: 
 3535:     my $namevalue='';
 3536:     foreach my $key (keys(%$storehash)) {
 3537:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3538:     }
 3539:     $namevalue=~s/\&$//;
 3540:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3541:     return critical
 3542:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3543: }
 3544: 
 3545: # --------------------------------------------------------------------- Restore
 3546: 
 3547: sub restore {
 3548:     my ($symb,$namespace,$domain,$stuname) = @_;
 3549:     my $home='';
 3550: 
 3551:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3552: 
 3553:     if (!$symb) {
 3554:       unless ($symb=escape(&symbread())) { return ''; }
 3555:     } else {
 3556:       $symb=&escape(&symbclean($symb));
 3557:     }
 3558:     if (!$namespace) { 
 3559:        unless ($namespace=$env{'request.course.id'}) { 
 3560:           return ''; 
 3561:        } 
 3562:     }
 3563:     if (!$domain) { $domain=$env{'user.domain'}; }
 3564:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3565:     if (!$home) { $home=$env{'user.home'}; }
 3566:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3567: 
 3568:     my %returnhash=();
 3569:     foreach my $line (split(/\&/,$answer)) {
 3570: 	my ($name,$value)=split(/\=/,$line);
 3571:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3572:     }
 3573:     my $version;
 3574:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3575:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3576:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3577:        }
 3578:     }
 3579:     return %returnhash;
 3580: }
 3581: 
 3582: # ---------------------------------------------------------- Course Description
 3583: 
 3584: sub coursedescription {
 3585:     my ($courseid,$args)=@_;
 3586:     $courseid=~s/^\///;
 3587:     $courseid=~s/\_/\//g;
 3588:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3589:     my $chome=&homeserver($cnum,$cdomain);
 3590:     my $normalid=$cdomain.'_'.$cnum;
 3591:     # need to always cache even if we get errors otherwise we keep 
 3592:     # trying and trying and trying to get the course description.
 3593:     my %envhash=();
 3594:     my %returnhash=();
 3595:     
 3596:     my $expiretime=600;
 3597:     if ($env{'request.course.id'} eq $normalid) {
 3598: 	$expiretime=120;
 3599:     }
 3600: 
 3601:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3602:     if (!$args->{'freshen_cache'}
 3603: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3604: 	foreach my $key (keys(%env)) {
 3605: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3606: 	    my ($setting) = $1;
 3607: 	    $returnhash{$setting} = $env{$key};
 3608: 	}
 3609: 	return %returnhash;
 3610:     }
 3611: 
 3612:     # get the data agin
 3613:     if (!$args->{'one_time'}) {
 3614: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3615:     }
 3616: 
 3617:     if ($chome ne 'no_host') {
 3618:        %returnhash=&dump('environment',$cdomain,$cnum);
 3619:        if (!exists($returnhash{'con_lost'})) {
 3620:            $returnhash{'home'}= $chome;
 3621: 	   $returnhash{'domain'} = $cdomain;
 3622: 	   $returnhash{'num'} = $cnum;
 3623:            if (!defined($returnhash{'type'})) {
 3624:                $returnhash{'type'} = 'Course';
 3625:            }
 3626:            while (my ($name,$value) = each %returnhash) {
 3627:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3628:            }
 3629:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3630:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3631: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3632:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3633:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3634:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3635:        }
 3636:     }
 3637:     if (!$args->{'one_time'}) {
 3638: 	&appenv(\%envhash);
 3639:     }
 3640:     return %returnhash;
 3641: }
 3642: 
 3643: # -------------------------------------------------See if a user is privileged
 3644: 
 3645: sub privileged {
 3646:     my ($username,$domain)=@_;
 3647:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3648: 			&homeserver($username,$domain));
 3649:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3650:     my $now=time;
 3651:     if ($rolesdump ne '') {
 3652:         foreach my $entry (split(/&/,$rolesdump)) {
 3653: 	    if ($entry!~/^rolesdef_/) {
 3654: 		my ($area,$role)=split(/=/,$entry);
 3655: 		$area=~s/\_\w\w$//;
 3656: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3657: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3658: 		    my $active=1;
 3659: 		    if ($tend) {
 3660: 			if ($tend<$now) { $active=0; }
 3661: 		    }
 3662: 		    if ($tstart) {
 3663: 			if ($tstart>$now) { $active=0; }
 3664: 		    }
 3665: 		    if ($active) { return 1; }
 3666: 		}
 3667: 	    }
 3668: 	}
 3669:     }
 3670:     return 0;
 3671: }
 3672: 
 3673: # -------------------------------------------------------- Get user privileges
 3674: 
 3675: sub rolesinit {
 3676:     my ($domain,$username,$authhost)=@_;
 3677:     my %userroles;
 3678:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3679:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3680:     my %allroles=();
 3681:     my %allgroups=();   
 3682:     my $now=time;
 3683:     %userroles = ('user.login.time' => $now);
 3684:     my $group_privs;
 3685: 
 3686:     if ($rolesdump ne '') {
 3687:         foreach my $entry (split(/&/,$rolesdump)) {
 3688: 	  if ($entry!~/^rolesdef_/) {
 3689:             my ($area,$role)=split(/=/,$entry);
 3690: 	    $area=~s/\_\w\w$//;
 3691:             my ($trole,$tend,$tstart,$group_privs);
 3692: 	    if ($role=~/^cr/) { 
 3693: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3694: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3695: 		    ($tend,$tstart)=split('_',$trest);
 3696: 		} else {
 3697: 		    $trole=$role;
 3698: 		}
 3699:             } elsif ($role =~ m|^gr/|) {
 3700:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3701:                 ($trole,$group_privs) = split(/\//,$trole);
 3702:                 $group_privs = &unescape($group_privs);
 3703: 	    } else {
 3704: 		($trole,$tend,$tstart)=split(/_/,$role);
 3705: 	    }
 3706: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3707: 					 $username);
 3708: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3709:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3710:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3711:             if (($area ne '') && ($trole ne '')) {
 3712: 		my $spec=$trole.'.'.$area;
 3713: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3714: 		if ($trole =~ /^cr\//) {
 3715:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3716:                 } elsif ($trole eq 'gr') {
 3717:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3718: 		} else {
 3719:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3720: 		}
 3721:             }
 3722:           }
 3723:         }
 3724:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3725:         $userroles{'user.adv'}    = $adv;
 3726: 	$userroles{'user.author'} = $author;
 3727:         $env{'user.adv'}=$adv;
 3728:     }
 3729:     return \%userroles;  
 3730: }
 3731: 
 3732: sub set_arearole {
 3733:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3734: # log the associated role with the area
 3735:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3736:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3737: }
 3738: 
 3739: sub custom_roleprivs {
 3740:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3741:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3742:     my $homsvr=homeserver($rauthor,$rdomain);
 3743:     if (&hostname($homsvr) ne '') {
 3744:         my ($rdummy,$roledef)=
 3745:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3746:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3747:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3748:             if (defined($syspriv)) {
 3749:                 $$allroles{'cm./'}.=':'.$syspriv;
 3750:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3751:             }
 3752:             if ($tdomain ne '') {
 3753:                 if (defined($dompriv)) {
 3754:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3755:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3756:                 }
 3757:                 if (($trest ne '') && (defined($coursepriv))) {
 3758:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3759:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3760:                 }
 3761:             }
 3762:         }
 3763:     }
 3764: }
 3765: 
 3766: sub group_roleprivs {
 3767:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3768:     my $access = 1;
 3769:     my $now = time;
 3770:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3771:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3772:     if ($access) {
 3773:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3774:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3775:     }
 3776: }
 3777: 
 3778: sub standard_roleprivs {
 3779:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3780:     if (defined($pr{$trole.':s'})) {
 3781:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3782:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3783:     }
 3784:     if ($tdomain ne '') {
 3785:         if (defined($pr{$trole.':d'})) {
 3786:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3787:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3788:         }
 3789:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3790:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3791:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3792:         }
 3793:     }
 3794: }
 3795: 
 3796: sub set_userprivs {
 3797:     my ($userroles,$allroles,$allgroups) = @_; 
 3798:     my $author=0;
 3799:     my $adv=0;
 3800:     my %grouproles = ();
 3801:     if (keys(%{$allgroups}) > 0) {
 3802:         foreach my $role (keys %{$allroles}) {
 3803:             my ($trole,$area,$sec,$extendedarea);
 3804:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3805:                 $trole = $1;
 3806:                 $area = $2;
 3807:                 $sec = $3;
 3808:                 $extendedarea = $area.$sec;
 3809:                 if (exists($$allgroups{$area})) {
 3810:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3811:                         my $spec = $trole.'.'.$extendedarea;
 3812:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3813:                                                 $$allgroups{$area}{$group};
 3814:                     }
 3815:                 }
 3816:             }
 3817:         }
 3818:     }
 3819:     foreach my $group (keys(%grouproles)) {
 3820:         $$allroles{$group} = $grouproles{$group};
 3821:     }
 3822:     foreach my $role (keys(%{$allroles})) {
 3823:         my %thesepriv;
 3824:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3825:         foreach my $item (split(/:/,$$allroles{$role})) {
 3826:             if ($item ne '') {
 3827:                 my ($privilege,$restrictions)=split(/&/,$item);
 3828:                 if ($restrictions eq '') {
 3829:                     $thesepriv{$privilege}='F';
 3830:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3831:                     $thesepriv{$privilege}.=$restrictions;
 3832:                 }
 3833:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3834:             }
 3835:         }
 3836:         my $thesestr='';
 3837:         foreach my $priv (keys(%thesepriv)) {
 3838: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3839: 	}
 3840:         $userroles->{'user.priv.'.$role} = $thesestr;
 3841:     }
 3842:     return ($author,$adv);
 3843: }
 3844: 
 3845: # --------------------------------------------------------------- get interface
 3846: 
 3847: sub get {
 3848:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3849:    my $items='';
 3850:    foreach my $item (@$storearr) {
 3851:        $items.=&escape($item).'&';
 3852:    }
 3853:    $items=~s/\&$//;
 3854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3855:    if (!$uname) { $uname=$env{'user.name'}; }
 3856:    my $uhome=&homeserver($uname,$udomain);
 3857: 
 3858:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3859:    my @pairs=split(/\&/,$rep);
 3860:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3861:      return @pairs;
 3862:    }
 3863:    my %returnhash=();
 3864:    my $i=0;
 3865:    foreach my $item (@$storearr) {
 3866:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3867:       $i++;
 3868:    }
 3869:    return %returnhash;
 3870: }
 3871: 
 3872: # --------------------------------------------------------------- del interface
 3873: 
 3874: sub del {
 3875:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3876:    my $items='';
 3877:    foreach my $item (@$storearr) {
 3878:        $items.=&escape($item).'&';
 3879:    }
 3880:    $items=~s/\&$//;
 3881:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3882:    if (!$uname) { $uname=$env{'user.name'}; }
 3883:    my $uhome=&homeserver($uname,$udomain);
 3884: 
 3885:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3886: }
 3887: 
 3888: # -------------------------------------------------------------- dump interface
 3889: 
 3890: sub dump {
 3891:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3892:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3893:     if (!$uname) { $uname=$env{'user.name'}; }
 3894:     my $uhome=&homeserver($uname,$udomain);
 3895:     if ($regexp) {
 3896: 	$regexp=&escape($regexp);
 3897:     } else {
 3898: 	$regexp='.';
 3899:     }
 3900:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3901:     my @pairs=split(/\&/,$rep);
 3902:     my %returnhash=();
 3903:     foreach my $item (@pairs) {
 3904: 	my ($key,$value)=split(/=/,$item,2);
 3905: 	$key = &unescape($key);
 3906: 	next if ($key =~ /^error: 2 /);
 3907: 	$returnhash{$key}=&thaw_unescape($value);
 3908:     }
 3909:     return %returnhash;
 3910: }
 3911: 
 3912: # --------------------------------------------------------- dumpstore interface
 3913: 
 3914: sub dumpstore {
 3915:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3916:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3917:    if (!$uname) { $uname=$env{'user.name'}; }
 3918:    my $uhome=&homeserver($uname,$udomain);
 3919:    if ($regexp) {
 3920:        $regexp=&escape($regexp);
 3921:    } else {
 3922:        $regexp='.';
 3923:    }
 3924:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3925:    my @pairs=split(/\&/,$rep);
 3926:    my %returnhash=();
 3927:    foreach my $item (@pairs) {
 3928:        my ($key,$value)=split(/=/,$item,2);
 3929:        next if ($key =~ /^error: 2 /);
 3930:        $returnhash{$key}=&thaw_unescape($value);
 3931:    }
 3932:    return %returnhash;
 3933: }
 3934: 
 3935: # -------------------------------------------------------------- keys interface
 3936: 
 3937: sub getkeys {
 3938:    my ($namespace,$udomain,$uname)=@_;
 3939:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3940:    if (!$uname) { $uname=$env{'user.name'}; }
 3941:    my $uhome=&homeserver($uname,$udomain);
 3942:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3943:    my @keyarray=();
 3944:    foreach my $key (split(/\&/,$rep)) {
 3945:       next if ($key =~ /^error: 2 /);
 3946:       push(@keyarray,&unescape($key));
 3947:    }
 3948:    return @keyarray;
 3949: }
 3950: 
 3951: # --------------------------------------------------------------- currentdump
 3952: sub currentdump {
 3953:    my ($courseid,$sdom,$sname)=@_;
 3954:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3955:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3956:    $sname    = $env{'user.name'}         if (! defined($sname));
 3957:    my $uhome = &homeserver($sname,$sdom);
 3958:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3959:    return if ($rep =~ /^(error:|no_such_host)/);
 3960:    #
 3961:    my %returnhash=();
 3962:    #
 3963:    if ($rep eq "unknown_cmd") { 
 3964:        # an old lond will not know currentdump
 3965:        # Do a dump and make it look like a currentdump
 3966:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3967:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3968:        my %hash = @tmp;
 3969:        @tmp=();
 3970:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3971:    } else {
 3972:        my @pairs=split(/\&/,$rep);
 3973:        foreach my $pair (@pairs) {
 3974:            my ($key,$value)=split(/=/,$pair,2);
 3975:            my ($symb,$param) = split(/:/,$key);
 3976:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3977:                                                         &thaw_unescape($value);
 3978:        }
 3979:    }
 3980:    return %returnhash;
 3981: }
 3982: 
 3983: sub convert_dump_to_currentdump{
 3984:     my %hash = %{shift()};
 3985:     my %returnhash;
 3986:     # Code ripped from lond, essentially.  The only difference
 3987:     # here is the unescaping done by lonnet::dump().  Conceivably
 3988:     # we might run in to problems with parameter names =~ /^v\./
 3989:     while (my ($key,$value) = each(%hash)) {
 3990:         my ($v,$symb,$param) = split(/:/,$key);
 3991: 	$symb  = &unescape($symb);
 3992: 	$param = &unescape($param);
 3993:         next if ($v eq 'version' || $symb eq 'keys');
 3994:         next if (exists($returnhash{$symb}) &&
 3995:                  exists($returnhash{$symb}->{$param}) &&
 3996:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3997:         $returnhash{$symb}->{$param}=$value;
 3998:         $returnhash{$symb}->{'v.'.$param}=$v;
 3999:     }
 4000:     #
 4001:     # Remove all of the keys in the hashes which keep track of
 4002:     # the version of the parameter.
 4003:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4004:         # use a foreach because we are going to delete from the hash.
 4005:         foreach my $key (keys(%$param_hash)) {
 4006:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4007:         }
 4008:     }
 4009:     return \%returnhash;
 4010: }
 4011: 
 4012: # ------------------------------------------------------ critical inc interface
 4013: 
 4014: sub cinc {
 4015:     return &inc(@_,'critical');
 4016: }
 4017: 
 4018: # --------------------------------------------------------------- inc interface
 4019: 
 4020: sub inc {
 4021:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4022:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4023:     if (!$uname) { $uname=$env{'user.name'}; }
 4024:     my $uhome=&homeserver($uname,$udomain);
 4025:     my $items='';
 4026:     if (! ref($store)) {
 4027:         # got a single value, so use that instead
 4028:         $items = &escape($store).'=&';
 4029:     } elsif (ref($store) eq 'SCALAR') {
 4030:         $items = &escape($$store).'=&';        
 4031:     } elsif (ref($store) eq 'ARRAY') {
 4032:         $items = join('=&',map {&escape($_);} @{$store});
 4033:     } elsif (ref($store) eq 'HASH') {
 4034:         while (my($key,$value) = each(%{$store})) {
 4035:             $items.= &escape($key).'='.&escape($value).'&';
 4036:         }
 4037:     }
 4038:     $items=~s/\&$//;
 4039:     if ($critical) {
 4040: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4041:     } else {
 4042: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4043:     }
 4044: }
 4045: 
 4046: # --------------------------------------------------------------- put interface
 4047: 
 4048: sub put {
 4049:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4050:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4051:    if (!$uname) { $uname=$env{'user.name'}; }
 4052:    my $uhome=&homeserver($uname,$udomain);
 4053:    my $items='';
 4054:    foreach my $item (keys(%$storehash)) {
 4055:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4056:    }
 4057:    $items=~s/\&$//;
 4058:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4059: }
 4060: 
 4061: # ------------------------------------------------------------ newput interface
 4062: 
 4063: sub newput {
 4064:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4066:    if (!$uname) { $uname=$env{'user.name'}; }
 4067:    my $uhome=&homeserver($uname,$udomain);
 4068:    my $items='';
 4069:    foreach my $key (keys(%$storehash)) {
 4070:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4071:    }
 4072:    $items=~s/\&$//;
 4073:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4074: }
 4075: 
 4076: # ---------------------------------------------------------  putstore interface
 4077: 
 4078: sub putstore {
 4079:    my ($namespace,$symb,$version,$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 $key (keys(%$storehash)) {
 4085:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4086:    }
 4087:    $items=~s/\&$//;
 4088:    my $esc_symb=&escape($symb);
 4089:    my $esc_v=&escape($version);
 4090:    my $reply =
 4091:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4092: 	      $uhome);
 4093:    if ($reply eq 'unknown_cmd') {
 4094:        # gfall back to way things use to be done
 4095:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4096: 			    $uname);
 4097:    }
 4098:    return $reply;
 4099: }
 4100: 
 4101: sub old_putstore {
 4102:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4103:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4104:     if (!$uname) { $uname=$env{'user.name'}; }
 4105:     my $uhome=&homeserver($uname,$udomain);
 4106:     my %newstorehash;
 4107:     foreach my $item (keys(%$storehash)) {
 4108: 	my $key = $version.':'.&escape($symb).':'.$item;
 4109: 	$newstorehash{$key} = $storehash->{$item};
 4110:     }
 4111:     my $items='';
 4112:     my %allitems = ();
 4113:     foreach my $item (keys(%newstorehash)) {
 4114: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4115: 	    my $key = $1.':keys:'.$2;
 4116: 	    $allitems{$key} .= $3.':';
 4117: 	}
 4118: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4119:     }
 4120:     foreach my $item (keys(%allitems)) {
 4121: 	$allitems{$item} =~ s/\:$//;
 4122: 	$items.= $item.'='.$allitems{$item}.'&';
 4123:     }
 4124:     $items=~s/\&$//;
 4125:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4126: }
 4127: 
 4128: # ------------------------------------------------------ critical put interface
 4129: 
 4130: sub cput {
 4131:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4132:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4133:    if (!$uname) { $uname=$env{'user.name'}; }
 4134:    my $uhome=&homeserver($uname,$udomain);
 4135:    my $items='';
 4136:    foreach my $item (keys(%$storehash)) {
 4137:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4138:    }
 4139:    $items=~s/\&$//;
 4140:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4141: }
 4142: 
 4143: # -------------------------------------------------------------- eget interface
 4144: 
 4145: sub eget {
 4146:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4147:    my $items='';
 4148:    foreach my $item (@$storearr) {
 4149:        $items.=&escape($item).'&';
 4150:    }
 4151:    $items=~s/\&$//;
 4152:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4153:    if (!$uname) { $uname=$env{'user.name'}; }
 4154:    my $uhome=&homeserver($uname,$udomain);
 4155:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4156:    my @pairs=split(/\&/,$rep);
 4157:    my %returnhash=();
 4158:    my $i=0;
 4159:    foreach my $item (@$storearr) {
 4160:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4161:       $i++;
 4162:    }
 4163:    return %returnhash;
 4164: }
 4165: 
 4166: # ------------------------------------------------------------ tmpput interface
 4167: sub tmpput {
 4168:     my ($storehash,$server,$context)=@_;
 4169:     my $items='';
 4170:     foreach my $item (keys(%$storehash)) {
 4171: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4172:     }
 4173:     $items=~s/\&$//;
 4174:     if (defined($context)) {
 4175:         $items .= ':'.&escape($context);
 4176:     }
 4177:     return &reply("tmpput:$items",$server);
 4178: }
 4179: 
 4180: # ------------------------------------------------------------ tmpget interface
 4181: sub tmpget {
 4182:     my ($token,$server)=@_;
 4183:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4184:     my $rep=&reply("tmpget:$token",$server);
 4185:     my %returnhash;
 4186:     foreach my $item (split(/\&/,$rep)) {
 4187: 	my ($key,$value)=split(/=/,$item);
 4188:         next if ($key =~ /^error: 2 /);
 4189: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4190:     }
 4191:     return %returnhash;
 4192: }
 4193: 
 4194: # ------------------------------------------------------------ tmpget interface
 4195: sub tmpdel {
 4196:     my ($token,$server)=@_;
 4197:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4198:     return &reply("tmpdel:$token",$server);
 4199: }
 4200: 
 4201: # -------------------------------------------------- portfolio access checking
 4202: 
 4203: sub portfolio_access {
 4204:     my ($requrl) = @_;
 4205:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4206:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4207:     if ($result) {
 4208:         my %setters;
 4209:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4210:             my ($startblock,$endblock) =
 4211:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4212:             if ($startblock && $endblock) {
 4213:                 return 'B';
 4214:             }
 4215:         } else {
 4216:             my ($startblock,$endblock) =
 4217:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4218:             if ($startblock && $endblock) {
 4219:                 return 'B';
 4220:             }
 4221:         }
 4222:     }
 4223:     if ($result eq 'ok') {
 4224:        return 'F';
 4225:     } elsif ($result =~ /^[^:]+:guest_/) {
 4226:        return 'A';
 4227:     }
 4228:     return '';
 4229: }
 4230: 
 4231: sub get_portfolio_access {
 4232:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4233: 
 4234:     if (!ref($access_hash)) {
 4235: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4236: 	my %access_controls = &get_access_controls($current_perms,$group,
 4237: 						   $file_name);
 4238: 	$access_hash = $access_controls{$file_name};
 4239:     }
 4240: 
 4241:     my ($public,$guest,@domains,@users,@courses,@groups);
 4242:     my $now = time;
 4243:     if (ref($access_hash) eq 'HASH') {
 4244:         foreach my $key (keys(%{$access_hash})) {
 4245:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4246:             if ($start > $now) {
 4247:                 next;
 4248:             }
 4249:             if ($end && $end<$now) {
 4250:                 next;
 4251:             }
 4252:             if ($scope eq 'public') {
 4253:                 $public = $key;
 4254:                 last;
 4255:             } elsif ($scope eq 'guest') {
 4256:                 $guest = $key;
 4257:             } elsif ($scope eq 'domains') {
 4258:                 push(@domains,$key);
 4259:             } elsif ($scope eq 'users') {
 4260:                 push(@users,$key);
 4261:             } elsif ($scope eq 'course') {
 4262:                 push(@courses,$key);
 4263:             } elsif ($scope eq 'group') {
 4264:                 push(@groups,$key);
 4265:             }
 4266:         }
 4267:         if ($public) {
 4268:             return 'ok';
 4269:         }
 4270:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4271:             if ($guest) {
 4272:                 return $guest;
 4273:             }
 4274:         } else {
 4275:             if (@domains > 0) {
 4276:                 foreach my $domkey (@domains) {
 4277:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4278:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4279:                             return 'ok';
 4280:                         }
 4281:                     }
 4282:                 }
 4283:             }
 4284:             if (@users > 0) {
 4285:                 foreach my $userkey (@users) {
 4286:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4287:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4288:                             if (ref($item) eq 'HASH') {
 4289:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4290:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4291:                                     return 'ok';
 4292:                                 }
 4293:                             }
 4294:                         }
 4295:                     } 
 4296:                 }
 4297:             }
 4298:             my %roleshash;
 4299:             my @courses_and_groups = @courses;
 4300:             push(@courses_and_groups,@groups); 
 4301:             if (@courses_and_groups > 0) {
 4302:                 my (%allgroups,%allroles); 
 4303:                 my ($start,$end,$role,$sec,$group);
 4304:                 foreach my $envkey (%env) {
 4305:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4306:                         my $cid = $2.'_'.$3; 
 4307:                         if ($1 eq 'gr') {
 4308:                             $group = $4;
 4309:                             $allgroups{$cid}{$group} = $env{$envkey};
 4310:                         } else {
 4311:                             if ($4 eq '') {
 4312:                                 $sec = 'none';
 4313:                             } else {
 4314:                                 $sec = $4;
 4315:                             }
 4316:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4317:                         }
 4318:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4319:                         my $cid = $2.'_'.$3;
 4320:                         if ($4 eq '') {
 4321:                             $sec = 'none';
 4322:                         } else {
 4323:                             $sec = $4;
 4324:                         }
 4325:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4326:                     }
 4327:                 }
 4328:                 if (keys(%allroles) == 0) {
 4329:                     return;
 4330:                 }
 4331:                 foreach my $key (@courses_and_groups) {
 4332:                     my %content = %{$$access_hash{$key}};
 4333:                     my $cnum = $content{'number'};
 4334:                     my $cdom = $content{'domain'};
 4335:                     my $cid = $cdom.'_'.$cnum;
 4336:                     if (!exists($allroles{$cid})) {
 4337:                         next;
 4338:                     }    
 4339:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4340:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4341:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4342:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4343:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4344:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4345:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4346:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4347:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4348:                                         if (grep/^all$/,@sections) {
 4349:                                             return 'ok';
 4350:                                         } else {
 4351:                                             if (grep/^$sec$/,@sections) {
 4352:                                                 return 'ok';
 4353:                                             }
 4354:                                         }
 4355:                                     }
 4356:                                 }
 4357:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4358:                                     if (grep/^none$/,@groups) {
 4359:                                         return 'ok';
 4360:                                     }
 4361:                                 } else {
 4362:                                     if (grep/^all$/,@groups) {
 4363:                                         return 'ok';
 4364:                                     } 
 4365:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4366:                                         if (grep/^$group$/,@groups) {
 4367:                                             return 'ok';
 4368:                                         }
 4369:                                     }
 4370:                                 } 
 4371:                             }
 4372:                         }
 4373:                     }
 4374:                 }
 4375:             }
 4376:             if ($guest) {
 4377:                 return $guest;
 4378:             }
 4379:         }
 4380:     }
 4381:     return;
 4382: }
 4383: 
 4384: sub course_group_datechecker {
 4385:     my ($dates,$now,$status) = @_;
 4386:     my ($start,$end) = split(/\./,$dates);
 4387:     if (!$start && !$end) {
 4388:         return 'ok';
 4389:     }
 4390:     if (grep/^active$/,@{$status}) {
 4391:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4392:             return 'ok';
 4393:         }
 4394:     }
 4395:     if (grep/^previous$/,@{$status}) {
 4396:         if ($end > $now ) {
 4397:             return 'ok';
 4398:         }
 4399:     }
 4400:     if (grep/^future$/,@{$status}) {
 4401:         if ($start > $now) {
 4402:             return 'ok';
 4403:         }
 4404:     }
 4405:     return; 
 4406: }
 4407: 
 4408: sub parse_portfolio_url {
 4409:     my ($url) = @_;
 4410: 
 4411:     my ($type,$udom,$unum,$group,$file_name);
 4412:     
 4413:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4414: 	$type = 1;
 4415:         $udom = $1;
 4416:         $unum = $2;
 4417:         $file_name = $3;
 4418:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4419: 	$type = 2;
 4420:         $udom = $1;
 4421:         $unum = $2;
 4422:         $group = $3;
 4423:         $file_name = $3.'/'.$4;
 4424:     }
 4425:     if (wantarray) {
 4426: 	return ($type,$udom,$unum,$file_name,$group);
 4427:     }
 4428:     return $type;
 4429: }
 4430: 
 4431: sub is_portfolio_url {
 4432:     my ($url) = @_;
 4433:     return scalar(&parse_portfolio_url($url));
 4434: }
 4435: 
 4436: sub is_portfolio_file {
 4437:     my ($file) = @_;
 4438:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4439:         return 1;
 4440:     }
 4441:     return;
 4442: }
 4443: 
 4444: sub usertools_access {
 4445:     my ($uname,$udom,$tool,$action) = @_;
 4446:     my $access;
 4447:     my %tools = (
 4448:                   aboutme   => 1,
 4449:                   blog      => 1,
 4450:                   portfolio => 1,
 4451:                 );
 4452:     return if (!defined($tools{$tool}));
 4453: 
 4454:     if ((!defined($udom)) || (!defined($uname))) {
 4455:         $udom = $env{'user.domain'};
 4456:         $uname = $env{'user.name'};
 4457:     }
 4458: 
 4459:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4460:         if ($action ne 'reload') {
 4461:             return $env{'environment.availabletools.'.$tool};
 4462:         }
 4463:     }
 4464: 
 4465:     my ($toolstatus,$inststatus);
 4466: 
 4467:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4468:         $toolstatus = $env{'environment.tools.'.$tool};
 4469:         $inststatus = $env{'environment.inststatus'};
 4470:     } else {
 4471:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4472:         $toolstatus = $userenv{'tools.'.$tool};
 4473:         $inststatus = $userenv{'inststatus'};
 4474:     }
 4475: 
 4476:     if ($toolstatus ne '') {
 4477:         if ($toolstatus) {
 4478:             $access = 1;
 4479:         } else {
 4480:             $access = 0;
 4481:         }
 4482:         return $access;
 4483:     }
 4484: 
 4485:     my $is_adv = &is_advanced_user($udom,$uname);
 4486:     my %domdef = &get_domain_defaults($udom);
 4487:     if (ref($domdef{$tool}) eq 'HASH') {
 4488:         if ($is_adv) {
 4489:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4490:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4491:                     $access = 1;
 4492:                 } else {
 4493:                     $access = 0;
 4494:                 }
 4495:                 return $access;
 4496:             }
 4497:         }
 4498:         if ($inststatus ne '') {
 4499:             my ($hasaccess,$hasnoaccess);
 4500:             foreach my $affiliation (split(/:/,$inststatus)) {
 4501:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4502:                     if ($domdef{$tool}{$affiliation}) {
 4503:                         $hasaccess = 1;
 4504:                     } else {
 4505:                         $hasnoaccess = 1;
 4506:                     }
 4507:                 }
 4508:             }
 4509:             if ($hasaccess || $hasnoaccess) {
 4510:                 if ($hasaccess) {
 4511:                     $access = 1;
 4512:                 } elsif ($hasnoaccess) {
 4513:                     $access = 0; 
 4514:                 }
 4515:                 return $access;
 4516:             }
 4517:         } else {
 4518:             if ($domdef{$tool}{'default'} ne '') {
 4519:                 if ($domdef{$tool}{'default'}) {
 4520:                     $access = 1;
 4521:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4522:                     $access = 0;
 4523:                 }
 4524:                 return $access;
 4525:             }
 4526:         }
 4527:     } else {
 4528:         $access = 1;
 4529:         return $access;
 4530:     }
 4531: }
 4532: 
 4533: sub is_advanced_user {
 4534:     my ($udom,$uname) = @_;
 4535:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4536:     my %allroles;
 4537:     my $is_adv;
 4538:     foreach my $role (keys(%roleshash)) {
 4539:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4540:         my $area = '/'.$tdomain.'/'.$trest;
 4541:         if ($sec ne '') {
 4542:             $area .= '/'.$sec;
 4543:         }
 4544:         if (($area ne '') && ($trole ne '')) {
 4545:             my $spec=$trole.'.'.$area;
 4546:             if ($trole =~ /^cr\//) {
 4547:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4548:             } elsif ($trole ne 'gr') {
 4549:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4550:             }
 4551:         }
 4552:     }
 4553:     foreach my $role (keys(%allroles)) {
 4554:         last if ($is_adv);
 4555:         foreach my $item (split(/:/,$allroles{$role})) {
 4556:             if ($item ne '') {
 4557:                 my ($privilege,$restrictions)=split(/&/,$item);
 4558:                 if ($privilege eq 'adv') {
 4559:                     $is_adv = 1;
 4560:                     last;
 4561:                 }
 4562:             }
 4563:         }
 4564:     }
 4565:     return $is_adv;
 4566: }
 4567: 
 4568: # ---------------------------------------------- Custom access rule evaluation
 4569: 
 4570: sub customaccess {
 4571:     my ($priv,$uri)=@_;
 4572:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4573:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4574:     $udom = &LONCAPA::clean_domain($udom);
 4575:     $ucrs = &LONCAPA::clean_username($ucrs);
 4576:     my $access=0;
 4577:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4578: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4579: 	if ($type eq 'user') {
 4580: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4581: 		my ($tdom,$tuname)=split(m{/},$scope);
 4582: 		if ($tdom) {
 4583: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4584: 		}
 4585: 		if ($tuname) {
 4586: 		    if ($tuname ne $env{'user.name'}) { next; }
 4587: 		}
 4588: 		$access=($effect eq 'allow');
 4589: 		last;
 4590: 	    }
 4591: 	} else {
 4592: 	    if ($role) {
 4593: 		if ($role ne $urole) { next; }
 4594: 	    }
 4595: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4596: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4597: 		if ($tdom) {
 4598: 		    if ($tdom ne $udom) { next; }
 4599: 		}
 4600: 		if ($tcrs) {
 4601: 		    if ($tcrs ne $ucrs) { next; }
 4602: 		}
 4603: 		if ($tsec) {
 4604: 		    if ($tsec ne $usec) { next; }
 4605: 		}
 4606: 		$access=($effect eq 'allow');
 4607: 		last;
 4608: 	    }
 4609: 	    if ($realm eq '' && $role eq '') {
 4610: 		$access=($effect eq 'allow');
 4611: 	    }
 4612: 	}
 4613:     }
 4614:     return $access;
 4615: }
 4616: 
 4617: # ------------------------------------------------- Check for a user privilege
 4618: 
 4619: sub allowed {
 4620:     my ($priv,$uri,$symb,$role)=@_;
 4621:     my $ver_orguri=$uri;
 4622:     $uri=&deversion($uri);
 4623:     my $orguri=$uri;
 4624:     $uri=&declutter($uri);
 4625: 
 4626:     if ($priv eq 'evb') {
 4627: # Evade communication block restrictions for specified role in a course
 4628:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4629:             return $1;
 4630:         } else {
 4631:             return;
 4632:         }
 4633:     }
 4634: 
 4635:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4636: # Free bre access to adm and meta resources
 4637:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4638: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4639: 	&& ($priv eq 'bre')) {
 4640: 	return 'F';
 4641:     }
 4642: 
 4643: # Free bre access to user's own portfolio contents
 4644:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4645:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4646: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4647:         my %setters;
 4648:         my ($startblock,$endblock) = 
 4649:             &Apache::loncommon::blockcheck(\%setters,'port');
 4650:         if ($startblock && $endblock) {
 4651:             return 'B';
 4652:         } else {
 4653:             return 'F';
 4654:         }
 4655:     }
 4656: 
 4657: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4658:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4659:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4660:         if (exists($env{'request.course.id'})) {
 4661:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4662:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4663:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4664:                 my $courseprivid=$env{'request.course.id'};
 4665:                 $courseprivid=~s/\_/\//;
 4666:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4667:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4668:                     return $1; 
 4669:                 } else {
 4670:                     if ($env{'request.course.sec'}) {
 4671:                         $courseprivid.='/'.$env{'request.course.sec'};
 4672:                     }
 4673:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4674:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4675:                         return $2;
 4676:                     }
 4677:                 }
 4678:             }
 4679:         }
 4680:     }
 4681: 
 4682: # Free bre to public access
 4683: 
 4684:     if ($priv eq 'bre') {
 4685:         my $copyright=&metadata($uri,'copyright');
 4686: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4687:            return 'F'; 
 4688:         }
 4689:         if ($copyright eq 'priv') {
 4690:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4691: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4692: 		return '';
 4693:             }
 4694:         }
 4695:         if ($copyright eq 'domain') {
 4696:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4697: 	    unless (($env{'user.domain'} eq $1) ||
 4698:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4699: 		return '';
 4700:             }
 4701:         }
 4702:         if ($env{'request.role'}=~ /li\.\//) {
 4703:             # Library role, so allow browsing of resources in this domain.
 4704:             return 'F';
 4705:         }
 4706:         if ($copyright eq 'custom') {
 4707: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4708:         }
 4709:     }
 4710:     # Domain coordinator is trying to create a course
 4711:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4712:         # uri is the requested domain in this case.
 4713:         # comparison to 'request.role.domain' shows if the user has selected
 4714:         # a role of dc for the domain in question.
 4715:         return 'F' if ($uri eq $env{'request.role.domain'});
 4716:     }
 4717: 
 4718:     my $thisallowed='';
 4719:     my $statecond=0;
 4720:     my $courseprivid='';
 4721: 
 4722: # Course
 4723: 
 4724:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4725:        $thisallowed.=$1;
 4726:     }
 4727: 
 4728: # Domain
 4729: 
 4730:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4731:        =~/\Q$priv\E\&([^\:]*)/) {
 4732:        $thisallowed.=$1;
 4733:     }
 4734: 
 4735: # Course: uri itself is a course
 4736:     my $courseuri=$uri;
 4737:     $courseuri=~s/\_(\d)/\/$1/;
 4738:     $courseuri=~s/^([^\/])/\/$1/;
 4739: 
 4740:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4741:        =~/\Q$priv\E\&([^\:]*)/) {
 4742:        $thisallowed.=$1;
 4743:     }
 4744: 
 4745: # URI is an uploaded document for this course, default permissions don't matter
 4746: # not allowing 'edit' access (editupload) to uploaded course docs
 4747:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4748: 	$thisallowed='';
 4749:         my ($match)=&is_on_map($uri);
 4750:         if ($match) {
 4751:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4752:                   =~/\Q$priv\E\&([^\:]*)/) {
 4753:                 $thisallowed.=$1;
 4754:             }
 4755:         } else {
 4756:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4757:             if ($refuri) {
 4758:                 if ($refuri =~ m|^/adm/|) {
 4759:                     $thisallowed='F';
 4760:                 } else {
 4761:                     $refuri=&declutter($refuri);
 4762:                     my ($match) = &is_on_map($refuri);
 4763:                     if ($match) {
 4764:                         $thisallowed='F';
 4765:                     }
 4766:                 }
 4767:             }
 4768:         }
 4769:     }
 4770: 
 4771:     if ($priv eq 'bre'
 4772: 	&& $thisallowed ne 'F' 
 4773: 	&& $thisallowed ne '2'
 4774: 	&& &is_portfolio_url($uri)) {
 4775: 	$thisallowed = &portfolio_access($uri);
 4776:     }
 4777:     
 4778: # Full access at system, domain or course-wide level? Exit.
 4779:     if ($thisallowed=~/F/) {
 4780: 	return 'F';
 4781:     }
 4782: 
 4783: # If this is generating or modifying users, exit with special codes
 4784: 
 4785:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4786: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4787: 	    my ($audom,$auname)=split('/',$uri);
 4788: # no author name given, so this just checks on the general right to make a co-author in this domain
 4789: 	    unless ($auname) { return $thisallowed; }
 4790: # an author name is given, so we are about to actually make a co-author for a certain account
 4791: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4792: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4793: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4794: 	}
 4795: 	return $thisallowed;
 4796:     }
 4797: #
 4798: # Gathered so far: system, domain and course wide privileges
 4799: #
 4800: # Course: See if uri or referer is an individual resource that is part of 
 4801: # the course
 4802: 
 4803:     if ($env{'request.course.id'}) {
 4804: 
 4805:        $courseprivid=$env{'request.course.id'};
 4806:        if ($env{'request.course.sec'}) {
 4807:           $courseprivid.='/'.$env{'request.course.sec'};
 4808:        }
 4809:        $courseprivid=~s/\_/\//;
 4810:        my $checkreferer=1;
 4811:        my ($match,$cond)=&is_on_map($uri);
 4812:        if ($match) {
 4813:            $statecond=$cond;
 4814:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4815:                =~/\Q$priv\E\&([^\:]*)/) {
 4816:                $thisallowed.=$1;
 4817:                $checkreferer=0;
 4818:            }
 4819:        }
 4820:        
 4821:        if ($checkreferer) {
 4822: 	  my $refuri=$env{'httpref.'.$orguri};
 4823:             unless ($refuri) {
 4824:                 foreach my $key (keys(%env)) {
 4825: 		    if ($key=~/^httpref\..*\*/) {
 4826: 			my $pattern=$key;
 4827:                         $pattern=~s/^httpref\.\/res\///;
 4828:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4829:                         $pattern=~s/\//\\\//g;
 4830:                         if ($orguri=~/$pattern/) {
 4831: 			    $refuri=$env{$key};
 4832:                         }
 4833:                     }
 4834:                 }
 4835:             }
 4836: 
 4837:          if ($refuri) { 
 4838: 	  $refuri=&declutter($refuri);
 4839:           my ($match,$cond)=&is_on_map($refuri);
 4840:             if ($match) {
 4841:               my $refstatecond=$cond;
 4842:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4843:                   =~/\Q$priv\E\&([^\:]*)/) {
 4844:                   $thisallowed.=$1;
 4845:                   $uri=$refuri;
 4846:                   $statecond=$refstatecond;
 4847:               }
 4848:           }
 4849:         }
 4850:        }
 4851:    }
 4852: 
 4853: #
 4854: # Gathered now: all privileges that could apply, and condition number
 4855: # 
 4856: #
 4857: # Full or no access?
 4858: #
 4859: 
 4860:     if ($thisallowed=~/F/) {
 4861: 	return 'F';
 4862:     }
 4863: 
 4864:     unless ($thisallowed) {
 4865:         return '';
 4866:     }
 4867: 
 4868: # Restrictions exist, deal with them
 4869: #
 4870: #   C:according to course preferences
 4871: #   R:according to resource settings
 4872: #   L:unless locked
 4873: #   X:according to user session state
 4874: #
 4875: 
 4876: # Possibly locked functionality, check all courses
 4877: # Locks might take effect only after 10 minutes cache expiration for other
 4878: # courses, and 2 minutes for current course
 4879: 
 4880:     my $envkey;
 4881:     if ($thisallowed=~/L/) {
 4882:         foreach $envkey (keys %env) {
 4883:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4884:                my $courseid=$2;
 4885:                my $roleid=$1.'.'.$2;
 4886:                $courseid=~s/^\///;
 4887:                my $expiretime=600;
 4888:                if ($env{'request.role'} eq $roleid) {
 4889: 		  $expiretime=120;
 4890:                }
 4891: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4892:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4893:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4894: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4895:                }
 4896:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4897:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4898: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4899:                        &log($env{'user.domain'},$env{'user.name'},
 4900:                             $env{'user.home'},
 4901:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4902:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4903:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4904: 		       return '';
 4905:                    }
 4906:                }
 4907:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4908:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4909: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4910:                        &log($env{'user.domain'},$env{'user.name'},
 4911:                             $env{'user.home'},
 4912:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4913:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4914:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4915: 		       return '';
 4916:                    }
 4917:                }
 4918: 	   }
 4919:        }
 4920:     }
 4921:    
 4922: #
 4923: # Rest of the restrictions depend on selected course
 4924: #
 4925: 
 4926:     unless ($env{'request.course.id'}) {
 4927: 	if ($thisallowed eq 'A') {
 4928: 	    return 'A';
 4929:         } elsif ($thisallowed eq 'B') {
 4930:             return 'B';
 4931: 	} else {
 4932: 	    return '1';
 4933: 	}
 4934:     }
 4935: 
 4936: #
 4937: # Now user is definitely in a course
 4938: #
 4939: 
 4940: 
 4941: # Course preferences
 4942: 
 4943:    if ($thisallowed=~/C/) {
 4944:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4945:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4946:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4947: 	   =~/\Q$rolecode\E/) {
 4948: 	   if ($priv ne 'pch') { 
 4949: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4950: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4951: 			$env{'request.course.id'});
 4952: 	   }
 4953:            return '';
 4954:        }
 4955: 
 4956:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4957: 	   =~/\Q$unamedom\E/) {
 4958: 	   if ($priv ne 'pch') { 
 4959: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4960: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4961: 			$env{'request.course.id'});
 4962: 	   }
 4963:            return '';
 4964:        }
 4965:    }
 4966: 
 4967: # Resource preferences
 4968: 
 4969:    if ($thisallowed=~/R/) {
 4970:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4971:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4972: 	   if ($priv ne 'pch') { 
 4973: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4974: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4975: 	   }
 4976: 	   return '';
 4977:        }
 4978:    }
 4979: 
 4980: # Restricted by state or randomout?
 4981: 
 4982:    if ($thisallowed=~/X/) {
 4983:       if ($env{'acc.randomout'}) {
 4984: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4985:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4986:             return ''; 
 4987:          }
 4988:       }
 4989:       if (&condval($statecond)) {
 4990: 	 return '2';
 4991:       } else {
 4992:          return '';
 4993:       }
 4994:    }
 4995: 
 4996:     if ($thisallowed eq 'A') {
 4997: 	return 'A';
 4998:     } elsif ($thisallowed eq 'B') {
 4999:         return 'B';
 5000:     }
 5001:    return 'F';
 5002: }
 5003: 
 5004: sub split_uri_for_cond {
 5005:     my $uri=&deversion(&declutter(shift));
 5006:     my @uriparts=split(/\//,$uri);
 5007:     my $filename=pop(@uriparts);
 5008:     my $pathname=join('/',@uriparts);
 5009:     return ($pathname,$filename);
 5010: }
 5011: # --------------------------------------------------- Is a resource on the map?
 5012: 
 5013: sub is_on_map {
 5014:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5015:     #Trying to find the conditional for the file
 5016:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5017: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5018:     if ($match) {
 5019: 	return (1,$1);
 5020:     } else {
 5021: 	return (0,0);
 5022:     }
 5023: }
 5024: 
 5025: # --------------------------------------------------------- Get symb from alias
 5026: 
 5027: sub get_symb_from_alias {
 5028:     my $symb=shift;
 5029:     my ($map,$resid,$url)=&decode_symb($symb);
 5030: # Already is a symb
 5031:     if ($url) { return $symb; }
 5032: # Must be an alias
 5033:     my $aliassymb='';
 5034:     my %bighash;
 5035:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5036:                             &GDBM_READER(),0640)) {
 5037:         my $rid=$bighash{'mapalias_'.$symb};
 5038: 	if ($rid) {
 5039: 	    my ($mapid,$resid)=split(/\./,$rid);
 5040: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5041: 				    $resid,$bighash{'src_'.$rid});
 5042: 	}
 5043:         untie %bighash;
 5044:     }
 5045:     return $aliassymb;
 5046: }
 5047: 
 5048: # ----------------------------------------------------------------- Define Role
 5049: 
 5050: sub definerole {
 5051:   if (allowed('mcr','/')) {
 5052:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5053:     foreach my $role (split(':',$sysrole)) {
 5054: 	my ($crole,$cqual)=split(/\&/,$role);
 5055:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5056:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5057: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5058:                return "refused:s:$crole&$cqual"; 
 5059:             }
 5060:         }
 5061:     }
 5062:     foreach my $role (split(':',$domrole)) {
 5063: 	my ($crole,$cqual)=split(/\&/,$role);
 5064:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5065:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5066: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5067:                return "refused:d:$crole&$cqual"; 
 5068:             }
 5069:         }
 5070:     }
 5071:     foreach my $role (split(':',$courole)) {
 5072: 	my ($crole,$cqual)=split(/\&/,$role);
 5073:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5074:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5075: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5076:                return "refused:c:$crole&$cqual"; 
 5077:             }
 5078:         }
 5079:     }
 5080:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5081:                 "$env{'user.domain'}:$env{'user.name'}:".
 5082: 	        "rolesdef_$rolename=".
 5083:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5084:     return reply($command,$env{'user.home'});
 5085:   } else {
 5086:     return 'refused';
 5087:   }
 5088: }
 5089: 
 5090: # ---------------- Make a metadata query against the network of library servers
 5091: 
 5092: sub metadata_query {
 5093:     my ($query,$custom,$customshow,$server_array)=@_;
 5094:     my %rhash;
 5095:     my %libserv = &all_library();
 5096:     my @server_list = (defined($server_array) ? @$server_array
 5097:                                               : keys(%libserv) );
 5098:     for my $server (@server_list) {
 5099: 	unless ($custom or $customshow) {
 5100: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5101: 	    $rhash{$server}=$reply;
 5102: 	}
 5103: 	else {
 5104: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5105: 			     &escape($custom).':'.&escape($customshow),
 5106: 			     $server);
 5107: 	    $rhash{$server}=$reply;
 5108: 	}
 5109:     }
 5110:     return \%rhash;
 5111: }
 5112: 
 5113: # ----------------------------------------- Send log queries and wait for reply
 5114: 
 5115: sub log_query {
 5116:     my ($uname,$udom,$query,%filters)=@_;
 5117:     my $uhome=&homeserver($uname,$udom);
 5118:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5119:     my $uhost=&hostname($uhome);
 5120:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5121:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5122:                        $uhome);
 5123:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5124:     return get_query_reply($queryid);
 5125: }
 5126: 
 5127: # -------------------------- Update MySQL table for portfolio file
 5128: 
 5129: sub update_portfolio_table {
 5130:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5131:     if ($group ne '') {
 5132:         $file_name =~s /^\Q$group\E//;
 5133:     }
 5134:     my $homeserver = &homeserver($uname,$udom);
 5135:     my $queryid=
 5136:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5137:                ':'.&escape($file_name).':'.$action,$homeserver);
 5138:     my $reply = &get_query_reply($queryid);
 5139:     return $reply;
 5140: }
 5141: 
 5142: # -------------------------- Update MySQL allusers table
 5143: 
 5144: sub update_allusers_table {
 5145:     my ($uname,$udom,$names) = @_;
 5146:     my $homeserver = &homeserver($uname,$udom);
 5147:     my $queryid=
 5148:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5149:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5150:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5151:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5152:                'generation='.&escape($names->{'generation'}).'%%'.
 5153:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5154:                'id='.&escape($names->{'id'}),$homeserver);
 5155:     my $reply = &get_query_reply($queryid);
 5156:     return $reply;
 5157: }
 5158: 
 5159: # ------- Request retrieval of institutional classlists for course(s)
 5160: 
 5161: sub fetch_enrollment_query {
 5162:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5163:     my $homeserver;
 5164:     my $maxtries = 1;
 5165:     if ($context eq 'automated') {
 5166:         $homeserver = $perlvar{'lonHostID'};
 5167:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5168:     } else {
 5169:         $homeserver = &homeserver($cnum,$dom);
 5170:     }
 5171:     my $host=&hostname($homeserver);
 5172:     my $cmd = '';
 5173:     foreach my $affiliate (keys %{$affiliatesref}) {
 5174:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5175:     }
 5176:     $cmd =~ s/%%$//;
 5177:     $cmd = &escape($cmd);
 5178:     my $query = 'fetchenrollment';
 5179:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5180:     unless ($queryid=~/^\Q$host\E\_/) { 
 5181:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5182:         return 'error: '.$queryid;
 5183:     }
 5184:     my $reply = &get_query_reply($queryid);
 5185:     my $tries = 1;
 5186:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5187:         $reply = &get_query_reply($queryid);
 5188:         $tries ++;
 5189:     }
 5190:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5191:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5192:     } else {
 5193:         my @responses = split(/:/,$reply);
 5194:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5195:             foreach my $line (@responses) {
 5196:                 my ($key,$value) = split(/=/,$line,2);
 5197:                 $$replyref{$key} = $value;
 5198:             }
 5199:         } else {
 5200:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5201:             foreach my $line (@responses) {
 5202:                 my ($key,$value) = split(/=/,$line);
 5203:                 $$replyref{$key} = $value;
 5204:                 if ($value > 0) {
 5205:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5206:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5207:                         my $destname = $pathname.'/'.$filename;
 5208:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5209:                         if ($xml_classlist =~ /^error/) {
 5210:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5211:                         } else {
 5212:                             if ( open(FILE,">$destname") ) {
 5213:                                 print FILE &unescape($xml_classlist);
 5214:                                 close(FILE);
 5215:                             } else {
 5216:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5217:                             }
 5218:                         }
 5219:                     }
 5220:                 }
 5221:             }
 5222:         }
 5223:         return 'ok';
 5224:     }
 5225:     return 'error';
 5226: }
 5227: 
 5228: sub get_query_reply {
 5229:     my $queryid=shift;
 5230:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5231:     my $reply='';
 5232:     for (1..100) {
 5233: 	sleep 2;
 5234:         if (-e $replyfile.'.end') {
 5235: 	    if (open(my $fh,$replyfile)) {
 5236: 		$reply = join('',<$fh>);
 5237: 		close($fh);
 5238: 	   } else { return 'error: reply_file_error'; }
 5239:            return &unescape($reply);
 5240: 	}
 5241:     }
 5242:     return 'timeout:'.$queryid;
 5243: }
 5244: 
 5245: sub courselog_query {
 5246: #
 5247: # possible filters:
 5248: # url: url or symb
 5249: # username
 5250: # domain
 5251: # action: view, submit, grade
 5252: # start: timestamp
 5253: # end: timestamp
 5254: #
 5255:     my (%filters)=@_;
 5256:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5257:     if ($filters{'url'}) {
 5258: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5259:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5260:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5261:     }
 5262:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5263:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5264:     return &log_query($cname,$cdom,'courselog',%filters);
 5265: }
 5266: 
 5267: sub userlog_query {
 5268: #
 5269: # possible filters:
 5270: # action: log check role
 5271: # start: timestamp
 5272: # end: timestamp
 5273: #
 5274:     my ($uname,$udom,%filters)=@_;
 5275:     return &log_query($uname,$udom,'userlog',%filters);
 5276: }
 5277: 
 5278: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5279: 
 5280: sub auto_run {
 5281:     my ($cnum,$cdom) = @_;
 5282:     my $response = 0;
 5283:     my $settings;
 5284:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5285:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5286:         $settings = $domconfig{'autoenroll'};
 5287:         if ($settings->{'run'} eq '1') {
 5288:             $response = 1;
 5289:         }
 5290:     } else {
 5291:         my $homeserver;
 5292:         if (&is_course($cdom,$cnum)) {
 5293:             $homeserver = &homeserver($cnum,$cdom);
 5294:         } else {
 5295:             $homeserver = &domain($cdom,'primary');
 5296:         }
 5297:         if ($homeserver ne 'no_host') {
 5298:             $response = &reply('autorun:'.$cdom,$homeserver);
 5299:         }
 5300:     }
 5301:     return $response;
 5302: }
 5303: 
 5304: sub auto_get_sections {
 5305:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5306:     my $homeserver = &homeserver($cnum,$cdom);
 5307:     my @secs = ();
 5308:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5309:     unless ($response eq 'refused') {
 5310:         @secs = split(/:/,$response);
 5311:     }
 5312:     return @secs;
 5313: }
 5314: 
 5315: sub auto_new_course {
 5316:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5317:     my $homeserver = &homeserver($cnum,$cdom);
 5318:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5319:     return $response;
 5320: }
 5321: 
 5322: sub auto_validate_courseID {
 5323:     my ($cnum,$cdom,$inst_course_id) = @_;
 5324:     my $homeserver = &homeserver($cnum,$cdom);
 5325:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5326:     return $response;
 5327: }
 5328: 
 5329: sub auto_create_password {
 5330:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5331:     my ($homeserver,$response);
 5332:     my $create_passwd = 0;
 5333:     my $authchk = '';
 5334:     if ($udom =~ /^$match_domain$/) {
 5335:         $homeserver = &domain($udom,'primary');
 5336:     }
 5337:     if ($homeserver eq '') {
 5338:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5339:             $homeserver = &homeserver($cnum,$cdom);
 5340:         }
 5341:     }
 5342:     if ($homeserver eq '') {
 5343:         $authchk = 'nodomain';
 5344:     } else {
 5345:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5346:         if ($response eq 'refused') {
 5347:             $authchk = 'refused';
 5348:         } else {
 5349:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5350:         }
 5351:     }
 5352:     return ($authparam,$create_passwd,$authchk);
 5353: }
 5354: 
 5355: sub auto_photo_permission {
 5356:     my ($cnum,$cdom,$students) = @_;
 5357:     my $homeserver = &homeserver($cnum,$cdom);
 5358:     my ($outcome,$perm_reqd,$conditions) = 
 5359: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5360:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5361: 	return (undef,undef);
 5362:     }
 5363:     return ($outcome,$perm_reqd,$conditions);
 5364: }
 5365: 
 5366: sub auto_checkphotos {
 5367:     my ($uname,$udom,$pid) = @_;
 5368:     my $homeserver = &homeserver($uname,$udom);
 5369:     my ($result,$resulttype);
 5370:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5371: 				   &escape($uname).':'.&escape($pid),
 5372: 				   $homeserver));
 5373:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5374: 	return (undef,undef);
 5375:     }
 5376:     if ($outcome) {
 5377:         ($result,$resulttype) = split(/:/,$outcome);
 5378:     } 
 5379:     return ($result,$resulttype);
 5380: }
 5381: 
 5382: sub auto_photochoice {
 5383:     my ($cnum,$cdom) = @_;
 5384:     my $homeserver = &homeserver($cnum,$cdom);
 5385:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5386: 						       &escape($cdom),
 5387: 						       $homeserver)));
 5388:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5389: 	return (undef,undef);
 5390:     }
 5391:     return ($update,$comment);
 5392: }
 5393: 
 5394: sub auto_photoupdate {
 5395:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5396:     my $homeserver = &homeserver($cnum,$dom);
 5397:     my $host=&hostname($homeserver);
 5398:     my $cmd = '';
 5399:     my $maxtries = 1;
 5400:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5401:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5402:     }
 5403:     $cmd =~ s/%%$//;
 5404:     $cmd = &escape($cmd);
 5405:     my $query = 'institutionalphotos';
 5406:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5407:     unless ($queryid=~/^\Q$host\E\_/) {
 5408:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5409:         return 'error: '.$queryid;
 5410:     }
 5411:     my $reply = &get_query_reply($queryid);
 5412:     my $tries = 1;
 5413:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5414:         $reply = &get_query_reply($queryid);
 5415:         $tries ++;
 5416:     }
 5417:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5418:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5419:     } else {
 5420:         my @responses = split(/:/,$reply);
 5421:         my $outcome = shift(@responses); 
 5422:         foreach my $item (@responses) {
 5423:             my ($key,$value) = split(/=/,$item);
 5424:             $$photo{$key} = $value;
 5425:         }
 5426:         return $outcome;
 5427:     }
 5428:     return 'error';
 5429: }
 5430: 
 5431: sub auto_instcode_format {
 5432:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5433: 	$cat_order) = @_;
 5434:     my $courses = '';
 5435:     my @homeservers;
 5436:     if ($caller eq 'global') {
 5437: 	my %servers = &get_servers($codedom,'library');
 5438: 	foreach my $tryserver (keys(%servers)) {
 5439: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5440: 		push(@homeservers,$tryserver);
 5441: 	    }
 5442:         }
 5443:     } else {
 5444:         push(@homeservers,&homeserver($caller,$codedom));
 5445:     }
 5446:     foreach my $code (keys(%{$instcodes})) {
 5447:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5448:     }
 5449:     chop($courses);
 5450:     my $ok_response = 0;
 5451:     my $response;
 5452:     while (@homeservers > 0 && $ok_response == 0) {
 5453:         my $server = shift(@homeservers); 
 5454:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5455:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5456:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5457: 		split(/:/,$response);
 5458:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5459:             push(@{$codetitles},&str2array($codetitles_str));
 5460:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5461:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5462:             $ok_response = 1;
 5463:         }
 5464:     }
 5465:     if ($ok_response) {
 5466:         return 'ok';
 5467:     } else {
 5468:         return $response;
 5469:     }
 5470: }
 5471: 
 5472: sub auto_instcode_defaults {
 5473:     my ($domain,$returnhash,$code_order) = @_;
 5474:     my @homeservers;
 5475: 
 5476:     my %servers = &get_servers($domain,'library');
 5477:     foreach my $tryserver (keys(%servers)) {
 5478: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5479: 	    push(@homeservers,$tryserver);
 5480: 	}
 5481:     }
 5482: 
 5483:     my $response;
 5484:     foreach my $server (@homeservers) {
 5485:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5486:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5487: 	
 5488: 	foreach my $pair (split(/\&/,$response)) {
 5489: 	    my ($name,$value)=split(/\=/,$pair);
 5490: 	    if ($name eq 'code_order') {
 5491: 		@{$code_order} = split(/\&/,&unescape($value));
 5492: 	    } else {
 5493: 		$returnhash->{&unescape($name)}=&unescape($value);
 5494: 	    }
 5495: 	}
 5496: 	return 'ok';
 5497:     }
 5498: 
 5499:     return $response;
 5500: } 
 5501: 
 5502: sub auto_validate_class_sec {
 5503:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5504:     my $homeserver = &homeserver($cnum,$cdom);
 5505:     my $ownerlist;
 5506:     if (ref($owners) eq 'ARRAY') {
 5507:         $ownerlist = join(',',@{$owners});
 5508:     } else {
 5509:         $ownerlist = $owners;
 5510:     }
 5511:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5512:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5513:     return $response;
 5514: }
 5515: 
 5516: # ------------------------------------------------------- Course Group routines
 5517: 
 5518: sub get_coursegroups {
 5519:     my ($cdom,$cnum,$group,$namespace) = @_;
 5520:     return(&dump($namespace,$cdom,$cnum,$group));
 5521: }
 5522: 
 5523: sub modify_coursegroup {
 5524:     my ($cdom,$cnum,$groupsettings) = @_;
 5525:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5526: }
 5527: 
 5528: sub toggle_coursegroup_status {
 5529:     my ($cdom,$cnum,$group,$action) = @_;
 5530:     my ($from_namespace,$to_namespace);
 5531:     if ($action eq 'delete') {
 5532:         $from_namespace = 'coursegroups';
 5533:         $to_namespace = 'deleted_groups';
 5534:     } else {
 5535:         $from_namespace = 'deleted_groups';
 5536:         $to_namespace = 'coursegroups';
 5537:     }
 5538:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5539:     if (my $tmp = &error(%curr_group)) {
 5540:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5541:         return ('read error',$tmp);
 5542:     } else {
 5543:         my %savedsettings = %curr_group; 
 5544:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5545:         my $deloutcome;
 5546:         if ($result eq 'ok') {
 5547:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5548:         } else {
 5549:             return ('write error',$result);
 5550:         }
 5551:         if ($deloutcome eq 'ok') {
 5552:             return 'ok';
 5553:         } else {
 5554:             return ('delete error',$deloutcome);
 5555:         }
 5556:     }
 5557: }
 5558: 
 5559: sub modify_group_roles {
 5560:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5561:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5562:     my $role = 'gr/'.&escape($userprivs);
 5563:     my ($uname,$udom) = split(/:/,$user);
 5564:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5565:     if ($result eq 'ok') {
 5566:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5567:     }
 5568:     return $result;
 5569: }
 5570: 
 5571: sub modify_coursegroup_membership {
 5572:     my ($cdom,$cnum,$membership) = @_;
 5573:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5574:     return $result;
 5575: }
 5576: 
 5577: sub get_active_groups {
 5578:     my ($udom,$uname,$cdom,$cnum) = @_;
 5579:     my $now = time;
 5580:     my %groups = ();
 5581:     foreach my $key (keys(%env)) {
 5582:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5583:             my ($start,$end) = split(/\./,$env{$key});
 5584:             if (($end!=0) && ($end<$now)) { next; }
 5585:             if (($start!=0) && ($start>$now)) { next; }
 5586:             if ($1 eq $cdom && $2 eq $cnum) {
 5587:                 $groups{$3} = $env{$key} ;
 5588:             }
 5589:         }
 5590:     }
 5591:     return %groups;
 5592: }
 5593: 
 5594: sub get_group_membership {
 5595:     my ($cdom,$cnum,$group) = @_;
 5596:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5597: }
 5598: 
 5599: sub get_users_groups {
 5600:     my ($udom,$uname,$courseid) = @_;
 5601:     my @usersgroups;
 5602:     my $cachetime=1800;
 5603: 
 5604:     my $hashid="$udom:$uname:$courseid";
 5605:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5606:     if (defined($cached)) {
 5607:         @usersgroups = split(/:/,$grouplist);
 5608:     } else {  
 5609:         $grouplist = '';
 5610:         my $courseurl = &courseid_to_courseurl($courseid);
 5611:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5612:         my $access_end = $env{'course.'.$courseid.
 5613:                               '.default_enrollment_end_date'};
 5614:         my $now = time;
 5615:         foreach my $key (keys(%roleshash)) {
 5616:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5617:                 my $group = $1;
 5618:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5619:                     my $start = $2;
 5620:                     my $end = $1;
 5621:                     if ($start == -1) { next; } # deleted from group
 5622:                     if (($start!=0) && ($start>$now)) { next; }
 5623:                     if (($end!=0) && ($end<$now)) {
 5624:                         if ($access_end && $access_end < $now) {
 5625:                             if ($access_end - $end < 86400) {
 5626:                                 push(@usersgroups,$group);
 5627:                             }
 5628:                         }
 5629:                         next;
 5630:                     }
 5631:                     push(@usersgroups,$group);
 5632:                 }
 5633:             }
 5634:         }
 5635:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5636:         $grouplist = join(':',@usersgroups);
 5637:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5638:     }
 5639:     return @usersgroups;
 5640: }
 5641: 
 5642: sub devalidate_getgroups_cache {
 5643:     my ($udom,$uname,$cdom,$cnum)=@_;
 5644:     my $courseid = $cdom.'_'.$cnum;
 5645: 
 5646:     my $hashid="$udom:$uname:$courseid";
 5647:     &devalidate_cache_new('getgroups',$hashid);
 5648: }
 5649: 
 5650: # ------------------------------------------------------------------ Plain Text
 5651: 
 5652: sub plaintext {
 5653:     my ($short,$type,$cid) = @_;
 5654:     if ($short =~ /^cr/) {
 5655: 	return (split('/',$short))[-1];
 5656:     }
 5657:     if (!defined($cid)) {
 5658:         $cid = $env{'request.course.id'};
 5659:     }
 5660:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5661:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5662:                                           '.plaintext'});
 5663:     }
 5664:     my %rolenames = (
 5665:                       Course => 'std',
 5666:                       Group => 'alt1',
 5667:                     );
 5668:     if (defined($type) && 
 5669:          defined($rolenames{$type}) && 
 5670:          defined($prp{$short}{$rolenames{$type}})) {
 5671:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5672:     } else {
 5673:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5674:     }
 5675: }
 5676: 
 5677: # ----------------------------------------------------------------- Assign Role
 5678: 
 5679: sub assignrole {
 5680:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5681:         $context)=@_;
 5682:     my $mrole;
 5683:     if ($role =~ /^cr\//) {
 5684:         my $cwosec=$url;
 5685:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5686: 	unless (&allowed('ccr',$cwosec)) {
 5687:            &logthis('Refused custom assignrole: '.
 5688:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5689: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5690:            return 'refused'; 
 5691:         }
 5692:         $mrole='cr';
 5693:     } elsif ($role =~ /^gr\//) {
 5694:         my $cwogrp=$url;
 5695:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5696:         unless (&allowed('mdg',$cwogrp)) {
 5697:             &logthis('Refused group assignrole: '.
 5698:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5699:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5700:             return 'refused';
 5701:         }
 5702:         $mrole='gr';
 5703:     } else {
 5704:         my $cwosec=$url;
 5705:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5706:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5707:             my $refused;
 5708:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5709:                 if (!(&allowed('c'.$role,$url))) {
 5710:                     $refused = 1;
 5711:                 }
 5712:             } else {
 5713:                 $refused = 1;
 5714:             }
 5715:             if ($refused) {
 5716:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5717:                     $refused = '';
 5718:                 } else {
 5719:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5720:                              ' '.$role.' '.$end.' '.$start.' by '.
 5721: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5722:                     return 'refused';
 5723:                 }
 5724:             }
 5725:         }
 5726:         $mrole=$role;
 5727:     }
 5728:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5729:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5730:     if ($end) { $command.='_'.$end; }
 5731:     if ($start) {
 5732: 	if ($end) { 
 5733:            $command.='_'.$start; 
 5734:         } else {
 5735:            $command.='_0_'.$start;
 5736:         }
 5737:     }
 5738:     my $origstart = $start;
 5739:     my $origend = $end;
 5740:     my $delflag;
 5741: # actually delete
 5742:     if ($deleteflag) {
 5743: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5744: # modify command to delete the role
 5745:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5746:                 "$udom:$uname:$url".'_'."$mrole";
 5747: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5748: # set start and finish to negative values for userrolelog
 5749:            $start=-1;
 5750:            $end=-1;
 5751:            $delflag = 1;
 5752:         }
 5753:     }
 5754: # send command
 5755:     my $answer=&reply($command,&homeserver($uname,$udom));
 5756: # log new user role if status is ok
 5757:     if ($answer eq 'ok') {
 5758: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5759: # for course roles, perform group memberships changes triggered by role change.
 5760:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5761:         unless ($role =~ /^gr/) {
 5762:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5763:                                              $origstart,$selfenroll,$context);
 5764:         }
 5765:     }
 5766:     return $answer;
 5767: }
 5768: 
 5769: # -------------------------------------------------- Modify user authentication
 5770: # Overrides without validation
 5771: 
 5772: sub modifyuserauth {
 5773:     my ($udom,$uname,$umode,$upass)=@_;
 5774:     my $uhome=&homeserver($uname,$udom);
 5775:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5776:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5777:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5778:              ' in domain '.$env{'request.role.domain'});  
 5779:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5780: 		     &escape($upass),$uhome);
 5781:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5782:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5783:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5784:     &log($udom,,$uname,$uhome,
 5785:         'Authentication changed by '.$env{'user.domain'}.', '.
 5786:                                      $env{'user.name'}.', '.$umode.
 5787:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5788:     unless ($reply eq 'ok') {
 5789:         &logthis('Authentication mode error: '.$reply);
 5790: 	return 'error: '.$reply;
 5791:     }   
 5792:     return 'ok';
 5793: }
 5794: 
 5795: # --------------------------------------------------------------- Modify a user
 5796: 
 5797: sub modifyuser {
 5798:     my ($udom,    $uname, $uid,
 5799:         $umode,   $upass, $first,
 5800:         $middle,  $last,  $gene,
 5801:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5802:     $udom= &LONCAPA::clean_domain($udom);
 5803:     $uname=&LONCAPA::clean_username($uname);
 5804:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5805:              $umode.', '.$first.', '.$middle.', '.
 5806: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5807:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5808:                                      ' desiredhome not specified'). 
 5809:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5810:              ' in domain '.$env{'request.role.domain'});
 5811:     my $uhome=&homeserver($uname,$udom,'true');
 5812: # ----------------------------------------------------------------- Create User
 5813:     if (($uhome eq 'no_host') && 
 5814: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5815:         my $unhome='';
 5816:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5817:             $unhome = $desiredhome;
 5818: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5819: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5820:         } else { # load balancing routine for determining $unhome
 5821:             my $loadm=10000000;
 5822: 	    my %servers = &get_servers($udom,'library');
 5823: 	    foreach my $tryserver (keys(%servers)) {
 5824: 		my $answer=reply('load',$tryserver);
 5825: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5826: 		    $loadm=$answer;
 5827: 		    $unhome=$tryserver;
 5828: 		}
 5829: 	    }
 5830:         }
 5831:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5832: 	    return 'error: unable to find a home server for '.$uname.
 5833:                    ' in domain '.$udom;
 5834:         }
 5835:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5836:                          &escape($upass),$unhome);
 5837: 	unless ($reply eq 'ok') {
 5838:             return 'error: '.$reply;
 5839:         }   
 5840:         $uhome=&homeserver($uname,$udom,'true');
 5841:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5842: 	    return 'error: unable verify users home machine.';
 5843:         }
 5844:     }   # End of creation of new user
 5845: # ---------------------------------------------------------------------- Add ID
 5846:     if ($uid) {
 5847:        $uid=~tr/A-Z/a-z/;
 5848:        my %uidhash=&idrget($udom,$uname);
 5849:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5850:          && (!$forceid)) {
 5851: 	  unless ($uid eq $uidhash{$uname}) {
 5852: 	      return 'error: user id "'.$uid.'" does not match '.
 5853:                   'current user id "'.$uidhash{$uname}.'".';
 5854:           }
 5855:        } else {
 5856: 	  &idput($udom,($uname => $uid));
 5857:        }
 5858:     }
 5859: # -------------------------------------------------------------- Add names, etc
 5860:     my @tmp=&get('environment',
 5861: 		   ['firstname','middlename','lastname','generation','id',
 5862:                     'permanentemail','inststatus'],
 5863: 		   $udom,$uname);
 5864:     my %names;
 5865:     if ($tmp[0] =~ m/^error:.*/) { 
 5866:         %names=(); 
 5867:     } else {
 5868:         %names = @tmp;
 5869:     }
 5870: #
 5871: # Make sure to not trash student environment if instructor does not bother
 5872: # to supply name and email information
 5873: #
 5874:     if ($first)  { $names{'firstname'}  = $first; }
 5875:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5876:     if ($last)   { $names{'lastname'}   = $last; }
 5877:     if (defined($gene))   { $names{'generation'} = $gene; }
 5878:     if ($email) {
 5879:        $email=~s/[^\w\@\.\-\,]//gs;
 5880:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5881:     }
 5882:     if ($uid) { $names{'id'}  = $uid; }
 5883:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5884:     my $reply = &put('environment', \%names, $udom,$uname);
 5885:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5886:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5887:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5888:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5889:                  $umode.', '.$first.', '.$middle.', '.
 5890: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5891:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5892:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5893:     } else {
 5894:         $logmsg .= ' during self creation';
 5895:     }
 5896:     &logthis($logmsg);
 5897:     return 'ok';
 5898: }
 5899: 
 5900: # -------------------------------------------------------------- Modify student
 5901: 
 5902: sub modifystudent {
 5903:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5904:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5905:         $selfenroll,$context)=@_;
 5906:     if (!$cid) {
 5907: 	unless ($cid=$env{'request.course.id'}) {
 5908: 	    return 'not_in_class';
 5909: 	}
 5910:     }
 5911: # --------------------------------------------------------------- Make the user
 5912:     my $reply=&modifyuser
 5913: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5914:          $desiredhome,$email);
 5915:     unless ($reply eq 'ok') { return $reply; }
 5916:     # This will cause &modify_student_enrollment to get the uid from the
 5917:     # students environment
 5918:     $uid = undef if (!$forceid);
 5919:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5920: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5921:     return $reply;
 5922: }
 5923: 
 5924: sub modify_student_enrollment {
 5925:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5926:     my ($cdom,$cnum,$chome);
 5927:     if (!$cid) {
 5928: 	unless ($cid=$env{'request.course.id'}) {
 5929: 	    return 'not_in_class';
 5930: 	}
 5931: 	$cdom=$env{'course.'.$cid.'.domain'};
 5932: 	$cnum=$env{'course.'.$cid.'.num'};
 5933:     } else {
 5934: 	($cdom,$cnum)=split(/_/,$cid);
 5935:     }
 5936:     $chome=$env{'course.'.$cid.'.home'};
 5937:     if (!$chome) {
 5938: 	$chome=&homeserver($cnum,$cdom);
 5939:     }
 5940:     if (!$chome) { return 'unknown_course'; }
 5941:     # Make sure the user exists
 5942:     my $uhome=&homeserver($uname,$udom);
 5943:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5944: 	return 'error: no such user';
 5945:     }
 5946:     # Get student data if we were not given enough information
 5947:     if (!defined($first)  || $first  eq '' || 
 5948:         !defined($last)   || $last   eq '' || 
 5949:         !defined($uid)    || $uid    eq '' || 
 5950:         !defined($middle) || $middle eq '' || 
 5951:         !defined($gene)   || $gene   eq '') {
 5952:         # They did not supply us with enough data to enroll the student, so
 5953:         # we need to pick up more information.
 5954:         my %tmp = &get('environment',
 5955:                        ['firstname','middlename','lastname', 'generation','id']
 5956:                        ,$udom,$uname);
 5957: 
 5958:         #foreach my $key (keys(%tmp)) {
 5959:         #    &logthis("key $key = ".$tmp{$key});
 5960:         #}
 5961:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5962:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5963:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5964:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5965:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5966:     }
 5967:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5968:     my $reply=cput('classlist',
 5969: 		   {"$uname:$udom" => 
 5970: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5971: 		   $cdom,$cnum);
 5972:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5973: 	return 'error: '.$reply;
 5974:     } else {
 5975: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5976:     }
 5977:     # Add student role to user
 5978:     my $uurl='/'.$cid;
 5979:     $uurl=~s/\_/\//g;
 5980:     if ($usec) {
 5981: 	$uurl.='/'.$usec;
 5982:     }
 5983:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5984: }
 5985: 
 5986: sub format_name {
 5987:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5988:     my $name;
 5989:     if ($first ne 'lastname') {
 5990: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5991:     } else {
 5992: 	if ($lastname=~/\S/) {
 5993: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5994: 	    $name=~s/\s+,/,/;
 5995: 	} else {
 5996: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5997: 	}
 5998:     }
 5999:     $name=~s/^\s+//;
 6000:     $name=~s/\s+$//;
 6001:     $name=~s/\s+/ /g;
 6002:     return $name;
 6003: }
 6004: 
 6005: # ------------------------------------------------- Write to course preferences
 6006: 
 6007: sub writecoursepref {
 6008:     my ($courseid,%prefs)=@_;
 6009:     $courseid=~s/^\///;
 6010:     $courseid=~s/\_/\//g;
 6011:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6012:     my $chome=homeserver($cnum,$cdomain);
 6013:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6014: 	return 'error: no such course';
 6015:     }
 6016:     my $cstring='';
 6017:     foreach my $pref (keys(%prefs)) {
 6018: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6019:     }
 6020:     $cstring=~s/\&$//;
 6021:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6022: }
 6023: 
 6024: # ---------------------------------------------------------- Make/modify course
 6025: 
 6026: sub createcourse {
 6027:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6028:         $course_owner,$crstype)=@_;
 6029:     $url=&declutter($url);
 6030:     my $cid='';
 6031:     unless (&allowed('ccc',$udom)) {
 6032:         return 'refused';
 6033:     }
 6034: # ------------------------------------------------------------------- Create ID
 6035:    my $uname=int(1+rand(9)).
 6036:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6037:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6038:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6039: # ----------------------------------------------- Make sure that does not exist
 6040:    my $uhome=&homeserver($uname,$udom,'true');
 6041:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6042:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6043:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6044:        $uhome=&homeserver($uname,$udom,'true');       
 6045:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6046:            return 'error: unable to generate unique course-ID';
 6047:        } 
 6048:    }
 6049: # ------------------------------------------------ Check supplied server name
 6050:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6051:     if (! &is_library($course_server)) {
 6052:         return 'error:bad server name '.$course_server;
 6053:     }
 6054: # ------------------------------------------------------------- Make the course
 6055:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6056:                       $course_server);
 6057:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6058:     $uhome=&homeserver($uname,$udom,'true');
 6059:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6060: 	return 'error: no such course';
 6061:     }
 6062: # ----------------------------------------------------------------- Course made
 6063: # log existence
 6064:     my $newcourse = {
 6065:                     $udom.'_'.$uname => {
 6066:                                      description => $description,
 6067:                                      inst_code   => $inst_code,
 6068:                                      owner       => $course_owner,
 6069:                                      type        => $crstype,
 6070:                                                 },
 6071:                     };
 6072:     &courseidput($udom,$newcourse,$uhome,'notime');
 6073: # set toplevel url
 6074:     my $topurl=$url;
 6075:     unless ($nonstandard) {
 6076: # ------------------------------------------ For standard courses, make top url
 6077:         my $mapurl=&clutter($url);
 6078:         if ($mapurl eq '/res/') { $mapurl=''; }
 6079:         $env{'form.initmap'}=(<<ENDINITMAP);
 6080: <map>
 6081: <resource id="1" type="start"></resource>
 6082: <resource id="2" src="$mapurl"></resource>
 6083: <resource id="3" type="finish"></resource>
 6084: <link index="1" from="1" to="2"></link>
 6085: <link index="2" from="2" to="3"></link>
 6086: </map>
 6087: ENDINITMAP
 6088:         $topurl=&declutter(
 6089:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6090:                           );
 6091:     }
 6092: # ----------------------------------------------------------- Write preferences
 6093:     &writecoursepref($udom.'_'.$uname,
 6094:                      ('description' => $description,
 6095:                       'url'         => $topurl));
 6096:     return '/'.$udom.'/'.$uname;
 6097: }
 6098: 
 6099: sub is_course {
 6100:     my ($cdom,$cnum) = @_;
 6101:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6102: 				undef,'.');
 6103:     if (exists($courses{$cdom.'_'.$cnum})) {
 6104:         return 1;
 6105:     }
 6106:     return 0;
 6107: }
 6108: 
 6109: # ---------------------------------------------------------- Assign Custom Role
 6110: 
 6111: sub assigncustomrole {
 6112:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6113:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6114:                        $end,$start,$deleteflag,$selfenroll,$context);
 6115: }
 6116: 
 6117: # ----------------------------------------------------------------- Revoke Role
 6118: 
 6119: sub revokerole {
 6120:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6121:     my $now=time;
 6122:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6123: }
 6124: 
 6125: # ---------------------------------------------------------- Revoke Custom Role
 6126: 
 6127: sub revokecustomrole {
 6128:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6129:     my $now=time;
 6130:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6131:            $deleteflag,$selfenroll,$context);
 6132: }
 6133: 
 6134: # ------------------------------------------------------------ Disk usage
 6135: sub diskusage {
 6136:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6137:     $directorypath =~ s/\/$//;
 6138:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6139:                        .&escape($getpropath).':'.&escape($uname).':'
 6140:                        .&escape($udom),homeserver($uname,$udom));
 6141:     if ($listing eq 'unknown_cmd') {
 6142:         if ($getpropath) {
 6143:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6144:         }
 6145:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6146:     }
 6147:     return $listing;
 6148: }
 6149: 
 6150: sub is_locked {
 6151:     my ($file_name, $domain, $user) = @_;
 6152:     my @check;
 6153:     my $is_locked;
 6154:     push @check, $file_name;
 6155:     my %locked = &get('file_permissions',\@check,
 6156: 		      $env{'user.domain'},$env{'user.name'});
 6157:     my ($tmp)=keys(%locked);
 6158:     if ($tmp=~/^error:/) { undef(%locked); }
 6159:     
 6160:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6161:         $is_locked = 'false';
 6162:         foreach my $entry (@{$locked{$file_name}}) {
 6163:            if (ref($entry) eq 'ARRAY') { 
 6164:                $is_locked = 'true';
 6165:                last;
 6166:            }
 6167:        }
 6168:     } else {
 6169:         $is_locked = 'false';
 6170:     }
 6171: }
 6172: 
 6173: sub declutter_portfile {
 6174:     my ($file) = @_;
 6175:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6176:     return $file;
 6177: }
 6178: 
 6179: # ------------------------------------------------------------- Mark as Read Only
 6180: 
 6181: sub mark_as_readonly {
 6182:     my ($domain,$user,$files,$what) = @_;
 6183:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6184:     my ($tmp)=keys(%current_permissions);
 6185:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6186:     foreach my $file (@{$files}) {
 6187: 	$file = &declutter_portfile($file);
 6188:         push(@{$current_permissions{$file}},$what);
 6189:     }
 6190:     &put('file_permissions',\%current_permissions,$domain,$user);
 6191:     return;
 6192: }
 6193: 
 6194: # ------------------------------------------------------------Save Selected Files
 6195: 
 6196: sub save_selected_files {
 6197:     my ($user, $path, @files) = @_;
 6198:     my $filename = $user."savedfiles";
 6199:     my @other_files = &files_not_in_path($user, $path);
 6200:     open (OUT, '>'.$tmpdir.$filename);
 6201:     foreach my $file (@files) {
 6202:         print (OUT $env{'form.currentpath'}.$file."\n");
 6203:     }
 6204:     foreach my $file (@other_files) {
 6205:         print (OUT $file."\n");
 6206:     }
 6207:     close (OUT);
 6208:     return 'ok';
 6209: }
 6210: 
 6211: sub clear_selected_files {
 6212:     my ($user) = @_;
 6213:     my $filename = $user."savedfiles";
 6214:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6215:     print (OUT undef);
 6216:     close (OUT);
 6217:     return ("ok");    
 6218: }
 6219: 
 6220: sub files_in_path {
 6221:     my ($user, $path) = @_;
 6222:     my $filename = $user."savedfiles";
 6223:     my %return_files;
 6224:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6225:     while (my $line_in = <IN>) {
 6226:         chomp ($line_in);
 6227:         my @paths_and_file = split (m!/!, $line_in);
 6228:         my $file_part = pop (@paths_and_file);
 6229:         my $path_part = join ('/', @paths_and_file);
 6230:         $path_part.='/';
 6231:         my $path_and_file = $path_part.$file_part;
 6232:         if ($path_part eq $path) {
 6233:             $return_files{$file_part}= 'selected';
 6234:         }
 6235:     }
 6236:     close (IN);
 6237:     return (\%return_files);
 6238: }
 6239: 
 6240: # called in portfolio select mode, to show files selected NOT in current directory
 6241: sub files_not_in_path {
 6242:     my ($user, $path) = @_;
 6243:     my $filename = $user."savedfiles";
 6244:     my @return_files;
 6245:     my $path_part;
 6246:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6247:     while (my $line = <IN>) {
 6248:         #ok, I know it's clunky, but I want it to work
 6249:         my @paths_and_file = split(m|/|, $line);
 6250:         my $file_part = pop(@paths_and_file);
 6251:         chomp($file_part);
 6252:         my $path_part = join('/', @paths_and_file);
 6253:         $path_part .= '/';
 6254:         my $path_and_file = $path_part.$file_part;
 6255:         if ($path_part ne $path) {
 6256:             push(@return_files, ($path_and_file));
 6257:         }
 6258:     }
 6259:     close(OUT);
 6260:     return (@return_files);
 6261: }
 6262: 
 6263: #----------------------------------------------Get portfolio file permissions
 6264: 
 6265: sub get_portfile_permissions {
 6266:     my ($domain,$user) = @_;
 6267:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6268:     my ($tmp)=keys(%current_permissions);
 6269:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6270:     return \%current_permissions;
 6271: }
 6272: 
 6273: #---------------------------------------------Get portfolio file access controls
 6274: 
 6275: sub get_access_controls {
 6276:     my ($current_permissions,$group,$file) = @_;
 6277:     my %access;
 6278:     my $real_file = $file;
 6279:     $file =~ s/\.meta$//;
 6280:     if (defined($file)) {
 6281:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6282:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6283:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6284:             }
 6285:         }
 6286:     } else {
 6287:         foreach my $key (keys(%{$current_permissions})) {
 6288:             if ($key =~ /\0accesscontrol$/) {
 6289:                 if (defined($group)) {
 6290:                     if ($key !~ m-^\Q$group\E/-) {
 6291:                         next;
 6292:                     }
 6293:                 }
 6294:                 my ($fullpath) = split(/\0/,$key);
 6295:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6296:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6297:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6298:                     }
 6299:                 }
 6300:             }
 6301:         }
 6302:     }
 6303:     return %access;
 6304: }
 6305: 
 6306: sub modify_access_controls {
 6307:     my ($file_name,$changes,$domain,$user)=@_;
 6308:     my ($outcome,$deloutcome);
 6309:     my %store_permissions;
 6310:     my %new_values;
 6311:     my %new_control;
 6312:     my %translation;
 6313:     my @deletions = ();
 6314:     my $now = time;
 6315:     if (exists($$changes{'activate'})) {
 6316:         if (ref($$changes{'activate'}) eq 'HASH') {
 6317:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6318:             my $numnew = scalar(@newitems);
 6319:             for (my $i=0; $i<$numnew; $i++) {
 6320:                 my $newkey = $newitems[$i];
 6321:                 my $newid = &Apache::loncommon::get_cgi_id();
 6322:                 if ($newkey =~ /^\d+:/) { 
 6323:                     $newkey =~ s/^(\d+)/$newid/;
 6324:                     $translation{$1} = $newid;
 6325:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6326:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6327:                     $translation{$1} = $newid;
 6328:                 }
 6329:                 $new_values{$file_name."\0".$newkey} = 
 6330:                                           $$changes{'activate'}{$newitems[$i]};
 6331:                 $new_control{$newkey} = $now;
 6332:             }
 6333:         }
 6334:     }
 6335:     my %todelete;
 6336:     my %changed_items;
 6337:     foreach my $action ('delete','update') {
 6338:         if (exists($$changes{$action})) {
 6339:             if (ref($$changes{$action}) eq 'HASH') {
 6340:                 foreach my $key (keys(%{$$changes{$action}})) {
 6341:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6342:                     if ($action eq 'delete') { 
 6343:                         $todelete{$itemnum} = 1;
 6344:                     } else {
 6345:                         $changed_items{$itemnum} = $key;
 6346:                     }
 6347:                 }
 6348:             }
 6349:         }
 6350:     }
 6351:     # get lock on access controls for file.
 6352:     my $lockhash = {
 6353:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6354:                                                        ':'.$env{'user.domain'},
 6355:                    }; 
 6356:     my $tries = 0;
 6357:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6358:    
 6359:     while (($gotlock ne 'ok') && $tries <3) {
 6360:         $tries ++;
 6361:         sleep 1;
 6362:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6363:     }
 6364:     if ($gotlock eq 'ok') {
 6365:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6366:         my ($tmp)=keys(%curr_permissions);
 6367:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6368:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6369:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6370:             if (ref($curr_controls) eq 'HASH') {
 6371:                 foreach my $control_item (keys(%{$curr_controls})) {
 6372:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6373:                     if (defined($todelete{$itemnum})) {
 6374:                         push(@deletions,$file_name."\0".$control_item);
 6375:                     } else {
 6376:                         if (defined($changed_items{$itemnum})) {
 6377:                             $new_control{$changed_items{$itemnum}} = $now;
 6378:                             push(@deletions,$file_name."\0".$control_item);
 6379:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6380:                         } else {
 6381:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6382:                         }
 6383:                     }
 6384:                 }
 6385:             }
 6386:         }
 6387:         my ($group);
 6388:         if (&is_course($domain,$user)) {
 6389:             ($group,my $file) = split(/\//,$file_name,2);
 6390:         }
 6391:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6392:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6393:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6394:         #  remove lock
 6395:         my @del_lock = ($file_name."\0".'locked_access_records');
 6396:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6397:         my $sqlresult =
 6398:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6399:                                     $group);
 6400:     } else {
 6401:         $outcome = "error: could not obtain lockfile\n";  
 6402:     }
 6403:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6404: }
 6405: 
 6406: sub make_public_indefinitely {
 6407:     my ($requrl) = @_;
 6408:     my $now = time;
 6409:     my $action = 'activate';
 6410:     my $aclnum = 0;
 6411:     if (&is_portfolio_url($requrl)) {
 6412:         my (undef,$udom,$unum,$file_name,$group) =
 6413:             &parse_portfolio_url($requrl);
 6414:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6415:         my %access_controls = &get_access_controls($current_perms,
 6416:                                                    $group,$file_name);
 6417:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6418:             my ($num,$scope,$end,$start) = 
 6419:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6420:             if ($scope eq 'public') {
 6421:                 if ($start <= $now && $end == 0) {
 6422:                     $action = 'none';
 6423:                 } else {
 6424:                     $action = 'update';
 6425:                     $aclnum = $num;
 6426:                 }
 6427:                 last;
 6428:             }
 6429:         }
 6430:         if ($action eq 'none') {
 6431:              return 'ok';
 6432:         } else {
 6433:             my %changes;
 6434:             my $newend = 0;
 6435:             my $newstart = $now;
 6436:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6437:             $changes{$action}{$newkey} = {
 6438:                 type => 'public',
 6439:                 time => {
 6440:                     start => $newstart,
 6441:                     end   => $newend,
 6442:                 },
 6443:             };
 6444:             my ($outcome,$deloutcome,$new_values,$translation) =
 6445:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6446:             return $outcome;
 6447:         }
 6448:     } else {
 6449:         return 'invalid';
 6450:     }
 6451: }
 6452: 
 6453: #------------------------------------------------------Get Marked as Read Only
 6454: 
 6455: sub get_marked_as_readonly {
 6456:     my ($domain,$user,$what,$group) = @_;
 6457:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6458:     my @readonly_files;
 6459:     my $cmp1=$what;
 6460:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6461:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6462:         if (defined($group)) {
 6463:             if ($file_name !~ m-^\Q$group\E/-) {
 6464:                 next;
 6465:             }
 6466:         }
 6467:         if (ref($value) eq "ARRAY"){
 6468:             foreach my $stored_what (@{$value}) {
 6469:                 my $cmp2=$stored_what;
 6470:                 if (ref($stored_what) eq 'ARRAY') {
 6471:                     $cmp2=join('',@{$stored_what});
 6472:                 }
 6473:                 if ($cmp1 eq $cmp2) {
 6474:                     push(@readonly_files, $file_name);
 6475:                     last;
 6476:                 } elsif (!defined($what)) {
 6477:                     push(@readonly_files, $file_name);
 6478:                     last;
 6479:                 }
 6480:             }
 6481:         }
 6482:     }
 6483:     return @readonly_files;
 6484: }
 6485: #-----------------------------------------------------------Get Marked as Read Only Hash
 6486: 
 6487: sub get_marked_as_readonly_hash {
 6488:     my ($current_permissions,$group,$what) = @_;
 6489:     my %readonly_files;
 6490:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6491:         if (defined($group)) {
 6492:             if ($file_name !~ m-^\Q$group\E/-) {
 6493:                 next;
 6494:             }
 6495:         }
 6496:         if (ref($value) eq "ARRAY"){
 6497:             foreach my $stored_what (@{$value}) {
 6498:                 if (ref($stored_what) eq 'ARRAY') {
 6499:                     foreach my $lock_descriptor(@{$stored_what}) {
 6500:                         if ($lock_descriptor eq 'graded') {
 6501:                             $readonly_files{$file_name} = 'graded';
 6502:                         } elsif ($lock_descriptor eq 'handback') {
 6503:                             $readonly_files{$file_name} = 'handback';
 6504:                         } else {
 6505:                             if (!exists($readonly_files{$file_name})) {
 6506:                                 $readonly_files{$file_name} = 'locked';
 6507:                             }
 6508:                         }
 6509:                     }
 6510:                 } 
 6511:             }
 6512:         } 
 6513:     }
 6514:     return %readonly_files;
 6515: }
 6516: # ------------------------------------------------------------ Unmark as Read Only
 6517: 
 6518: sub unmark_as_readonly {
 6519:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6520:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6521:     my ($domain,$user,$what,$file_name,$group) = @_;
 6522:     $file_name = &declutter_portfile($file_name);
 6523:     my $symb_crs = $what;
 6524:     if (ref($what)) { $symb_crs=join('',@$what); }
 6525:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6526:     my ($tmp)=keys(%current_permissions);
 6527:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6528:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6529:     foreach my $file (@readonly_files) {
 6530: 	my $clean_file = &declutter_portfile($file);
 6531: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6532: 	my $current_locks = $current_permissions{$file};
 6533:         my @new_locks;
 6534:         my @del_keys;
 6535:         if (ref($current_locks) eq "ARRAY"){
 6536:             foreach my $locker (@{$current_locks}) {
 6537:                 my $compare=$locker;
 6538:                 if (ref($locker) eq 'ARRAY') {
 6539:                     $compare=join('',@{$locker});
 6540:                     if ($compare ne $symb_crs) {
 6541:                         push(@new_locks, $locker);
 6542:                     }
 6543:                 }
 6544:             }
 6545:             if (scalar(@new_locks) > 0) {
 6546:                 $current_permissions{$file} = \@new_locks;
 6547:             } else {
 6548:                 push(@del_keys, $file);
 6549:                 &del('file_permissions',\@del_keys, $domain, $user);
 6550:                 delete($current_permissions{$file});
 6551:             }
 6552:         }
 6553:     }
 6554:     &put('file_permissions',\%current_permissions,$domain,$user);
 6555:     return;
 6556: }
 6557: 
 6558: # ------------------------------------------------------------ Directory lister
 6559: 
 6560: sub dirlist {
 6561:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6562:     $uri=~s/^\///;
 6563:     $uri=~s/\/$//;
 6564:     my ($udom, $uname);
 6565:     if ($getuserdir) {
 6566:         $udom = $userdomain;
 6567:         $uname = $username;
 6568:     } else {
 6569:         (undef,$udom,$uname)=split(/\//,$uri);
 6570:         if(defined($userdomain)) {
 6571:             $udom = $userdomain;
 6572:         }
 6573:         if(defined($username)) {
 6574:             $uname = $username;
 6575:         }
 6576:     }
 6577:     my ($dirRoot,$listing,@listing_results);
 6578: 
 6579:     $dirRoot = $perlvar{'lonDocRoot'};
 6580:     if (defined($getpropath)) {
 6581:         $dirRoot = &propath($udom,$uname);
 6582:         $dirRoot =~ s/\/$//;
 6583:     } elsif (defined($getuserdir)) {
 6584:         my $subdir=$uname.'__';
 6585:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6586:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6587:                    ."/$udom/$subdir/$uname";
 6588:     } elsif (defined($alternateRoot)) {
 6589:         $dirRoot = $alternateRoot;
 6590:     }
 6591: 
 6592:     if($udom) {
 6593:         if($uname) {
 6594:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6595:                               .$getuserdir.':'.&escape($dirRoot)
 6596:                               .':'.&escape($uname).':'.&escape($udom),
 6597:                               &homeserver($uname,$udom));
 6598:             if ($listing eq 'unknown_cmd') {
 6599:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6600:                                   &homeserver($uname,$udom));
 6601:             } else {
 6602:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6603:             }
 6604:             if ($listing eq 'unknown_cmd') {
 6605:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6606: 				  &homeserver($uname,$udom));
 6607:                 @listing_results = split(/:/,$listing);
 6608:             } else {
 6609:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6610:             }
 6611:             return @listing_results;
 6612:         } elsif(!$alternateRoot) {
 6613:             my %allusers;
 6614: 	    my %servers = &get_servers($udom,'library');
 6615:  	    foreach my $tryserver (keys(%servers)) {
 6616:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6617:                                   &escape($udom),$tryserver);
 6618:                 if ($listing eq 'unknown_cmd') {
 6619: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6620: 				      $udom, $tryserver);
 6621:                 } else {
 6622:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6623:                 }
 6624: 		if ($listing eq 'unknown_cmd') {
 6625: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6626: 				      $udom, $tryserver);
 6627: 		    @listing_results = split(/:/,$listing);
 6628: 		} else {
 6629: 		    @listing_results =
 6630: 			map { &unescape($_); } split(/:/,$listing);
 6631: 		}
 6632: 		if ($listing_results[0] ne 'no_such_dir' && 
 6633: 		    $listing_results[0] ne 'empty'       &&
 6634: 		    $listing_results[0] ne 'con_lost') {
 6635: 		    foreach my $line (@listing_results) {
 6636: 			my ($entry) = split(/&/,$line,2);
 6637: 			$allusers{$entry} = 1;
 6638: 		    }
 6639: 		}
 6640:             }
 6641:             my $alluserstr='';
 6642:             foreach my $user (sort(keys(%allusers))) {
 6643:                 $alluserstr.=$user.'&user:';
 6644:             }
 6645:             $alluserstr=~s/:$//;
 6646:             return split(/:/,$alluserstr);
 6647:         } else {
 6648:             return ('missing user name');
 6649:         }
 6650:     } elsif(!defined($getpropath)) {
 6651:         my @all_domains = sort(&all_domains());
 6652:         foreach my $domain (@all_domains) {
 6653:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6654:         }
 6655:         return @all_domains;
 6656:     } else {
 6657:         return ('missing domain');
 6658:     }
 6659: }
 6660: 
 6661: # --------------------------------------------- GetFileTimestamp
 6662: # This function utilizes dirlist and returns the date stamp for
 6663: # when it was last modified.  It will also return an error of -1
 6664: # if an error occurs
 6665: 
 6666: sub GetFileTimestamp {
 6667:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6668:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6669:     $studentName   = &LONCAPA::clean_username($studentName);
 6670:     my ($fileStat) = 
 6671:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6672:                                  undef,$getuserdir);
 6673:     my @stats = split('&', $fileStat);
 6674:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6675:         # @stats contains first the filename, then the stat output
 6676:         return $stats[10]; # so this is 10 instead of 9.
 6677:     } else {
 6678:         return -1;
 6679:     }
 6680: }
 6681: 
 6682: sub stat_file {
 6683:     my ($uri) = @_;
 6684:     $uri = &clutter_with_no_wrapper($uri);
 6685: 
 6686:     my ($udom,$uname,$file);
 6687:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6688: 	($udom,$uname,$file) =
 6689: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6690: 	$file = 'userfiles/'.$file;
 6691:     }
 6692:     if ($uri =~ m-^/res/-) {
 6693: 	($udom,$uname) = 
 6694: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6695: 	$file = $uri;
 6696:     }
 6697: 
 6698:     if (!$udom || !$uname || !$file) {
 6699: 	# unable to handle the uri
 6700: 	return ();
 6701:     }
 6702:     my $getpropath;
 6703:     if ($file =~ /^userfiles\//) {
 6704:         $getpropath = 1;
 6705:     }
 6706:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6707:     my @stats = split('&', $result);
 6708:     
 6709:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6710: 	shift(@stats); #filename is first
 6711: 	return @stats;
 6712:     }
 6713:     return ();
 6714: }
 6715: 
 6716: # -------------------------------------------------------- Value of a Condition
 6717: 
 6718: # gets the value of a specific preevaluated condition
 6719: #    stored in the string  $env{user.state.<cid>}
 6720: # or looks up a condition reference in the bighash and if if hasn't
 6721: # already been evaluated recurses into docondval to get the value of
 6722: # the condition, then memoizing it to 
 6723: #   $env{user.state.<cid>.<condition>}
 6724: sub directcondval {
 6725:     my $number=shift;
 6726:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6727: 	&Apache::lonuserstate::evalstate();
 6728:     }
 6729:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6730: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6731:     } elsif ($number =~ /^_/) {
 6732: 	my $sub_condition;
 6733: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6734: 		&GDBM_READER(),0640)) {
 6735: 	    $sub_condition=$bighash{'conditions'.$number};
 6736: 	    untie(%bighash);
 6737: 	}
 6738: 	my $value = &docondval($sub_condition);
 6739: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6740: 	return $value;
 6741:     }
 6742:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6743:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6744:     } else {
 6745:        return 2;
 6746:     }
 6747: }
 6748: 
 6749: # get the collection of conditions for this resource
 6750: sub condval {
 6751:     my $condidx=shift;
 6752:     my $allpathcond='';
 6753:     foreach my $cond (split(/\|/,$condidx)) {
 6754: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6755: 	    $allpathcond.=
 6756: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6757: 	}
 6758:     }
 6759:     $allpathcond=~s/\|$//;
 6760:     return &docondval($allpathcond);
 6761: }
 6762: 
 6763: #evaluates an expression of conditions
 6764: sub docondval {
 6765:     my ($allpathcond) = @_;
 6766:     my $result=0;
 6767:     if ($env{'request.course.id'}
 6768: 	&& defined($allpathcond)) {
 6769: 	my $operand='|';
 6770: 	my @stack;
 6771: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6772: 	    if ($chunk eq '(') {
 6773: 		push @stack,($operand,$result);
 6774: 	    } elsif ($chunk eq ')') {
 6775: 		my $before=pop @stack;
 6776: 		if (pop @stack eq '&') {
 6777: 		    $result=$result>$before?$before:$result;
 6778: 		} else {
 6779: 		    $result=$result>$before?$result:$before;
 6780: 		}
 6781: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6782: 		$operand=$chunk;
 6783: 	    } else {
 6784: 		my $new=directcondval($chunk);
 6785: 		if ($operand eq '&') {
 6786: 		    $result=$result>$new?$new:$result;
 6787: 		} else {
 6788: 		    $result=$result>$new?$result:$new;
 6789: 		}
 6790: 	    }
 6791: 	}
 6792:     }
 6793:     return $result;
 6794: }
 6795: 
 6796: # ---------------------------------------------------- Devalidate courseresdata
 6797: 
 6798: sub devalidatecourseresdata {
 6799:     my ($coursenum,$coursedomain)=@_;
 6800:     my $hashid=$coursenum.':'.$coursedomain;
 6801:     &devalidate_cache_new('courseres',$hashid);
 6802: }
 6803: 
 6804: 
 6805: # --------------------------------------------------- Course Resourcedata Query
 6806: #
 6807: #  Parameters:
 6808: #      $coursenum    - Number of the course.
 6809: #      $coursedomain - Domain at which the course was created.
 6810: #  Returns:
 6811: #     A hash of the course parameters along (I think) with timestamps
 6812: #     and version info.
 6813: 
 6814: sub get_courseresdata {
 6815:     my ($coursenum,$coursedomain)=@_;
 6816:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6817:     my $hashid=$coursenum.':'.$coursedomain;
 6818:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6819:     my %dumpreply;
 6820:     unless (defined($cached)) {
 6821: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6822: 	$result=\%dumpreply;
 6823: 	my ($tmp) = keys(%dumpreply);
 6824: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6825: 	    &do_cache_new('courseres',$hashid,$result,600);
 6826: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6827: 	    return $tmp;
 6828: 	} elsif ($tmp =~ /^(error)/) {
 6829: 	    $result=undef;
 6830: 	    &do_cache_new('courseres',$hashid,$result,600);
 6831: 	}
 6832:     }
 6833:     return $result;
 6834: }
 6835: 
 6836: sub devalidateuserresdata {
 6837:     my ($uname,$udom)=@_;
 6838:     my $hashid="$udom:$uname";
 6839:     &devalidate_cache_new('userres',$hashid);
 6840: }
 6841: 
 6842: sub get_userresdata {
 6843:     my ($uname,$udom)=@_;
 6844:     #most student don\'t have any data set, check if there is some data
 6845:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6846: 
 6847:     my $hashid="$udom:$uname";
 6848:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6849:     if (!defined($cached)) {
 6850: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6851: 	$result=\%resourcedata;
 6852: 	&do_cache_new('userres',$hashid,$result,600);
 6853:     }
 6854:     my ($tmp)=keys(%$result);
 6855:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6856: 	return $result;
 6857:     }
 6858:     #error 2 occurs when the .db doesn't exist
 6859:     if ($tmp!~/error: 2 /) {
 6860: 	&logthis("<font color=\"blue\">WARNING:".
 6861: 		 " Trying to get resource data for ".
 6862: 		 $uname." at ".$udom.": ".
 6863: 		 $tmp."</font>");
 6864:     } elsif ($tmp=~/error: 2 /) {
 6865: 	#&EXT_cache_set($udom,$uname);
 6866: 	&do_cache_new('userres',$hashid,undef,600);
 6867: 	undef($tmp); # not really an error so don't send it back
 6868:     }
 6869:     return $tmp;
 6870: }
 6871: #----------------------------------------------- resdata - return resource data
 6872: #  Purpose:
 6873: #    Return resource data for either users or for a course.
 6874: #  Parameters:
 6875: #     $name      - Course/user name.
 6876: #     $domain    - Name of the domain the user/course is registered on.
 6877: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6878: #     @which     - Array of names of resources desired.
 6879: #  Returns:
 6880: #     The value of the first reasource in @which that is found in the
 6881: #     resource hash.
 6882: #  Exceptional Conditions:
 6883: #     If the $type passed in is not valid (not the string 'course' or 
 6884: #     'user', an undefined  reference is returned.
 6885: #     If none of the resources are found, an undef is returned
 6886: sub resdata {
 6887:     my ($name,$domain,$type,@which)=@_;
 6888:     my $result;
 6889:     if ($type eq 'course') {
 6890: 	$result=&get_courseresdata($name,$domain);
 6891:     } elsif ($type eq 'user') {
 6892: 	$result=&get_userresdata($name,$domain);
 6893:     }
 6894:     if (!ref($result)) { return $result; }    
 6895:     foreach my $item (@which) {
 6896: 	if (defined($result->{$item->[0]})) {
 6897: 	    return [$result->{$item->[0]},$item->[1]];
 6898: 	}
 6899:     }
 6900:     return undef;
 6901: }
 6902: 
 6903: #
 6904: # EXT resource caching routines
 6905: #
 6906: 
 6907: sub clear_EXT_cache_status {
 6908:     &delenv('cache.EXT.');
 6909: }
 6910: 
 6911: sub EXT_cache_status {
 6912:     my ($target_domain,$target_user) = @_;
 6913:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6914:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6915:         # We know already the user has no data
 6916:         return 1;
 6917:     } else {
 6918:         return 0;
 6919:     }
 6920: }
 6921: 
 6922: sub EXT_cache_set {
 6923:     my ($target_domain,$target_user) = @_;
 6924:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6925:     #&appenv({$cachename => time});
 6926: }
 6927: 
 6928: # --------------------------------------------------------- Value of a Variable
 6929: sub EXT {
 6930: 
 6931:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6932:     unless ($varname) { return ''; }
 6933:     #get real user name/domain, courseid and symb
 6934:     my $courseid;
 6935:     my $publicuser;
 6936:     if ($symbparm) {
 6937: 	$symbparm=&get_symb_from_alias($symbparm);
 6938:     }
 6939:     if (!($uname && $udom)) {
 6940:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6941:       if (!$symbparm) {	$symbparm=$cursymb; }
 6942:     } else {
 6943: 	$courseid=$env{'request.course.id'};
 6944:     }
 6945:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6946:     my $rest;
 6947:     if (defined($therest[0])) {
 6948:        $rest=join('.',@therest);
 6949:     } else {
 6950:        $rest='';
 6951:     }
 6952: 
 6953:     my $qualifierrest=$qualifier;
 6954:     if ($rest) { $qualifierrest.='.'.$rest; }
 6955:     my $spacequalifierrest=$space;
 6956:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6957:     if ($realm eq 'user') {
 6958: # --------------------------------------------------------------- user.resource
 6959: 	if ($space eq 'resource') {
 6960: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6961: 		  || defined($Apache::lonhomework::parsing_a_task))
 6962: 		 &&
 6963: 		 ($symbparm eq &symbread()) ) {	
 6964: 		# if we are in the middle of processing the resource the
 6965: 		# get the value we are planning on committing
 6966:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6967:                     return $Apache::lonhomework::results{$qualifierrest};
 6968:                 } else {
 6969:                     return $Apache::lonhomework::history{$qualifierrest};
 6970:                 }
 6971: 	    } else {
 6972: 		my %restored;
 6973: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6974: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6975: 		} else {
 6976: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6977: 		}
 6978: 		return $restored{$qualifierrest};
 6979: 	    }
 6980: # ----------------------------------------------------------------- user.access
 6981:         } elsif ($space eq 'access') {
 6982: 	    # FIXME - not supporting calls for a specific user
 6983:             return &allowed($qualifier,$rest);
 6984: # ------------------------------------------ user.preferences, user.environment
 6985:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6986: 	    if (($uname eq $env{'user.name'}) &&
 6987: 		($udom eq $env{'user.domain'})) {
 6988: 		return $env{join('.',('environment',$qualifierrest))};
 6989: 	    } else {
 6990: 		my %returnhash;
 6991: 		if (!$publicuser) {
 6992: 		    %returnhash=&userenvironment($udom,$uname,
 6993: 						 $qualifierrest);
 6994: 		}
 6995: 		return $returnhash{$qualifierrest};
 6996: 	    }
 6997: # ----------------------------------------------------------------- user.course
 6998:         } elsif ($space eq 'course') {
 6999: 	    # FIXME - not supporting calls for a specific user
 7000:             return $env{join('.',('request.course',$qualifier))};
 7001: # ------------------------------------------------------------------- user.role
 7002:         } elsif ($space eq 'role') {
 7003: 	    # FIXME - not supporting calls for a specific user
 7004:             my ($role,$where)=split(/\./,$env{'request.role'});
 7005:             if ($qualifier eq 'value') {
 7006: 		return $role;
 7007:             } elsif ($qualifier eq 'extent') {
 7008:                 return $where;
 7009:             }
 7010: # ----------------------------------------------------------------- user.domain
 7011:         } elsif ($space eq 'domain') {
 7012:             return $udom;
 7013: # ------------------------------------------------------------------- user.name
 7014:         } elsif ($space eq 'name') {
 7015:             return $uname;
 7016: # ---------------------------------------------------- Any other user namespace
 7017:         } else {
 7018: 	    my %reply;
 7019: 	    if (!$publicuser) {
 7020: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7021: 	    }
 7022: 	    return $reply{$qualifierrest};
 7023:         }
 7024:     } elsif ($realm eq 'query') {
 7025: # ---------------------------------------------- pull stuff out of query string
 7026:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7027: 						[$spacequalifierrest]);
 7028: 	return $env{'form.'.$spacequalifierrest}; 
 7029:    } elsif ($realm eq 'request') {
 7030: # ------------------------------------------------------------- request.browser
 7031:         if ($space eq 'browser') {
 7032: 	    if ($qualifier eq 'textremote') {
 7033: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7034: 		    return 1;
 7035: 		} else {
 7036: 		    return 0;
 7037: 		}
 7038: 	    } else {
 7039: 		return $env{'browser.'.$qualifier};
 7040: 	    }
 7041: # ------------------------------------------------------------ request.filename
 7042:         } else {
 7043:             return $env{'request.'.$spacequalifierrest};
 7044:         }
 7045:     } elsif ($realm eq 'course') {
 7046: # ---------------------------------------------------------- course.description
 7047:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7048:     } elsif ($realm eq 'resource') {
 7049: 
 7050: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7051: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7052: 	}
 7053: 
 7054: 	if ($space eq 'title') {
 7055: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7056: 	    return &gettitle($symbparm);
 7057: 	}
 7058: 	
 7059: 	if ($space eq 'map') {
 7060: 	    my ($map) = &decode_symb($symbparm);
 7061: 	    return &symbread($map);
 7062: 	}
 7063: 	if ($space eq 'filename') {
 7064: 	    if ($symbparm) {
 7065: 		return &clutter((&decode_symb($symbparm))[2]);
 7066: 	    }
 7067: 	    return &hreflocation('',$env{'request.filename'});
 7068: 	}
 7069: 
 7070: 	my ($section, $group, @groups);
 7071: 	my ($courselevelm,$courselevel);
 7072: 	if ($symbparm && defined($courseid) && 
 7073: 	    $courseid eq $env{'request.course.id'}) {
 7074: 
 7075: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7076: 
 7077: # ----------------------------------------------------- Cascading lookup scheme
 7078: 	    my $symbp=$symbparm;
 7079: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7080: 
 7081: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7082: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7083: 
 7084: 	    if (($env{'user.name'} eq $uname) &&
 7085: 		($env{'user.domain'} eq $udom)) {
 7086: 		$section=$env{'request.course.sec'};
 7087:                 @groups = split(/:/,$env{'request.course.groups'});  
 7088:                 @groups=&sort_course_groups($courseid,@groups); 
 7089: 	    } else {
 7090: 		if (! defined($usection)) {
 7091: 		    $section=&getsection($udom,$uname,$courseid);
 7092: 		} else {
 7093: 		    $section = $usection;
 7094: 		}
 7095:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7096: 	    }
 7097: 
 7098: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7099: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7100: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7101: 
 7102: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7103: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7104: 	    $courselevelm=$courseid.'.'.$mapparm;
 7105: 
 7106: # ----------------------------------------------------------- first, check user
 7107: 
 7108: 	    my $userreply=&resdata($uname,$udom,'user',
 7109: 				       ([$courselevelr,'resource'],
 7110: 					[$courselevelm,'map'     ],
 7111: 					[$courselevel, 'course'  ]));
 7112: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7113: 
 7114: # ------------------------------------------------ second, check some of course
 7115:             my $coursereply;
 7116:             if (@groups > 0) {
 7117:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7118:                                        $mapparm,$spacequalifierrest);
 7119:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7120:             }
 7121: 
 7122: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7123: 				  $env{'course.'.$courseid.'.domain'},
 7124: 				  'course',
 7125: 				  ([$seclevelr,   'resource'],
 7126: 				   [$seclevelm,   'map'     ],
 7127: 				   [$seclevel,    'course'  ],
 7128: 				   [$courselevelr,'resource']));
 7129: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7130: 
 7131: # ------------------------------------------------------ third, check map parms
 7132: 	    my %parmhash=();
 7133: 	    my $thisparm='';
 7134: 	    if (tie(%parmhash,'GDBM_File',
 7135: 		    $env{'request.course.fn'}.'_parms.db',
 7136: 		    &GDBM_READER(),0640)) {
 7137: 		$thisparm=$parmhash{$symbparm};
 7138: 		untie(%parmhash);
 7139: 	    }
 7140: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7141: 	}
 7142: # ------------------------------------------ fourth, look in resource metadata
 7143: 
 7144: 	$spacequalifierrest=~s/\./\_/;
 7145: 	my $filename;
 7146: 	if (!$symbparm) { $symbparm=&symbread(); }
 7147: 	if ($symbparm) {
 7148: 	    $filename=(&decode_symb($symbparm))[2];
 7149: 	} else {
 7150: 	    $filename=$env{'request.filename'};
 7151: 	}
 7152: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7153: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7154: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7155: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7156: 
 7157: # ---------------------------------------------- fourth, look in rest of course
 7158: 	if ($symbparm && defined($courseid) && 
 7159: 	    $courseid eq $env{'request.course.id'}) {
 7160: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7161: 				     $env{'course.'.$courseid.'.domain'},
 7162: 				     'course',
 7163: 				     ([$courselevelm,'map'   ],
 7164: 				      [$courselevel, 'course']));
 7165: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7166: 	}
 7167: # ------------------------------------------------------------------ Cascade up
 7168: 	unless ($space eq '0') {
 7169: 	    my @parts=split(/_/,$space);
 7170: 	    my $id=pop(@parts);
 7171: 	    my $part=join('_',@parts);
 7172: 	    if ($part eq '') { $part='0'; }
 7173: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7174: 				 $symbparm,$udom,$uname,$section,1);
 7175: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7176: 	}
 7177: 	if ($recurse) { return undef; }
 7178: 	my $pack_def=&packages_tab_default($filename,$varname);
 7179: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7180: # ---------------------------------------------------- Any other user namespace
 7181:     } elsif ($realm eq 'environment') {
 7182: # ----------------------------------------------------------------- environment
 7183: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7184: 	    return $env{'environment.'.$spacequalifierrest};
 7185: 	} else {
 7186: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7187: 		return '';
 7188: 	    }
 7189: 	    my %returnhash=&userenvironment($udom,$uname,
 7190: 					    $spacequalifierrest);
 7191: 	    return $returnhash{$spacequalifierrest};
 7192: 	}
 7193:     } elsif ($realm eq 'system') {
 7194: # ----------------------------------------------------------------- system.time
 7195: 	if ($space eq 'time') {
 7196: 	    return time;
 7197:         }
 7198:     } elsif ($realm eq 'server') {
 7199: # ----------------------------------------------------------------- system.time
 7200: 	if ($space eq 'name') {
 7201: 	    return $ENV{'SERVER_NAME'};
 7202:         }
 7203:     }
 7204:     return '';
 7205: }
 7206: 
 7207: sub get_reply {
 7208:     my ($reply_value) = @_;
 7209:     if (ref($reply_value) eq 'ARRAY') {
 7210:         if (wantarray) {
 7211: 	    return @$reply_value;
 7212:         }
 7213:         return $reply_value->[0];
 7214:     } else {
 7215:         return $reply_value;
 7216:     }
 7217: }
 7218: 
 7219: sub check_group_parms {
 7220:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7221:     my @groupitems = ();
 7222:     my $resultitem;
 7223:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7224:     foreach my $group (@{$groups}) {
 7225:         foreach my $level (@levels) {
 7226:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7227:              push(@groupitems,[$item,$level->[1]]);
 7228:         }
 7229:     }
 7230:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7231:                             $env{'course.'.$courseid.'.domain'},
 7232:                                      'course',@groupitems);
 7233:     return $coursereply;
 7234: }
 7235: 
 7236: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7237:     my ($courseid,@groups) = @_;
 7238:     @groups = sort(@groups);
 7239:     return @groups;
 7240: }
 7241: 
 7242: sub packages_tab_default {
 7243:     my ($uri,$varname)=@_;
 7244:     my (undef,$part,$name)=split(/\./,$varname);
 7245: 
 7246:     my (@extension,@specifics,$do_default);
 7247:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7248: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7249: 	if ($pack_type eq 'default') {
 7250: 	    $do_default=1;
 7251: 	} elsif ($pack_type eq 'extension') {
 7252: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7253: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7254: 	    # only look at packages defaults for packages that this id is
 7255: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7256: 	}
 7257:     }
 7258:     # first look for a package that matches the requested part id
 7259:     foreach my $package (@specifics) {
 7260: 	my (undef,$pack_type,$pack_part)=@{$package};
 7261: 	next if ($pack_part ne $part);
 7262: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7263: 	    return $packagetab{"$pack_type&$name&default"};
 7264: 	}
 7265:     }
 7266:     # look for any possible matching non extension_ package
 7267:     foreach my $package (@specifics) {
 7268: 	my (undef,$pack_type,$pack_part)=@{$package};
 7269: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7270: 	    return $packagetab{"$pack_type&$name&default"};
 7271: 	}
 7272: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7273: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7274: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7275: 	}
 7276:     }
 7277:     # look for any posible extension_ match
 7278:     foreach my $package (@extension) {
 7279: 	my ($package,$pack_type)=@{$package};
 7280: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7281: 	    return $packagetab{"$pack_type&$name&default"};
 7282: 	}
 7283: 	if (defined($packagetab{$package."&$name&default"})) {
 7284: 	    return $packagetab{$package."&$name&default"};
 7285: 	}
 7286:     }
 7287:     # look for a global default setting
 7288:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7289: 	return $packagetab{"default&$name&default"};
 7290:     }
 7291:     return undef;
 7292: }
 7293: 
 7294: sub add_prefix_and_part {
 7295:     my ($prefix,$part)=@_;
 7296:     my $keyroot;
 7297:     if (defined($prefix) && $prefix !~ /^__/) {
 7298: 	# prefix that has a part already
 7299: 	$keyroot=$prefix;
 7300:     } elsif (defined($prefix)) {
 7301: 	# prefix that is missing a part
 7302: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7303:     } else {
 7304: 	# no prefix at all
 7305: 	if (defined($part)) { $keyroot='_'.$part; }
 7306:     }
 7307:     return $keyroot;
 7308: }
 7309: 
 7310: # ---------------------------------------------------------------- Get metadata
 7311: 
 7312: my %metaentry;
 7313: sub metadata {
 7314:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7315:     $uri=&declutter($uri);
 7316:     # if it is a non metadata possible uri return quickly
 7317:     if (($uri eq '') || 
 7318: 	(($uri =~ m|^/*adm/|) && 
 7319: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7320:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7321: 	return undef;
 7322:     }
 7323:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7324: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7325: 	return undef;
 7326:     }
 7327:     my $filename=$uri;
 7328:     $uri=~s/\.meta$//;
 7329: #
 7330: # Is the metadata already cached?
 7331: # Look at timestamp of caching
 7332: # Everything is cached by the main uri, libraries are never directly cached
 7333: #
 7334:     if (!defined($liburi)) {
 7335: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7336: 	if (defined($cached)) { return $result->{':'.$what}; }
 7337:     }
 7338:     {
 7339: #
 7340: # Is this a recursive call for a library?
 7341: #
 7342: #	if (! exists($metacache{$uri})) {
 7343: #	    $metacache{$uri}={};
 7344: #	}
 7345: 	my $cachetime = 60*60;
 7346:         if ($liburi) {
 7347: 	    $liburi=&declutter($liburi);
 7348:             $filename=$liburi;
 7349:         } else {
 7350: 	    &devalidate_cache_new('meta',$uri);
 7351: 	    undef(%metaentry);
 7352: 	}
 7353:         my %metathesekeys=();
 7354:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7355: 	my $metastring;
 7356: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7357: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7358: 	    $metastring = 
 7359: 		&Apache::lonnet::ssi_body($which,
 7360: 					  ('grade_target' => 'meta'));
 7361: 	    $cachetime = 1; # only want this cached in the child not long term
 7362: 	} elsif ($uri !~ m -^(editupload)/-) {
 7363: 	    my $file=&filelocation('',&clutter($filename));
 7364: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7365: 	    $metastring=&getfile($file);
 7366: 	}
 7367:         my $parser=HTML::LCParser->new(\$metastring);
 7368:         my $token;
 7369:         undef %metathesekeys;
 7370:         while ($token=$parser->get_token) {
 7371: 	    if ($token->[0] eq 'S') {
 7372: 		if (defined($token->[2]->{'package'})) {
 7373: #
 7374: # This is a package - get package info
 7375: #
 7376: 		    my $package=$token->[2]->{'package'};
 7377: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7378: 		    if (defined($token->[2]->{'id'})) { 
 7379: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7380: 		    }
 7381: 		    if ($metaentry{':packages'}) {
 7382: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7383: 		    } else {
 7384: 			$metaentry{':packages'}=$package.$keyroot;
 7385: 		    }
 7386: 		    foreach my $pack_entry (keys(%packagetab)) {
 7387: 			my $part=$keyroot;
 7388: 			$part=~s/^\_//;
 7389: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7390: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7391: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7392: 			    # ignore package.tab specified default values
 7393:                             # here &package_tab_default() will fetch those
 7394: 			    if ($subp eq 'default') { next; }
 7395: 			    my $value=$packagetab{$pack_entry};
 7396: 			    my $unikey;
 7397: 			    if ($pack =~ /_0$/) {
 7398: 				$unikey='parameter_0_'.$name;
 7399: 				$part=0;
 7400: 			    } else {
 7401: 				$unikey='parameter'.$keyroot.'_'.$name;
 7402: 			    }
 7403: 			    if ($subp eq 'display') {
 7404: 				$value.=' [Part: '.$part.']';
 7405: 			    }
 7406: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7407: 			    $metathesekeys{$unikey}=1;
 7408: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7409: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7410: 			    }
 7411: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7412: 				$metaentry{':'.$unikey}=
 7413: 				    $metaentry{':'.$unikey.'.default'};
 7414: 			    }
 7415: 			}
 7416: 		    }
 7417: 		} else {
 7418: #
 7419: # This is not a package - some other kind of start tag
 7420: #
 7421: 		    my $entry=$token->[1];
 7422: 		    my $unikey;
 7423: 		    if ($entry eq 'import') {
 7424: 			$unikey='';
 7425: 		    } else {
 7426: 			$unikey=$entry;
 7427: 		    }
 7428: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7429: 
 7430: 		    if (defined($token->[2]->{'id'})) { 
 7431: 			$unikey.='_'.$token->[2]->{'id'}; 
 7432: 		    }
 7433: 
 7434: 		    if ($entry eq 'import') {
 7435: #
 7436: # Importing a library here
 7437: #
 7438: 			if ($depthcount<20) {
 7439: 			    my $location=$parser->get_text('/import');
 7440: 			    my $dir=$filename;
 7441: 			    $dir=~s|[^/]*$||;
 7442: 			    $location=&filelocation($dir,$location);
 7443: 			    my $metadata = 
 7444: 				&metadata($uri,'keys', $location,$unikey,
 7445: 					  $depthcount+1);
 7446: 			    foreach my $meta (split(',',$metadata)) {
 7447: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7448: 				$metathesekeys{$meta}=1;
 7449: 			    }
 7450: 			}
 7451: 		    } else { 
 7452: 			
 7453: 			if (defined($token->[2]->{'name'})) { 
 7454: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7455: 			}
 7456: 			$metathesekeys{$unikey}=1;
 7457: 			foreach my $param (@{$token->[3]}) {
 7458: 			    $metaentry{':'.$unikey.'.'.$param} =
 7459: 				$token->[2]->{$param};
 7460: 			}
 7461: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7462: 			my $default=$metaentry{':'.$unikey.'.default'};
 7463: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7464: 		 # only ws inside the tag, and not in default, so use default
 7465: 		 # as value
 7466: 			    $metaentry{':'.$unikey}=$default;
 7467: 			} elsif ( $internaltext =~ /\S/ ) {
 7468: 		  # something interesting inside the tag
 7469: 			    $metaentry{':'.$unikey}=$internaltext;
 7470: 			} else {
 7471: 		  # no interesting values, don't set a default
 7472: 			}
 7473: # end of not-a-package not-a-library import
 7474: 		    }
 7475: # end of not-a-package start tag
 7476: 		}
 7477: # the next is the end of "start tag"
 7478: 	    }
 7479: 	}
 7480: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7481: 	$extension = lc($extension);
 7482: 	if ($extension eq 'htm') { $extension='html'; }
 7483: 
 7484: 	foreach my $key (keys(%packagetab)) {
 7485: 	    #no specific packages #how's our extension
 7486: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7487: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7488: 					 \%metathesekeys);
 7489: 	}
 7490: 
 7491: 	if (!exists($metaentry{':packages'})
 7492: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7493: 	    foreach my $key (keys(%packagetab)) {
 7494: 		#no specific packages well let's get default then
 7495: 		if ($key!~/^default&/) { next; }
 7496: 		&metadata_create_package_def($uri,$key,'default',
 7497: 					     \%metathesekeys);
 7498: 	    }
 7499: 	}
 7500: # are there custom rights to evaluate
 7501: 	if ($metaentry{':copyright'} eq 'custom') {
 7502: 
 7503:     #
 7504:     # Importing a rights file here
 7505:     #
 7506: 	    unless ($depthcount) {
 7507: 		my $location=$metaentry{':customdistributionfile'};
 7508: 		my $dir=$filename;
 7509: 		$dir=~s|[^/]*$||;
 7510: 		$location=&filelocation($dir,$location);
 7511: 		my $rights_metadata =
 7512: 		    &metadata($uri,'keys',$location,'_rights',
 7513: 			      $depthcount+1);
 7514: 		foreach my $rights (split(',',$rights_metadata)) {
 7515: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7516: 		    $metathesekeys{$rights}=1;
 7517: 		}
 7518: 	    }
 7519: 	}
 7520: 	# uniqifiy package listing
 7521: 	my %seen;
 7522: 	my @uniq_packages =
 7523: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7524: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7525: 
 7526: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7527: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7528: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7529: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7530: # this is the end of "was not already recently cached
 7531:     }
 7532:     return $metaentry{':'.$what};
 7533: }
 7534: 
 7535: sub metadata_create_package_def {
 7536:     my ($uri,$key,$package,$metathesekeys)=@_;
 7537:     my ($pack,$name,$subp)=split(/\&/,$key);
 7538:     if ($subp eq 'default') { next; }
 7539:     
 7540:     if (defined($metaentry{':packages'})) {
 7541: 	$metaentry{':packages'}.=','.$package;
 7542:     } else {
 7543: 	$metaentry{':packages'}=$package;
 7544:     }
 7545:     my $value=$packagetab{$key};
 7546:     my $unikey;
 7547:     $unikey='parameter_0_'.$name;
 7548:     $metaentry{':'.$unikey.'.part'}=0;
 7549:     $$metathesekeys{$unikey}=1;
 7550:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7551: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7552:     }
 7553:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7554: 	$metaentry{':'.$unikey}=
 7555: 	    $metaentry{':'.$unikey.'.default'};
 7556:     }
 7557: }
 7558: 
 7559: sub metadata_generate_part0 {
 7560:     my ($metadata,$metacache,$uri) = @_;
 7561:     my %allnames;
 7562:     foreach my $metakey (keys(%$metadata)) {
 7563: 	if ($metakey=~/^parameter\_(.*)/) {
 7564: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7565: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7566: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7567: 	    $allnames{$name}=$part;
 7568: 	  }
 7569: 	}
 7570:     }
 7571:     foreach my $name (keys(%allnames)) {
 7572:       $$metadata{"parameter_0_$name"}=1;
 7573:       my $key=":parameter_0_$name";
 7574:       $$metacache{"$key.part"}='0';
 7575:       $$metacache{"$key.name"}=$name;
 7576:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7577: 					   $allnames{$name}.'_'.$name.
 7578: 					   '.type'};
 7579:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7580: 			     '.display'};
 7581:       my $expr='[Part: '.$allnames{$name}.']';
 7582:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7583:       $$metacache{"$key.display"}=$olddis;
 7584:     }
 7585: }
 7586: 
 7587: # ------------------------------------------------------ Devalidate title cache
 7588: 
 7589: sub devalidate_title_cache {
 7590:     my ($url)=@_;
 7591:     if (!$env{'request.course.id'}) { return; }
 7592:     my $symb=&symbread($url);
 7593:     if (!$symb) { return; }
 7594:     my $key=$env{'request.course.id'}."\0".$symb;
 7595:     &devalidate_cache_new('title',$key);
 7596: }
 7597: 
 7598: # ------------------------------------------------- Get the title of a resource
 7599: 
 7600: sub gettitle {
 7601:     my $urlsymb=shift;
 7602:     my $symb=&symbread($urlsymb);
 7603:     if ($symb) {
 7604: 	my $key=$env{'request.course.id'}."\0".$symb;
 7605: 	my ($result,$cached)=&is_cached_new('title',$key);
 7606: 	if (defined($cached)) { 
 7607: 	    return $result;
 7608: 	}
 7609: 	my ($map,$resid,$url)=&decode_symb($symb);
 7610: 	my $title='';
 7611: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7612: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7613: 	} else {
 7614: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7615: 		    &GDBM_READER(),0640)) {
 7616: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7617: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7618: 		untie(%bighash);
 7619: 	    }
 7620: 	}
 7621: 	$title=~s/\&colon\;/\:/gs;
 7622: 	if ($title) {
 7623: 	    return &do_cache_new('title',$key,$title,600);
 7624: 	}
 7625: 	$urlsymb=$url;
 7626:     }
 7627:     my $title=&metadata($urlsymb,'title');
 7628:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7629:     return $title;
 7630: }
 7631: 
 7632: sub get_slot {
 7633:     my ($which,$cnum,$cdom)=@_;
 7634:     if (!$cnum || !$cdom) {
 7635: 	(undef,my $courseid)=&whichuser();
 7636: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7637: 	$cnum=$env{'course.'.$courseid.'.num'};
 7638:     }
 7639:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7640:     my %slotinfo;
 7641:     if (exists($remembered{$key})) {
 7642: 	$slotinfo{$which} = $remembered{$key};
 7643:     } else {
 7644: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7645: 	&Apache::lonhomework::showhash(%slotinfo);
 7646: 	my ($tmp)=keys(%slotinfo);
 7647: 	if ($tmp=~/^error:/) { return (); }
 7648: 	$remembered{$key} = $slotinfo{$which};
 7649:     }
 7650:     if (ref($slotinfo{$which}) eq 'HASH') {
 7651: 	return %{$slotinfo{$which}};
 7652:     }
 7653:     return $slotinfo{$which};
 7654: }
 7655: # ------------------------------------------------- Update symbolic store links
 7656: 
 7657: sub symblist {
 7658:     my ($mapname,%newhash)=@_;
 7659:     $mapname=&deversion(&declutter($mapname));
 7660:     my %hash;
 7661:     if (($env{'request.course.fn'}) && (%newhash)) {
 7662:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7663:                       &GDBM_WRCREAT(),0640)) {
 7664: 	    foreach my $url (keys %newhash) {
 7665: 		next if ($url eq 'last_known'
 7666: 			 && $env{'form.no_update_last_known'});
 7667: 		$hash{declutter($url)}=&encode_symb($mapname,
 7668: 						    $newhash{$url}->[1],
 7669: 						    $newhash{$url}->[0]);
 7670:             }
 7671:             if (untie(%hash)) {
 7672: 		return 'ok';
 7673:             }
 7674:         }
 7675:     }
 7676:     return 'error';
 7677: }
 7678: 
 7679: # --------------------------------------------------------------- Verify a symb
 7680: 
 7681: sub symbverify {
 7682:     my ($symb,$thisurl)=@_;
 7683:     my $thisfn=$thisurl;
 7684:     $thisfn=&declutter($thisfn);
 7685: # direct jump to resource in page or to a sequence - will construct own symbs
 7686:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7687: # check URL part
 7688:     my ($map,$resid,$url)=&decode_symb($symb);
 7689: 
 7690:     unless ($url eq $thisfn) { return 0; }
 7691: 
 7692:     $symb=&symbclean($symb);
 7693:     $thisurl=&deversion($thisurl);
 7694:     $thisfn=&deversion($thisfn);
 7695: 
 7696:     my %bighash;
 7697:     my $okay=0;
 7698: 
 7699:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7700:                             &GDBM_READER(),0640)) {
 7701:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7702:         unless ($ids) { 
 7703:            $ids=$bighash{'ids_/'.$thisurl};
 7704:         }
 7705:         if ($ids) {
 7706: # ------------------------------------------------------------------- Has ID(s)
 7707: 	    foreach my $id (split(/\,/,$ids)) {
 7708: 	       my ($mapid,$resid)=split(/\./,$id);
 7709:                if (
 7710:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7711:    eq $symb) { 
 7712: 		   if (($env{'request.role.adv'}) ||
 7713: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7714: 		       $okay=1; 
 7715: 		   }
 7716: 	       }
 7717: 	   }
 7718:         }
 7719: 	untie(%bighash);
 7720:     }
 7721:     return $okay;
 7722: }
 7723: 
 7724: # --------------------------------------------------------------- Clean-up symb
 7725: 
 7726: sub symbclean {
 7727:     my $symb=shift;
 7728:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7729: # remove version from map
 7730:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7731: 
 7732: # remove version from URL
 7733:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7734: 
 7735: # remove wrapper
 7736: 
 7737:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7738:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7739:     return $symb;
 7740: }
 7741: 
 7742: # ---------------------------------------------- Split symb to find map and url
 7743: 
 7744: sub encode_symb {
 7745:     my ($map,$resid,$url)=@_;
 7746:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7747: }
 7748: 
 7749: sub decode_symb {
 7750:     my $symb=shift;
 7751:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7752:     my ($map,$resid,$url)=split(/___/,$symb);
 7753:     return (&fixversion($map),$resid,&fixversion($url));
 7754: }
 7755: 
 7756: sub fixversion {
 7757:     my $fn=shift;
 7758:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7759:     my %bighash;
 7760:     my $uri=&clutter($fn);
 7761:     my $key=$env{'request.course.id'}.'_'.$uri;
 7762: # is this cached?
 7763:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7764:     if (defined($cached)) { return $result; }
 7765: # unfortunately not cached, or expired
 7766:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7767: 	    &GDBM_READER(),0640)) {
 7768:  	if ($bighash{'version_'.$uri}) {
 7769:  	    my $version=$bighash{'version_'.$uri};
 7770:  	    unless (($version eq 'mostrecent') || 
 7771: 		    ($version==&getversion($uri))) {
 7772:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7773:  	    }
 7774:  	}
 7775:  	untie %bighash;
 7776:     }
 7777:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7778: }
 7779: 
 7780: sub deversion {
 7781:     my $url=shift;
 7782:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7783:     return $url;
 7784: }
 7785: 
 7786: # ------------------------------------------------------ Return symb list entry
 7787: 
 7788: sub symbread {
 7789:     my ($thisfn,$donotrecurse)=@_;
 7790:     my $cache_str='request.symbread.cached.'.$thisfn;
 7791:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7792: # no filename provided? try from environment
 7793:     unless ($thisfn) {
 7794:         if ($env{'request.symb'}) {
 7795: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7796: 	}
 7797: 	$thisfn=$env{'request.filename'};
 7798:     }
 7799:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7800: # is that filename actually a symb? Verify, clean, and return
 7801:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7802: 	if (&symbverify($thisfn,$1)) {
 7803: 	    return $env{$cache_str}=&symbclean($thisfn);
 7804: 	}
 7805:     }
 7806:     $thisfn=declutter($thisfn);
 7807:     my %hash;
 7808:     my %bighash;
 7809:     my $syval='';
 7810:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7811:         my $targetfn = $thisfn;
 7812:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7813:             $targetfn = 'adm/wrapper/'.$thisfn;
 7814:         }
 7815: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7816: 	    $targetfn=$1;
 7817: 	}
 7818:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7819:                       &GDBM_READER(),0640)) {
 7820: 	    $syval=$hash{$targetfn};
 7821:             untie(%hash);
 7822:         }
 7823: # ---------------------------------------------------------- There was an entry
 7824:         if ($syval) {
 7825: 	    #unless ($syval=~/\_\d+$/) {
 7826: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7827: 		    #&appenv({'request.ambiguous' => $thisfn});
 7828: 		    #return $env{$cache_str}='';
 7829: 		#}    
 7830: 		#$syval.=$1;
 7831: 	    #}
 7832:         } else {
 7833: # ------------------------------------------------------- Was not in symb table
 7834:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7835:                             &GDBM_READER(),0640)) {
 7836: # ---------------------------------------------- Get ID(s) for current resource
 7837:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7838:               unless ($ids) { 
 7839:                  $ids=$bighash{'ids_/'.$thisfn};
 7840:               }
 7841:               unless ($ids) {
 7842: # alias?
 7843: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7844:               }
 7845:               if ($ids) {
 7846: # ------------------------------------------------------------------- Has ID(s)
 7847:                  my @possibilities=split(/\,/,$ids);
 7848:                  if ($#possibilities==0) {
 7849: # ----------------------------------------------- There is only one possibility
 7850: 		     my ($mapid,$resid)=split(/\./,$ids);
 7851: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7852: 						    $resid,$thisfn);
 7853:                  } elsif (!$donotrecurse) {
 7854: # ------------------------------------------ There is more than one possibility
 7855:                      my $realpossible=0;
 7856:                      foreach my $id (@possibilities) {
 7857: 			 my $file=$bighash{'src_'.$id};
 7858:                          if (&allowed('bre',$file)) {
 7859:          		    my ($mapid,$resid)=split(/\./,$id);
 7860:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7861: 				$realpossible++;
 7862:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7863: 						    $resid,$thisfn);
 7864:                             }
 7865: 			 }
 7866:                      }
 7867: 		     if ($realpossible!=1) { $syval=''; }
 7868:                  } else {
 7869:                      $syval='';
 7870:                  }
 7871: 	      }
 7872:               untie(%bighash)
 7873:            }
 7874:         }
 7875:         if ($syval) {
 7876: 	    return $env{$cache_str}=$syval;
 7877:         }
 7878:     }
 7879:     &appenv({'request.ambiguous' => $thisfn});
 7880:     return $env{$cache_str}='';
 7881: }
 7882: 
 7883: # ---------------------------------------------------------- Return random seed
 7884: 
 7885: sub numval {
 7886:     my $txt=shift;
 7887:     $txt=~tr/A-J/0-9/;
 7888:     $txt=~tr/a-j/0-9/;
 7889:     $txt=~tr/K-T/0-9/;
 7890:     $txt=~tr/k-t/0-9/;
 7891:     $txt=~tr/U-Z/0-5/;
 7892:     $txt=~tr/u-z/0-5/;
 7893:     $txt=~s/\D//g;
 7894:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7895:     return int($txt);
 7896: }
 7897: 
 7898: sub numval2 {
 7899:     my $txt=shift;
 7900:     $txt=~tr/A-J/0-9/;
 7901:     $txt=~tr/a-j/0-9/;
 7902:     $txt=~tr/K-T/0-9/;
 7903:     $txt=~tr/k-t/0-9/;
 7904:     $txt=~tr/U-Z/0-5/;
 7905:     $txt=~tr/u-z/0-5/;
 7906:     $txt=~s/\D//g;
 7907:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7908:     my $total;
 7909:     foreach my $val (@txts) { $total+=$val; }
 7910:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7911:     return int($total);
 7912: }
 7913: 
 7914: sub numval3 {
 7915:     use integer;
 7916:     my $txt=shift;
 7917:     $txt=~tr/A-J/0-9/;
 7918:     $txt=~tr/a-j/0-9/;
 7919:     $txt=~tr/K-T/0-9/;
 7920:     $txt=~tr/k-t/0-9/;
 7921:     $txt=~tr/U-Z/0-5/;
 7922:     $txt=~tr/u-z/0-5/;
 7923:     $txt=~s/\D//g;
 7924:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7925:     my $total;
 7926:     foreach my $val (@txts) { $total+=$val; }
 7927:     if ($_64bit) { $total=(($total<<32)>>32); }
 7928:     return $total;
 7929: }
 7930: 
 7931: sub digest {
 7932:     my ($data)=@_;
 7933:     my $digest=&Digest::MD5::md5($data);
 7934:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7935:     my ($e,$f);
 7936:     {
 7937:         use integer;
 7938:         $e=($a+$b);
 7939:         $f=($c+$d);
 7940:         if ($_64bit) {
 7941:             $e=(($e<<32)>>32);
 7942:             $f=(($f<<32)>>32);
 7943:         }
 7944:     }
 7945:     if (wantarray) {
 7946: 	return ($e,$f);
 7947:     } else {
 7948: 	my $g;
 7949: 	{
 7950: 	    use integer;
 7951: 	    $g=($e+$f);
 7952: 	    if ($_64bit) {
 7953: 		$g=(($g<<32)>>32);
 7954: 	    }
 7955: 	}
 7956: 	return $g;
 7957:     }
 7958: }
 7959: 
 7960: sub latest_rnd_algorithm_id {
 7961:     return '64bit5';
 7962: }
 7963: 
 7964: sub get_rand_alg {
 7965:     my ($courseid)=@_;
 7966:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7967:     if ($courseid) {
 7968: 	return $env{"course.$courseid.rndseed"};
 7969:     }
 7970:     return &latest_rnd_algorithm_id();
 7971: }
 7972: 
 7973: sub validCODE {
 7974:     my ($CODE)=@_;
 7975:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7976:     return 0;
 7977: }
 7978: 
 7979: sub getCODE {
 7980:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7981:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7982: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7983: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7984: 	return $Apache::lonhomework::history{'resource.CODE'};
 7985:     }
 7986:     return undef;
 7987: }
 7988: 
 7989: sub rndseed {
 7990:     my ($symb,$courseid,$domain,$username)=@_;
 7991:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7992:     if (!defined($symb)) {
 7993: 	unless ($symb=$wsymb) { return time; }
 7994:     }
 7995:     if (!$courseid) { $courseid=$wcourseid; }
 7996:     if (!$domain) { $domain=$wdomain; }
 7997:     if (!$username) { $username=$wusername }
 7998:     my $which=&get_rand_alg();
 7999: 
 8000:     if (defined(&getCODE())) {
 8001: 	if ($which eq '64bit5') {
 8002: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8003: 	} elsif ($which eq '64bit4') {
 8004: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8005: 	} else {
 8006: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8007: 	}
 8008:     } elsif ($which eq '64bit5') {
 8009: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8010:     } elsif ($which eq '64bit4') {
 8011: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8012:     } elsif ($which eq '64bit3') {
 8013: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8014:     } elsif ($which eq '64bit2') {
 8015: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8016:     } elsif ($which eq '64bit') {
 8017: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8018:     }
 8019:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8020: }
 8021: 
 8022: sub rndseed_32bit {
 8023:     my ($symb,$courseid,$domain,$username)=@_;
 8024:     {
 8025: 	use integer;
 8026: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8027: 	my $symbseed=numval($symb) << 22;
 8028: 	my $namechck=unpack("%32C*",$username) << 17;
 8029: 	my $nameseed=numval($username) << 12;
 8030: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8031: 	my $courseseed=unpack("%32C*",$courseid);
 8032: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8033: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8034: 	#&logthis("rndseed :$num:$symb");
 8035: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8036: 	return $num;
 8037:     }
 8038: }
 8039: 
 8040: sub rndseed_64bit {
 8041:     my ($symb,$courseid,$domain,$username)=@_;
 8042:     {
 8043: 	use integer;
 8044: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8045: 	my $symbseed=numval($symb) << 10;
 8046: 	my $namechck=unpack("%32S*",$username);
 8047: 	
 8048: 	my $nameseed=numval($username) << 21;
 8049: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8050: 	my $courseseed=unpack("%32S*",$courseid);
 8051: 	
 8052: 	my $num1=$symbchck+$symbseed+$namechck;
 8053: 	my $num2=$nameseed+$domainseed+$courseseed;
 8054: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8055: 	#&logthis("rndseed :$num:$symb");
 8056: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8057: 	return "$num1,$num2";
 8058:     }
 8059: }
 8060: 
 8061: sub rndseed_64bit2 {
 8062:     my ($symb,$courseid,$domain,$username)=@_;
 8063:     {
 8064: 	use integer;
 8065: 	# strings need to be an even # of cahracters long, it it is odd the
 8066:         # last characters gets thrown away
 8067: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8068: 	my $symbseed=numval($symb) << 10;
 8069: 	my $namechck=unpack("%32S*",$username.' ');
 8070: 	
 8071: 	my $nameseed=numval($username) << 21;
 8072: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8073: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8074: 	
 8075: 	my $num1=$symbchck+$symbseed+$namechck;
 8076: 	my $num2=$nameseed+$domainseed+$courseseed;
 8077: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8078: 	#&logthis("rndseed :$num:$symb");
 8079: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8080: 	return "$num1,$num2";
 8081:     }
 8082: }
 8083: 
 8084: sub rndseed_64bit3 {
 8085:     my ($symb,$courseid,$domain,$username)=@_;
 8086:     {
 8087: 	use integer;
 8088: 	# strings need to be an even # of cahracters long, it it is odd the
 8089:         # last characters gets thrown away
 8090: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8091: 	my $symbseed=numval2($symb) << 10;
 8092: 	my $namechck=unpack("%32S*",$username.' ');
 8093: 	
 8094: 	my $nameseed=numval2($username) << 21;
 8095: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8096: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8097: 	
 8098: 	my $num1=$symbchck+$symbseed+$namechck;
 8099: 	my $num2=$nameseed+$domainseed+$courseseed;
 8100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8101: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8102: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8103: 	
 8104: 	return "$num1:$num2";
 8105:     }
 8106: }
 8107: 
 8108: sub rndseed_64bit4 {
 8109:     my ($symb,$courseid,$domain,$username)=@_;
 8110:     {
 8111: 	use integer;
 8112: 	# strings need to be an even # of cahracters long, it it is odd the
 8113:         # last characters gets thrown away
 8114: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8115: 	my $symbseed=numval3($symb) << 10;
 8116: 	my $namechck=unpack("%32S*",$username.' ');
 8117: 	
 8118: 	my $nameseed=numval3($username) << 21;
 8119: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8120: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8121: 	
 8122: 	my $num1=$symbchck+$symbseed+$namechck;
 8123: 	my $num2=$nameseed+$domainseed+$courseseed;
 8124: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8125: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8126: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8127: 	
 8128: 	return "$num1:$num2";
 8129:     }
 8130: }
 8131: 
 8132: sub rndseed_64bit5 {
 8133:     my ($symb,$courseid,$domain,$username)=@_;
 8134:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8135:     return "$num1:$num2";
 8136: }
 8137: 
 8138: sub rndseed_CODE_64bit {
 8139:     my ($symb,$courseid,$domain,$username)=@_;
 8140:     {
 8141: 	use integer;
 8142: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8143: 	my $symbseed=numval2($symb);
 8144: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8145: 	my $CODEseed=numval(&getCODE());
 8146: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8147: 	my $num1=$symbseed+$CODEchck;
 8148: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8149: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8150: 	#&logthis("rndseed :$num1:$num2:$symb");
 8151: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8152: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8153: 	return "$num1:$num2";
 8154:     }
 8155: }
 8156: 
 8157: sub rndseed_CODE_64bit4 {
 8158:     my ($symb,$courseid,$domain,$username)=@_;
 8159:     {
 8160: 	use integer;
 8161: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8162: 	my $symbseed=numval3($symb);
 8163: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8164: 	my $CODEseed=numval3(&getCODE());
 8165: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8166: 	my $num1=$symbseed+$CODEchck;
 8167: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8168: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8169: 	#&logthis("rndseed :$num1:$num2:$symb");
 8170: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8171: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8172: 	return "$num1:$num2";
 8173:     }
 8174: }
 8175: 
 8176: sub rndseed_CODE_64bit5 {
 8177:     my ($symb,$courseid,$domain,$username)=@_;
 8178:     my $code = &getCODE();
 8179:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8180:     return "$num1:$num2";
 8181: }
 8182: 
 8183: sub setup_random_from_rndseed {
 8184:     my ($rndseed)=@_;
 8185:     if ($rndseed =~/([,:])/) {
 8186: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8187: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8188:     } else {
 8189: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8190:     }
 8191: }
 8192: 
 8193: sub latest_receipt_algorithm_id {
 8194:     return 'receipt3';
 8195: }
 8196: 
 8197: sub recunique {
 8198:     my $fucourseid=shift;
 8199:     my $unique;
 8200:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8201: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8202: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8203:     } else {
 8204: 	$unique=$perlvar{'lonReceipt'};
 8205:     }
 8206:     return unpack("%32C*",$unique);
 8207: }
 8208: 
 8209: sub recprefix {
 8210:     my $fucourseid=shift;
 8211:     my $prefix;
 8212:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8213: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8214: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8215:     } else {
 8216: 	$prefix=$perlvar{'lonHostID'};
 8217:     }
 8218:     return unpack("%32C*",$prefix);
 8219: }
 8220: 
 8221: sub ireceipt {
 8222:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8223: 
 8224:     my $return =&recprefix($fucourseid).'-';
 8225: 
 8226:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8227: 	$env{'request.state'} eq 'construct') {
 8228: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8229: 	return $return;
 8230:     }
 8231: 
 8232:     my $cuname=unpack("%32C*",$funame);
 8233:     my $cudom=unpack("%32C*",$fudom);
 8234:     my $cucourseid=unpack("%32C*",$fucourseid);
 8235:     my $cusymb=unpack("%32C*",$fusymb);
 8236:     my $cunique=&recunique($fucourseid);
 8237:     my $cpart=unpack("%32S*",$part);
 8238:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8239: 
 8240: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8241: 			       
 8242: 	$return.= ($cunique%$cuname+
 8243: 		   $cunique%$cudom+
 8244: 		   $cusymb%$cuname+
 8245: 		   $cusymb%$cudom+
 8246: 		   $cucourseid%$cuname+
 8247: 		   $cucourseid%$cudom+
 8248: 		   $cpart%$cuname+
 8249: 		   $cpart%$cudom);
 8250:     } else {
 8251: 	$return.= ($cunique%$cuname+
 8252: 		   $cunique%$cudom+
 8253: 		   $cusymb%$cuname+
 8254: 		   $cusymb%$cudom+
 8255: 		   $cucourseid%$cuname+
 8256: 		   $cucourseid%$cudom);
 8257:     }
 8258:     return $return;
 8259: }
 8260: 
 8261: sub receipt {
 8262:     my ($part)=@_;
 8263:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8264:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8265: }
 8266: 
 8267: sub whichuser {
 8268:     my ($passedsymb)=@_;
 8269:     my ($symb,$courseid,$domain,$name,$publicuser);
 8270:     if (defined($env{'form.grade_symb'})) {
 8271: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8272: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8273: 	if (!$allowed &&
 8274: 	    exists($env{'request.course.sec'}) &&
 8275: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8276: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8277: 			      '/'.$env{'request.course.sec'});
 8278: 	}
 8279: 	if ($allowed) {
 8280: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8281: 	    $courseid=$tmp_courseid;
 8282: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8283: 	    ($name)=&get_env_multiple('form.grade_username');
 8284: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8285: 	}
 8286:     }
 8287:     if (!$passedsymb) {
 8288: 	$symb=&symbread();
 8289:     } else {
 8290: 	$symb=$passedsymb;
 8291:     }
 8292:     $courseid=$env{'request.course.id'};
 8293:     $domain=$env{'user.domain'};
 8294:     $name=$env{'user.name'};
 8295:     if ($name eq 'public' && $domain eq 'public') {
 8296: 	if (!defined($env{'form.username'})) {
 8297: 	    $env{'form.username'}.=time.rand(10000000);
 8298: 	}
 8299: 	$name.=$env{'form.username'};
 8300:     }
 8301:     return ($symb,$courseid,$domain,$name,$publicuser);
 8302: 
 8303: }
 8304: 
 8305: # ------------------------------------------------------------ Serves up a file
 8306: # returns either the contents of the file or 
 8307: # -1 if the file doesn't exist
 8308: #
 8309: # if the target is a file that was uploaded via DOCS, 
 8310: # a check will be made to see if a current copy exists on the local server,
 8311: # if it does this will be served, otherwise a copy will be retrieved from
 8312: # the home server for the course and stored in /home/httpd/html/userfiles on
 8313: # the local server.   
 8314: 
 8315: sub getfile {
 8316:     my ($file) = @_;
 8317:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8318:     &repcopy($file);
 8319:     return &readfile($file);
 8320: }
 8321: 
 8322: sub repcopy_userfile {
 8323:     my ($file)=@_;
 8324:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8325:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8326:     my ($cdom,$cnum,$filename) = 
 8327: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8328:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8329:     if (-e "$file") {
 8330: # we already have a local copy, check it out
 8331: 	my @fileinfo = stat($file);
 8332: 	my $rtncode;
 8333: 	my $info;
 8334: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8335: 	if ($lwpresp ne 'ok') {
 8336: # there is no such file anymore, even though we had a local copy
 8337: 	    if ($rtncode eq '404') {
 8338: 		unlink($file);
 8339: 	    }
 8340: 	    return -1;
 8341: 	}
 8342: 	if ($info < $fileinfo[9]) {
 8343: # nice, the file we have is up-to-date, just say okay
 8344: 	    return 'ok';
 8345: 	} else {
 8346: # the file is outdated, get rid of it
 8347: 	    unlink($file);
 8348: 	}
 8349:     }
 8350: # one way or the other, at this point, we don't have the file
 8351: # construct the correct path for the file
 8352:     my @parts = ($cdom,$cnum); 
 8353:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8354: 	push @parts, split(/\//,$1);
 8355:     }
 8356:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8357:     foreach my $part (@parts) {
 8358: 	$path .= '/'.$part;
 8359: 	if (!-e $path) {
 8360: 	    mkdir($path,0770);
 8361: 	}
 8362:     }
 8363: # now the path exists for sure
 8364: # get a user agent
 8365:     my $ua=new LWP::UserAgent;
 8366:     my $transferfile=$file.'.in.transfer';
 8367: # FIXME: this should flock
 8368:     if (-e $transferfile) { return 'ok'; }
 8369:     my $request;
 8370:     $uri=~s/^\///;
 8371:     my $homeserver = &homeserver($cnum,$cdom);
 8372:     my $protocol = $protocol{$homeserver};
 8373:     $protocol = 'http' if ($protocol ne 'https');
 8374:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8375:     my $response=$ua->request($request,$transferfile);
 8376: # did it work?
 8377:     if ($response->is_error()) {
 8378: 	unlink($transferfile);
 8379: 	&logthis("Userfile repcopy failed for $uri");
 8380: 	return -1;
 8381:     }
 8382: # worked, rename the transfer file
 8383:     rename($transferfile,$file);
 8384:     return 'ok';
 8385: }
 8386: 
 8387: sub tokenwrapper {
 8388:     my $uri=shift;
 8389:     $uri=~s|^https?\://([^/]+)||;
 8390:     $uri=~s|^/||;
 8391:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8392:     my $token=$1;
 8393:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8394:     if ($udom && $uname && $file) {
 8395: 	$file=~s|(\?\.*)*$||;
 8396:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8397:         my $homeserver = &homeserver($uname,$udom);
 8398:         my $protocol = $protocol{$homeserver};
 8399:         $protocol = 'http' if ($protocol ne 'https');
 8400:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8401:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8402:                                '&tokenissued='.$perlvar{'lonHostID'};
 8403:     } else {
 8404:         return '/adm/notfound.html';
 8405:     }
 8406: }
 8407: 
 8408: # call with reqtype HEAD: get last modification time
 8409: # call with reqtype GET: get the file contents
 8410: # Do not call this with reqtype GET for large files! It loads everything into memory
 8411: #
 8412: sub getuploaded {
 8413:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8414:     $uri=~s/^\///;
 8415:     my $homeserver = &homeserver($cnum,$cdom);
 8416:     my $protocol = $protocol{$homeserver};
 8417:     $protocol = 'http' if ($protocol ne 'https');
 8418:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8419:     my $ua=new LWP::UserAgent;
 8420:     my $request=new HTTP::Request($reqtype,$uri);
 8421:     my $response=$ua->request($request);
 8422:     $$rtncode = $response->code;
 8423:     if (! $response->is_success()) {
 8424: 	return 'failed';
 8425:     }      
 8426:     if ($reqtype eq 'HEAD') {
 8427: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8428:     } elsif ($reqtype eq 'GET') {
 8429: 	$$info = $response->content;
 8430:     }
 8431:     return 'ok';
 8432: }
 8433: 
 8434: sub readfile {
 8435:     my $file = shift;
 8436:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8437:     my $fh;
 8438:     open($fh,"<$file");
 8439:     my $a='';
 8440:     while (my $line = <$fh>) { $a .= $line; }
 8441:     return $a;
 8442: }
 8443: 
 8444: sub filelocation {
 8445:     my ($dir,$file) = @_;
 8446:     my $location;
 8447:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8448: 
 8449:     if ($file =~ m-^/adm/-) {
 8450: 	$file=~s-^/adm/wrapper/-/-;
 8451: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8452:     }
 8453: 
 8454:     if ($file=~m:^/~:) { # is a contruction space reference
 8455:         $location = $file;
 8456:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8457:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8458: 	# is a correct contruction space reference
 8459:         $location = $file;
 8460:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8461:         $location = $file;
 8462:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8463:         my ($udom,$uname,$filename)=
 8464:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8465:         my $home=&homeserver($uname,$udom);
 8466:         my $is_me=0;
 8467:         my @ids=&current_machine_ids();
 8468:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8469:         if ($is_me) {
 8470:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8471:         } else {
 8472:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8473:   	      $udom.'/'.$uname.'/'.$filename;
 8474:         }
 8475:     } elsif ($file =~ m-^/adm/-) {
 8476: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8477:     } else {
 8478:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8479:         $file=~s:^/res/:/:;
 8480:         if ( !( $file =~ m:^/:) ) {
 8481:             $location = $dir. '/'.$file;
 8482:         } else {
 8483:             $location = '/home/httpd/html/res'.$file;
 8484:         }
 8485:     }
 8486:     $location=~s://+:/:g; # remove duplicate /
 8487:     while ($location=~m{/\.\./}) {
 8488: 	if ($location =~ m{/[^/]+/\.\./}) {
 8489: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8490: 	} else {
 8491: 	    $location=~ s{/\.\./}{/}g;
 8492: 	}
 8493:     } #remove dir/..
 8494:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8495:     return $location;
 8496: }
 8497: 
 8498: sub hreflocation {
 8499:     my ($dir,$file)=@_;
 8500:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8501: 	$file=filelocation($dir,$file);
 8502:     } elsif ($file=~m-^/adm/-) {
 8503: 	$file=~s-^/adm/wrapper/-/-;
 8504: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8505:     }
 8506:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8507: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8508:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8509: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8510:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8511: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8512: 	    -/uploaded/$1/$2/-x;
 8513:     }
 8514:     if ($file=~ m{^/userfiles/}) {
 8515: 	$file =~ s{^/userfiles/}{/uploaded/};
 8516:     }
 8517:     return $file;
 8518: }
 8519: 
 8520: sub current_machine_domains {
 8521:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8522: }
 8523: 
 8524: sub machine_domains {
 8525:     my ($hostname) = @_;
 8526:     my @domains;
 8527:     my %hostname = &all_hostnames();
 8528:     while( my($id, $name) = each(%hostname)) {
 8529: #	&logthis("-$id-$name-$hostname-");
 8530: 	if ($hostname eq $name) {
 8531: 	    push(@domains,&host_domain($id));
 8532: 	}
 8533:     }
 8534:     return @domains;
 8535: }
 8536: 
 8537: sub current_machine_ids {
 8538:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8539: }
 8540: 
 8541: sub machine_ids {
 8542:     my ($hostname) = @_;
 8543:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8544:     my @ids;
 8545:     my %name_to_host = &all_names();
 8546:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8547: 	return @{ $name_to_host{$hostname} };
 8548:     }
 8549:     return;
 8550: }
 8551: 
 8552: sub additional_machine_domains {
 8553:     my @domains;
 8554:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8555:     while( my $line = <$fh>) {
 8556:         $line =~ s/\s//g;
 8557:         push(@domains,$line);
 8558:     }
 8559:     return @domains;
 8560: }
 8561: 
 8562: sub default_login_domain {
 8563:     my $domain = $perlvar{'lonDefDomain'};
 8564:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8565:     foreach my $posdom (&current_machine_domains(),
 8566:                         &additional_machine_domains()) {
 8567:         if (lc($posdom) eq lc($testdomain)) {
 8568:             $domain=$posdom;
 8569:             last;
 8570:         }
 8571:     }
 8572:     return $domain;
 8573: }
 8574: 
 8575: # ------------------------------------------------------------- Declutters URLs
 8576: 
 8577: sub declutter {
 8578:     my $thisfn=shift;
 8579:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8580:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8581:     $thisfn=~s/^\///;
 8582:     $thisfn=~s|^adm/wrapper/||;
 8583:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8584:     $thisfn=~s/^res\///;
 8585:     $thisfn=~s/\?.+$//;
 8586:     return $thisfn;
 8587: }
 8588: 
 8589: # ------------------------------------------------------------- Clutter up URLs
 8590: 
 8591: sub clutter {
 8592:     my $thisfn='/'.&declutter(shift);
 8593:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8594: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8595:        $thisfn='/res'.$thisfn; 
 8596:     }
 8597:     if ($thisfn !~m|/adm|) {
 8598: 	if ($thisfn =~ m|/ext/|) {
 8599: 	    $thisfn='/adm/wrapper'.$thisfn;
 8600: 	} else {
 8601: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8602: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8603: 	    if ($embstyle eq 'ssi'
 8604: 		|| ($embstyle eq 'hdn')
 8605: 		|| ($embstyle eq 'rat')
 8606: 		|| ($embstyle eq 'prv')
 8607: 		|| ($embstyle eq 'ign')) {
 8608: 		#do nothing with these
 8609: 	    } elsif (($embstyle eq 'img') 
 8610: 		|| ($embstyle eq 'emb')
 8611: 		|| ($embstyle eq 'wrp')) {
 8612: 		$thisfn='/adm/wrapper'.$thisfn;
 8613: 	    } elsif ($embstyle eq 'unk'
 8614: 		     && $thisfn!~/\.(sequence|page)$/) {
 8615: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8616: 	    } else {
 8617: #		&logthis("Got a blank emb style");
 8618: 	    }
 8619: 	}
 8620:     }
 8621:     return $thisfn;
 8622: }
 8623: 
 8624: sub clutter_with_no_wrapper {
 8625:     my $uri = &clutter(shift);
 8626:     if ($uri =~ m-^/adm/-) {
 8627: 	$uri =~ s-^/adm/wrapper/-/-;
 8628: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8629:     }
 8630:     return $uri;
 8631: }
 8632: 
 8633: sub freeze_escape {
 8634:     my ($value)=@_;
 8635:     if (ref($value)) {
 8636: 	$value=&nfreeze($value);
 8637: 	return '__FROZEN__'.&escape($value);
 8638:     }
 8639:     return &escape($value);
 8640: }
 8641: 
 8642: 
 8643: sub thaw_unescape {
 8644:     my ($value)=@_;
 8645:     if ($value =~ /^__FROZEN__/) {
 8646: 	substr($value,0,10,undef);
 8647: 	$value=&unescape($value);
 8648: 	return &thaw($value);
 8649:     }
 8650:     return &unescape($value);
 8651: }
 8652: 
 8653: sub correct_line_ends {
 8654:     my ($result)=@_;
 8655:     $$result =~s/\r\n/\n/mg;
 8656:     $$result =~s/\r/\n/mg;
 8657: }
 8658: # ================================================================ Main Program
 8659: 
 8660: sub goodbye {
 8661:    &logthis("Starting Shut down");
 8662: #not converted to using infrastruture and probably shouldn't be
 8663:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8664: #converted
 8665: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8666:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8667: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8668: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8669: #1.1 only
 8670: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8671: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8672: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8673: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8674:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8675:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8676:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8677:    &flushcourselogs();
 8678:    &logthis("Shutting down");
 8679: }
 8680: 
 8681: sub get_dns {
 8682:     my ($url,$func,$ignore_cache) = @_;
 8683:     if (!$ignore_cache) {
 8684: 	my ($content,$cached)=
 8685: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8686: 	if ($cached) {
 8687: 	    &$func($content);
 8688: 	    return;
 8689: 	}
 8690:     }
 8691: 
 8692:     my %alldns;
 8693:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8694:     foreach my $dns (<$config>) {
 8695: 	next if ($dns !~ /^\^(\S*)/x);
 8696:         my $line = $1;
 8697:         my ($host,$protocol) = split(/:/,$line);
 8698:         if ($protocol ne 'https') {
 8699:             $protocol = 'http';
 8700:         }
 8701: 	$alldns{$host} = $protocol;
 8702:     }
 8703:     while (%alldns) {
 8704: 	my ($dns) = keys(%alldns);
 8705: 	my $ua=new LWP::UserAgent;
 8706: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8707: 	my $response=$ua->request($request);
 8708:         delete($alldns{$dns});
 8709: 	next if ($response->is_error());
 8710: 	my @content = split("\n",$response->content);
 8711: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8712: 	&$func(\@content);
 8713: 	return;
 8714:     }
 8715:     close($config);
 8716:     my $which = (split('/',$url))[3];
 8717:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8718:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8719:     my @content = <$config>;
 8720:     &$func(\@content);
 8721:     return;
 8722: }
 8723: # ------------------------------------------------------------ Read domain file
 8724: {
 8725:     my $loaded;
 8726:     my %domain;
 8727: 
 8728:     sub parse_domain_tab {
 8729: 	my ($lines) = @_;
 8730: 	foreach my $line (@$lines) {
 8731: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8732: 
 8733: 	    chomp($line);
 8734: 	    my ($name,@elements) = split(/:/,$line,9);
 8735: 	    my %this_domain;
 8736: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8737: 			       'lang_def', 'city', 'longi', 'lati',
 8738: 			       'primary') {
 8739: 		$this_domain{$field} = shift(@elements);
 8740: 	    }
 8741: 	    $domain{$name} = \%this_domain;
 8742: 	}
 8743:     }
 8744: 
 8745:     sub reset_domain_info {
 8746: 	undef($loaded);
 8747: 	undef(%domain);
 8748:     }
 8749: 
 8750:     sub load_domain_tab {
 8751: 	my ($ignore_cache) = @_;
 8752: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8753: 	my $fh;
 8754: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8755: 	    my @lines = <$fh>;
 8756: 	    &parse_domain_tab(\@lines);
 8757: 	}
 8758: 	close($fh);
 8759: 	$loaded = 1;
 8760:     }
 8761: 
 8762:     sub domain {
 8763: 	&load_domain_tab() if (!$loaded);
 8764: 
 8765: 	my ($name,$what) = @_;
 8766: 	return if ( !exists($domain{$name}) );
 8767: 
 8768: 	if (!$what) {
 8769: 	    return $domain{$name}{'description'};
 8770: 	}
 8771: 	return $domain{$name}{$what};
 8772:     }
 8773: 
 8774:     sub domain_info {
 8775:         &load_domain_tab() if (!$loaded);
 8776:         return %domain;
 8777:     }
 8778: 
 8779: }
 8780: 
 8781: 
 8782: # ------------------------------------------------------------- Read hosts file
 8783: {
 8784:     my %hostname;
 8785:     my %hostdom;
 8786:     my %libserv;
 8787:     my $loaded;
 8788:     my %name_to_host;
 8789: 
 8790:     sub parse_hosts_tab {
 8791: 	my ($file) = @_;
 8792: 	foreach my $configline (@$file) {
 8793: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8794: 	    next if ($configline =~ /^\^/);
 8795: 	    chomp($configline);
 8796: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8797: 	    $name=~s/\s//g;
 8798: 	    if ($id && $domain && $role && $name) {
 8799: 		$hostname{$id}=$name;
 8800: 		push(@{$name_to_host{$name}}, $id);
 8801: 		$hostdom{$id}=$domain;
 8802: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8803:                 if (defined($protocol)) {
 8804:                     if ($protocol eq 'https') {
 8805:                         $protocol{$id} = $protocol;
 8806:                     } else {
 8807:                         $protocol{$id} = 'http'; 
 8808:                     }
 8809:                 } else {
 8810:                     $protocol{$id} = 'http';
 8811:                 }
 8812: 	    }
 8813: 	}
 8814:     }
 8815:     
 8816:     sub reset_hosts_info {
 8817: 	&purge_remembered();
 8818: 	&reset_domain_info();
 8819: 	&reset_hosts_ip_info();
 8820: 	undef(%name_to_host);
 8821: 	undef(%hostname);
 8822: 	undef(%hostdom);
 8823: 	undef(%libserv);
 8824: 	undef($loaded);
 8825:     }
 8826: 
 8827:     sub load_hosts_tab {
 8828: 	my ($ignore_cache) = @_;
 8829: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8830: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8831: 	my @config = <$config>;
 8832: 	&parse_hosts_tab(\@config);
 8833: 	close($config);
 8834: 	$loaded=1;
 8835:     }
 8836: 
 8837:     sub hostname {
 8838: 	&load_hosts_tab() if (!$loaded);
 8839: 
 8840: 	my ($lonid) = @_;
 8841: 	return $hostname{$lonid};
 8842:     }
 8843: 
 8844:     sub all_hostnames {
 8845: 	&load_hosts_tab() if (!$loaded);
 8846: 
 8847: 	return %hostname;
 8848:     }
 8849: 
 8850:     sub all_names {
 8851: 	&load_hosts_tab() if (!$loaded);
 8852: 
 8853: 	return %name_to_host;
 8854:     }
 8855: 
 8856:     sub all_host_domain {
 8857:         &load_hosts_tab() if (!$loaded);
 8858:         return %hostdom;
 8859:     }
 8860: 
 8861:     sub is_library {
 8862: 	&load_hosts_tab() if (!$loaded);
 8863: 
 8864: 	return exists($libserv{$_[0]});
 8865:     }
 8866: 
 8867:     sub all_library {
 8868: 	&load_hosts_tab() if (!$loaded);
 8869: 
 8870: 	return %libserv;
 8871:     }
 8872: 
 8873:     sub get_servers {
 8874: 	&load_hosts_tab() if (!$loaded);
 8875: 
 8876: 	my ($domain,$type) = @_;
 8877: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8878: 	                                          : %hostname;
 8879: 	my %result;
 8880: 	if (ref($domain) eq 'ARRAY') {
 8881: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8882: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8883: 		    $result{$host} = $hostname;
 8884: 		}
 8885: 	    }
 8886: 	} else {
 8887: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8888: 		if ($hostdom{$host} eq $domain) {
 8889: 		    $result{$host} = $hostname;
 8890: 		}
 8891: 	    }
 8892: 	}
 8893: 	return %result;
 8894:     }
 8895: 
 8896:     sub host_domain {
 8897: 	&load_hosts_tab() if (!$loaded);
 8898: 
 8899: 	my ($lonid) = @_;
 8900: 	return $hostdom{$lonid};
 8901:     }
 8902: 
 8903:     sub all_domains {
 8904: 	&load_hosts_tab() if (!$loaded);
 8905: 
 8906: 	my %seen;
 8907: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8908: 	return @uniq;
 8909:     }
 8910: }
 8911: 
 8912: { 
 8913:     my %iphost;
 8914:     my %name_to_ip;
 8915:     my %lonid_to_ip;
 8916: 
 8917:     sub get_hosts_from_ip {
 8918: 	my ($ip) = @_;
 8919: 	my %iphosts = &get_iphost();
 8920: 	if (ref($iphosts{$ip})) {
 8921: 	    return @{$iphosts{$ip}};
 8922: 	}
 8923: 	return;
 8924:     }
 8925:     
 8926:     sub reset_hosts_ip_info {
 8927: 	undef(%iphost);
 8928: 	undef(%name_to_ip);
 8929: 	undef(%lonid_to_ip);
 8930:     }
 8931: 
 8932:     sub get_host_ip {
 8933: 	my ($lonid) = @_;
 8934: 	if (exists($lonid_to_ip{$lonid})) {
 8935: 	    return $lonid_to_ip{$lonid};
 8936: 	}
 8937: 	my $name=&hostname($lonid);
 8938:    	my $ip = gethostbyname($name);
 8939: 	return if (!$ip || length($ip) ne 4);
 8940: 	$ip=inet_ntoa($ip);
 8941: 	$name_to_ip{$name}   = $ip;
 8942: 	$lonid_to_ip{$lonid} = $ip;
 8943: 	return $ip;
 8944:     }
 8945:     
 8946:     sub get_iphost {
 8947: 	my ($ignore_cache) = @_;
 8948: 
 8949: 	if (!$ignore_cache) {
 8950: 	    if (%iphost) {
 8951: 		return %iphost;
 8952: 	    }
 8953: 	    my ($ip_info,$cached)=
 8954: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8955: 	    if ($cached) {
 8956: 		%iphost      = %{$ip_info->[0]};
 8957: 		%name_to_ip  = %{$ip_info->[1]};
 8958: 		%lonid_to_ip = %{$ip_info->[2]};
 8959: 		return %iphost;
 8960: 	    }
 8961: 	}
 8962: 
 8963: 	# get yesterday's info for fallback
 8964: 	my %old_name_to_ip;
 8965: 	my ($ip_info,$cached)=
 8966: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8967: 	if ($cached) {
 8968: 	    %old_name_to_ip = %{$ip_info->[1]};
 8969: 	}
 8970: 
 8971: 	my %name_to_host = &all_names();
 8972: 	foreach my $name (keys(%name_to_host)) {
 8973: 	    my $ip;
 8974: 	    if (!exists($name_to_ip{$name})) {
 8975: 		$ip = gethostbyname($name);
 8976: 		if (!$ip || length($ip) ne 4) {
 8977: 		    if (defined($old_name_to_ip{$name})) {
 8978: 			$ip = $old_name_to_ip{$name};
 8979: 			&logthis("Can't find $name defaulting to old $ip");
 8980: 		    } else {
 8981: 			&logthis("Name $name no IP found");
 8982: 			next;
 8983: 		    }
 8984: 		} else {
 8985: 		    $ip=inet_ntoa($ip);
 8986: 		}
 8987: 		$name_to_ip{$name} = $ip;
 8988: 	    } else {
 8989: 		$ip = $name_to_ip{$name};
 8990: 	    }
 8991: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8992: 		$lonid_to_ip{$id} = $ip;
 8993: 	    }
 8994: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8995: 	}
 8996: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8997: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8998: 				      48*60*60);
 8999: 
 9000: 	return %iphost;
 9001:     }
 9002: }
 9003: 
 9004: BEGIN {
 9005: 
 9006: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9007:     unless ($readit) {
 9008: {
 9009:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9010:     %perlvar = (%perlvar,%{$configvars});
 9011: }
 9012: 
 9013: 
 9014: # ------------------------------------------------------ Read spare server file
 9015: {
 9016:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9017: 
 9018:     while (my $configline=<$config>) {
 9019:        chomp($configline);
 9020:        if ($configline) {
 9021: 	   my ($host,$type) = split(':',$configline,2);
 9022: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9023: 	   push(@{ $spareid{$type} }, $host);
 9024:        }
 9025:     }
 9026:     close($config);
 9027: }
 9028: # ------------------------------------------------------------ Read permissions
 9029: {
 9030:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9031: 
 9032:     while (my $configline=<$config>) {
 9033: 	chomp($configline);
 9034: 	if ($configline) {
 9035: 	    my ($role,$perm)=split(/ /,$configline);
 9036: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9037: 	}
 9038:     }
 9039:     close($config);
 9040: }
 9041: 
 9042: # -------------------------------------------- Read plain texts for permissions
 9043: {
 9044:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9045: 
 9046:     while (my $configline=<$config>) {
 9047: 	chomp($configline);
 9048: 	if ($configline) {
 9049: 	    my ($short,@plain)=split(/:/,$configline);
 9050:             %{$prp{$short}} = ();
 9051: 	    if (@plain > 0) {
 9052:                 $prp{$short}{'std'} = $plain[0];
 9053:                 for (my $i=1; $i<@plain; $i++) {
 9054:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9055:                 }
 9056:             }
 9057: 	}
 9058:     }
 9059:     close($config);
 9060: }
 9061: 
 9062: # ---------------------------------------------------------- Read package table
 9063: {
 9064:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9065: 
 9066:     while (my $configline=<$config>) {
 9067: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9068: 	chomp($configline);
 9069: 	my ($short,$plain)=split(/:/,$configline);
 9070: 	my ($pack,$name)=split(/\&/,$short);
 9071: 	if ($plain ne '') {
 9072: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9073: 	    $packagetab{$short}=$plain; 
 9074: 	}
 9075:     }
 9076:     close($config);
 9077: }
 9078: 
 9079: # ------------- set up temporary directory
 9080: {
 9081:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9082: 
 9083: }
 9084: 
 9085: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9086: 				'compress_threshold'=> 20_000,
 9087:  			        });
 9088: 
 9089: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9090: $dumpcount=0;
 9091: $locknum=0;
 9092: 
 9093: &logtouch();
 9094: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9095: $readit=1;
 9096:     {
 9097: 	use integer;
 9098: 	my $test=(2**32)+1;
 9099: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9100: 	&logthis(" Detected 64bit platform ($_64bit)");
 9101:     }
 9102: }
 9103: }
 9104: 
 9105: 1;
 9106: __END__
 9107: 
 9108: =pod
 9109: 
 9110: =head1 NAME
 9111: 
 9112: Apache::lonnet - Subroutines to ask questions about things in the network.
 9113: 
 9114: =head1 SYNOPSIS
 9115: 
 9116: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9117: 
 9118:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9119: 
 9120: Common parameters:
 9121: 
 9122: =over 4
 9123: 
 9124: =item *
 9125: 
 9126: $uname : an internal username (if $cname expecting a course Id specifically)
 9127: 
 9128: =item *
 9129: 
 9130: $udom : a domain (if $cdom expecting a course's domain specifically)
 9131: 
 9132: =item *
 9133: 
 9134: $symb : a resource instance identifier
 9135: 
 9136: =item *
 9137: 
 9138: $namespace : the name of a .db file that contains the data needed or
 9139: being set.
 9140: 
 9141: =back
 9142: 
 9143: =head1 OVERVIEW
 9144: 
 9145: lonnet provides subroutines which interact with the
 9146: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9147: about classes, users, and resources.
 9148: 
 9149: For many of these objects you can also use this to store data about
 9150: them or modify them in various ways.
 9151: 
 9152: =head2 Symbs
 9153: 
 9154: To identify a specific instance of a resource, LON-CAPA uses symbols
 9155: or "symbs"X<symb>. These identifiers are built from the URL of the
 9156: map, the resource number of the resource in the map, and the URL of
 9157: the resource itself. The latter is somewhat redundant, but might help
 9158: if maps change.
 9159: 
 9160: An example is
 9161: 
 9162:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9163: 
 9164: The respective map entry is
 9165: 
 9166:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9167:   title="Problem 2">
 9168:  </resource>
 9169: 
 9170: Symbs are used by the random number generator, as well as to store and
 9171: restore data specific to a certain instance of for example a problem.
 9172: 
 9173: =head2 Storing And Retrieving Data
 9174: 
 9175: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9176: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9177: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9178: is is the non-critical message twin of cstore. These functions are for
 9179: handlers to store a perl hash to a user's permanent data space in an
 9180: easy manner, and to retrieve it again on another call. It is expected
 9181: that a handler would use this once at the beginning to retrieve data,
 9182: and then again once at the end to send only the new data back.
 9183: 
 9184: The data is stored in the user's data directory on the user's
 9185: homeserver under the ID of the course.
 9186: 
 9187: The hash that is returned by restore will have all of the previous
 9188: value for all of the elements of the hash.
 9189: 
 9190: Example:
 9191: 
 9192:  #creating a hash
 9193:  my %hash;
 9194:  $hash{'foo'}='bar';
 9195: 
 9196:  #storing it
 9197:  &Apache::lonnet::cstore(\%hash);
 9198: 
 9199:  #changing a value
 9200:  $hash{'foo'}='notbar';
 9201: 
 9202:  #adding a new value
 9203:  $hash{'bar'}='foo';
 9204:  &Apache::lonnet::cstore(\%hash);
 9205: 
 9206:  #retrieving the hash
 9207:  my %history=&Apache::lonnet::restore();
 9208: 
 9209:  #print the hash
 9210:  foreach my $key (sort(keys(%history))) {
 9211:    print("\%history{$key} = $history{$key}");
 9212:  }
 9213: 
 9214: Will print out:
 9215: 
 9216:  %history{1:foo} = bar
 9217:  %history{1:keys} = foo:timestamp
 9218:  %history{1:timestamp} = 990455579
 9219:  %history{2:bar} = foo
 9220:  %history{2:foo} = notbar
 9221:  %history{2:keys} = foo:bar:timestamp
 9222:  %history{2:timestamp} = 990455580
 9223:  %history{bar} = foo
 9224:  %history{foo} = notbar
 9225:  %history{timestamp} = 990455580
 9226:  %history{version} = 2
 9227: 
 9228: Note that the special hash entries C<keys>, C<version> and
 9229: C<timestamp> were added to the hash. C<version> will be equal to the
 9230: total number of versions of the data that have been stored. The
 9231: C<timestamp> attribute will be the UNIX time the hash was
 9232: stored. C<keys> is available in every historical section to list which
 9233: keys were added or changed at a specific historical revision of a
 9234: hash.
 9235: 
 9236: B<Warning>: do not store the hash that restore returns directly. This
 9237: will cause a mess since it will restore the historical keys as if the
 9238: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9239: 
 9240: Calling convention:
 9241: 
 9242:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9243:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9244: 
 9245: For more detailed information, see lonnet specific documentation.
 9246: 
 9247: =head1 RETURN MESSAGES
 9248: 
 9249: =over 4
 9250: 
 9251: =item * B<con_lost>: unable to contact remote host
 9252: 
 9253: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9254: when the connection is brought back up
 9255: 
 9256: =item * B<con_failed>: unable to contact remote host and unable to save message
 9257: for later delivery
 9258: 
 9259: =item * B<error:>: an error a occurred, a description of the error follows the :
 9260: 
 9261: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9262: that was requested
 9263: 
 9264: =back
 9265: 
 9266: =head1 PUBLIC SUBROUTINES
 9267: 
 9268: =head2 Session Environment Functions
 9269: 
 9270: =over 4
 9271: 
 9272: =item * 
 9273: X<appenv()>
 9274: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9275: the user envirnoment file, and will be restored for each access this
 9276: user makes during this session, also modifies the %env for the current
 9277: process. Optional rolesarrayref - if defined contains a reference to an array
 9278: of roles which are exempt from the restriction on modifying user.role entries 
 9279: in the user's environment.db and in %env.    
 9280: 
 9281: =item *
 9282: X<delenv()>
 9283: B<delenv($delthis,$regexp)>: removes all items from the session
 9284: environment file that begin with $delthis. If the
 9285: optional second arg - $regexp - is true, $delthis is treated as a
 9286: regular expression, otherwise \Q$delthis\E is used.
 9287: The values are also deleted from the current processes %env.
 9288: 
 9289: =item * get_env_multiple($name) 
 9290: 
 9291: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9292: values may be defined and end up as an array ref.
 9293: 
 9294: returns an array of values
 9295: 
 9296: =back
 9297: 
 9298: =head2 User Information
 9299: 
 9300: =over 4
 9301: 
 9302: =item *
 9303: X<queryauthenticate()>
 9304: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9305: authentication scheme
 9306: 
 9307: =item *
 9308: X<authenticate()>
 9309: B<authenticate($uname,$upass,$udom)>: try to
 9310: authenticate user from domain's lib servers (first use the current
 9311: one). C<$upass> should be the users password.
 9312: 
 9313: =item *
 9314: X<homeserver()>
 9315: B<homeserver($uname,$udom)>: find the server which has
 9316: the user's directory and files (there must be only one), this caches
 9317: the answer, and also caches if there is a borken connection.
 9318: 
 9319: =item *
 9320: X<idget()>
 9321: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9322: (IDs are a unique resource in a domain, there must be only 1 ID per
 9323: username, and only 1 username per ID in a specific domain) (returns
 9324: hash: id=>name,id=>name)
 9325: 
 9326: =item *
 9327: X<idrget()>
 9328: B<idrget($udom,@unames)>: find the IDs behind a list of
 9329: usernames (returns hash: name=>id,name=>id)
 9330: 
 9331: =item *
 9332: X<idput()>
 9333: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9334: 
 9335: =item *
 9336: X<rolesinit()>
 9337: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9338: 
 9339: =item *
 9340: X<getsection()>
 9341: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9342: course $cname, return section name/number or '' for "not in course"
 9343: and '-1' for "no section"
 9344: 
 9345: =item *
 9346: X<userenvironment()>
 9347: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9348: passed in @what from the requested user's environment, returns a hash
 9349: 
 9350: =item * 
 9351: X<userlog_query()>
 9352: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9353: activity.log file. %filters defines filters applied when parsing the
 9354: log file. These can be start or end timestamps, or the type of action
 9355: - log to look for Login or Logout events, check for Checkin or
 9356: Checkout, role for role selection. The response is in the form
 9357: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9358: escaped strings of the action recorded in the activity.log file.
 9359: 
 9360: =back
 9361: 
 9362: =head2 User Roles
 9363: 
 9364: =over 4
 9365: 
 9366: =item *
 9367: 
 9368: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9369:  F: full access
 9370:  U,I,K: authentication modes (cxx only)
 9371:  '': forbidden
 9372:  1: user needs to choose course
 9373:  2: browse allowed
 9374:  A: passphrase authentication needed
 9375: 
 9376: =item *
 9377: 
 9378: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9379: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9380: and course level
 9381: 
 9382: =item *
 9383: 
 9384: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9385: explanation of a user role term
 9386: 
 9387: =item *
 9388: 
 9389: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9390: All arguments are optional. Returns a hash of a roles, either for
 9391: co-author/assistant author roles for a user's Construction Space
 9392: (default), or if $context is 'userroles', roles for the user himself,
 9393: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9394: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9395: For each key, value is set to colon-separated start and end times for
 9396: the role.  If no username and domain are specified, will default to
 9397: current user/domain. Types, roles, and roledoms are references to arrays
 9398: of role statuses (active, future or previous), roles 
 9399: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9400: to restrict the list of roles reported. If no array ref is 
 9401: provided for types, will default to return only active roles.
 9402: 
 9403: =back
 9404: 
 9405: =head2 User Modification
 9406: 
 9407: =over 4
 9408: 
 9409: =item *
 9410: 
 9411: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9412: user for the level given by URL.  Optional start and end dates (leave empty
 9413: string or zero for "no date")
 9414: 
 9415: =item *
 9416: 
 9417: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9418: change a users, password, possible return values are: ok,
 9419: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9420: refused
 9421: 
 9422: =item *
 9423: 
 9424: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9425: 
 9426: =item *
 9427: 
 9428: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9429:            $forceid,$desiredhome,$email,$inststatus) : 
 9430: modify user
 9431: 
 9432: =item *
 9433: 
 9434: modifystudent
 9435: 
 9436: modify a student's enrollment and identification information.
 9437: The course id is resolved based on the current users environment.  
 9438: This means the envoking user must be a course coordinator or otherwise
 9439: associated with a course.
 9440: 
 9441: This call is essentially a wrapper for lonnet::modifyuser and
 9442: lonnet::modify_student_enrollment
 9443: 
 9444: Inputs: 
 9445: 
 9446: =over 4
 9447: 
 9448: =item B<$udom> Student's loncapa domain
 9449: 
 9450: =item B<$uname> Student's loncapa login name
 9451: 
 9452: =item B<$uid> Student/Employee ID
 9453: 
 9454: =item B<$umode> Student's authentication mode
 9455: 
 9456: =item B<$upass> Student's password
 9457: 
 9458: =item B<$first> Student's first name
 9459: 
 9460: =item B<$middle> Student's middle name
 9461: 
 9462: =item B<$last> Student's last name
 9463: 
 9464: =item B<$gene> Student's generation
 9465: 
 9466: =item B<$usec> Student's section in course
 9467: 
 9468: =item B<$end> Unix time of the roles expiration
 9469: 
 9470: =item B<$start> Unix time of the roles start date
 9471: 
 9472: =item B<$forceid> If defined, allow $uid to be changed
 9473: 
 9474: =item B<$desiredhome> server to use as home server for student
 9475: 
 9476: =item B<$email> Student's permanent e-mail address
 9477: 
 9478: =item B<$type> Type of enrollment (auto or manual)
 9479: 
 9480: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9481: 
 9482: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9483: 
 9484: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9485: 
 9486: =item B<$context> role change context (shown in User Management Logs display in a course)
 9487: 
 9488: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9489: 
 9490: =back
 9491: 
 9492: =item *
 9493: 
 9494: modify_student_enrollment
 9495: 
 9496: Change a students enrollment status in a class.  The environment variable
 9497: 'role.request.course' must be defined for this function to proceed.
 9498: 
 9499: Inputs:
 9500: 
 9501: =over 4
 9502: 
 9503: =item $udom, students domain
 9504: 
 9505: =item $uname, students name
 9506: 
 9507: =item $uid, students user id
 9508: 
 9509: =item $first, students first name
 9510: 
 9511: =item $middle
 9512: 
 9513: =item $last
 9514: 
 9515: =item $gene
 9516: 
 9517: =item $usec
 9518: 
 9519: =item $end
 9520: 
 9521: =item $start
 9522: 
 9523: =item $type
 9524: 
 9525: =item $locktype
 9526: 
 9527: =item $cid
 9528: 
 9529: =item $selfenroll
 9530: 
 9531: =item $context
 9532: 
 9533: =back
 9534: 
 9535: 
 9536: =item *
 9537: 
 9538: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9539: custom role; give a custom role to a user for the level given by URL.  Specify
 9540: name and domain of role author, and role name
 9541: 
 9542: =item *
 9543: 
 9544: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9545: 
 9546: =item *
 9547: 
 9548: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9549: 
 9550: =back
 9551: 
 9552: =head2 Course Infomation
 9553: 
 9554: =over 4
 9555: 
 9556: =item *
 9557: 
 9558: coursedescription($courseid) : returns a hash of information about the
 9559: specified course id, including all environment settings for the
 9560: course, the description of the course will be in the hash under the
 9561: key 'description'
 9562: 
 9563: =item *
 9564: 
 9565: resdata($name,$domain,$type,@which) : request for current parameter
 9566: setting for a specific $type, where $type is either 'course' or 'user',
 9567: @what should be a list of parameters to ask about. This routine caches
 9568: answers for 5 minutes.
 9569: 
 9570: =item *
 9571: 
 9572: get_courseresdata($courseid, $domain) : dump the entire course resource
 9573: data base, returning a hash that is keyed by the resource name and has
 9574: values that are the resource value.  I believe that the timestamps and
 9575: versions are also returned.
 9576: 
 9577: 
 9578: =back
 9579: 
 9580: =head2 Course Modification
 9581: 
 9582: =over 4
 9583: 
 9584: =item *
 9585: 
 9586: writecoursepref($courseid,%prefs) : write preferences (environment
 9587: database) for a course
 9588: 
 9589: =item *
 9590: 
 9591: createcourse($udom,$description,$url) : make/modify course
 9592: 
 9593: =back
 9594: 
 9595: =head2 Resource Subroutines
 9596: 
 9597: =over 4
 9598: 
 9599: =item *
 9600: 
 9601: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9602: 
 9603: =item *
 9604: 
 9605: repcopy($filename) : subscribes to the requested file, and attempts to
 9606: replicate from the owning library server, Might return
 9607: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9608: 'bad_request', also attempts to grab the metadata for the
 9609: resource. Expects the local filesystem pathname
 9610: (/home/httpd/html/res/....)
 9611: 
 9612: =back
 9613: 
 9614: =head2 Resource Information
 9615: 
 9616: =over 4
 9617: 
 9618: =item *
 9619: 
 9620: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9621: a vairety of different possible values, $varname should be a request
 9622: string, and the other parameters can be used to specify who and what
 9623: one is asking about.
 9624: 
 9625: Possible values for $varname are environment.lastname (or other item
 9626: from the envirnment hash), user.name (or someother aspect about the
 9627: user), resource.0.maxtries (or some other part and parameter of a
 9628: resource)
 9629: 
 9630: =item *
 9631: 
 9632: directcondval($number) : get current value of a condition; reads from a state
 9633: string
 9634: 
 9635: =item *
 9636: 
 9637: condval($condidx) : value of condition index based on state
 9638: 
 9639: =item *
 9640: 
 9641: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9642: resource's metadata, $what should be either a specific key, or either
 9643: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9644: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9645: 
 9646: this function automatically caches all requests
 9647: 
 9648: =item *
 9649: 
 9650: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9651: network of library servers; returns file handle of where SQL and regex results
 9652: will be stored for query
 9653: 
 9654: =item *
 9655: 
 9656: symbread($filename) : return symbolic list entry (filename argument optional);
 9657: returns the data handle
 9658: 
 9659: =item *
 9660: 
 9661: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9662: a possible symb for the URL in $thisfn, and if is an encryypted
 9663: resource that the user accessed using /enc/ returns a 1 on success, 0
 9664: on failure, user must be in a course, as it assumes the existance of
 9665: the course initial hash, and uses $env('request.course.id'}
 9666: 
 9667: 
 9668: =item *
 9669: 
 9670: symbclean($symb) : removes versions numbers from a symb, returns the
 9671: cleaned symb
 9672: 
 9673: =item *
 9674: 
 9675: is_on_map($uri) : checks if the $uri is somewhere on the current
 9676: course map, user must be in a course for it to work.
 9677: 
 9678: =item *
 9679: 
 9680: numval($salt) : return random seed value (addend for rndseed)
 9681: 
 9682: =item *
 9683: 
 9684: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9685: a random seed, all arguments are optional, if they aren't sent it uses the
 9686: environment to derive them. Note: if symb isn't sent and it can't get one
 9687: from &symbread it will use the current time as its return value
 9688: 
 9689: =item *
 9690: 
 9691: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9692: unfakeable, receipt
 9693: 
 9694: =item *
 9695: 
 9696: receipt() : API to ireceipt working off of env values; given out to users
 9697: 
 9698: =item *
 9699: 
 9700: countacc($url) : count the number of accesses to a given URL
 9701: 
 9702: =item *
 9703: 
 9704: 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
 9705: 
 9706: =item *
 9707: 
 9708: 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)
 9709: 
 9710: =item *
 9711: 
 9712: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9713: 
 9714: =item *
 9715: 
 9716: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9717: forcing spreadsheet to reevaluate the resource scores next time.
 9718: 
 9719: =back
 9720: 
 9721: =head2 Storing/Retreiving Data
 9722: 
 9723: =over 4
 9724: 
 9725: =item *
 9726: 
 9727: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9728: for this url; hashref needs to be given and should be a \%hashname; the
 9729: remaining args aren't required and if they aren't passed or are '' they will
 9730: be derived from the env
 9731: 
 9732: =item *
 9733: 
 9734: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9735: uses critical subroutine
 9736: 
 9737: =item *
 9738: 
 9739: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9740: all args are optional
 9741: 
 9742: =item *
 9743: 
 9744: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9745: dumps the complete (or key matching regexp) namespace into a hash
 9746: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9747: normally &store()ed into
 9748: 
 9749: $range should be either an integer '100' (give me the first 100
 9750:                                            matching records)
 9751:               or be  two integers sperated by a - with no spaces
 9752:                  '30-50' (give me the 30th through the 50th matching
 9753:                           records)
 9754: 
 9755: 
 9756: =item *
 9757: 
 9758: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9759: replaces a &store() version of data with a replacement set of data
 9760: for a particular resource in a namespace passed in the $storehash hash 
 9761: reference
 9762: 
 9763: =item *
 9764: 
 9765: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9766: works very similar to store/cstore, but all data is stored in a
 9767: temporary location and can be reset using tmpreset, $storehash should
 9768: be a hash reference, returns nothing on success
 9769: 
 9770: =item *
 9771: 
 9772: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9773: similar to restore, but all data is stored in a temporary location and
 9774: can be reset using tmpreset. Returns a hash of values on success,
 9775: error string otherwise.
 9776: 
 9777: =item *
 9778: 
 9779: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9780: deltes all keys for $symb form the temporary storage hash.
 9781: 
 9782: =item *
 9783: 
 9784: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9785: reference filled in from namesp ($udom and $uname are optional)
 9786: 
 9787: =item *
 9788: 
 9789: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9790: namesp ($udom and $uname are optional)
 9791: 
 9792: =item *
 9793: 
 9794: dump($namespace,$udom,$uname,$regexp,$range) : 
 9795: dumps the complete (or key matching regexp) namespace into a hash
 9796: ($udom, $uname, $regexp, $range are optional)
 9797: 
 9798: $range should be either an integer '100' (give me the first 100
 9799:                                            matching records)
 9800:               or be  two integers sperated by a - with no spaces
 9801:                  '30-50' (give me the 30th through the 50th matching
 9802:                           records)
 9803: =item *
 9804: 
 9805: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9806: $store can be a scalar, an array reference, or if the amount to be 
 9807: incremented is > 1, a hash reference.
 9808: 
 9809: ($udom and $uname are optional)
 9810: 
 9811: =item *
 9812: 
 9813: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9814: ($udom and $uname are optional)
 9815: 
 9816: =item *
 9817: 
 9818: cput($namespace,$storehash,$udom,$uname) : critical put
 9819: ($udom and $uname are optional)
 9820: 
 9821: =item *
 9822: 
 9823: newput($namespace,$storehash,$udom,$uname) :
 9824: 
 9825: Attempts to store the items in the $storehash, but only if they don't
 9826: currently exist, if this succeeds you can be certain that you have 
 9827: successfully created a new key value pair in the $namespace db.
 9828: 
 9829: 
 9830: Args:
 9831:  $namespace: name of database to store values to
 9832:  $storehash: hashref to store to the db
 9833:  $udom: (optional) domain of user containing the db
 9834:  $uname: (optional) name of user caontaining the db
 9835: 
 9836: Returns:
 9837:  'ok' -> succeeded in storing all keys of $storehash
 9838:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9839:                         least <key> already existed in the db (other
 9840:                         requested keys may also already exist)
 9841:  'error: <msg>' -> unable to tie the DB or other error occurred
 9842:  'con_lost' -> unable to contact request server
 9843:  'refused' -> action was not allowed by remote machine
 9844: 
 9845: 
 9846: =item *
 9847: 
 9848: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9849: reference filled in from namesp (encrypts the return communication)
 9850: ($udom and $uname are optional)
 9851: 
 9852: =item *
 9853: 
 9854: log($udom,$name,$home,$message) : write to permanent log for user; use
 9855: critical subroutine
 9856: 
 9857: =item *
 9858: 
 9859: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9860: array reference filled in from namespace found in domain level on either
 9861: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9862: 
 9863: =item *
 9864: 
 9865: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9866: domain level either on specified domain server ($uhome) or primary domain 
 9867: server ($udom and $uhome are optional)
 9868: 
 9869: =item * 
 9870: 
 9871: get_domain_defaults($target_domain) : returns hash with defaults for
 9872: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9873: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9874: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9875: Values are retrieved from cache (if current), or from domain's configuration.db
 9876: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9877: or lonTabs/domain.tab. 
 9878: 
 9879: %domdefaults = &get_auth_defaults($target_domain);
 9880: 
 9881: =back
 9882: 
 9883: =head2 Network Status Functions
 9884: 
 9885: =over 4
 9886: 
 9887: =item *
 9888: 
 9889: dirlist($uri) : return directory list based on URI
 9890: 
 9891: =item *
 9892: 
 9893: spareserver() : find server with least workload from spare.tab
 9894: 
 9895: =back
 9896: 
 9897: =head2 Apache Request
 9898: 
 9899: =over 4
 9900: 
 9901: =item *
 9902: 
 9903: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9904: localhost, posts hash
 9905: 
 9906: =back
 9907: 
 9908: =head2 Data to String to Data
 9909: 
 9910: =over 4
 9911: 
 9912: =item *
 9913: 
 9914: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9915: and '&' separators, supports elements that are arrayrefs and hashrefs
 9916: 
 9917: =item *
 9918: 
 9919: hashref2str($hashref) : convert a hashref into a string complete with
 9920: escaping and '=' and '&' separators, supports elements that are
 9921: arrayrefs and hashrefs
 9922: 
 9923: =item *
 9924: 
 9925: arrayref2str($arrayref) : convert an arrayref into a string complete
 9926: with escaping and '&' separators, supports elements that are arrayrefs
 9927: and hashrefs
 9928: 
 9929: =item *
 9930: 
 9931: str2hash($string) : convert string to hash using unescaping and
 9932: splitting on '=' and '&', supports elements that are arrayrefs and
 9933: hashrefs
 9934: 
 9935: =item *
 9936: 
 9937: str2array($string) : convert string to hash using unescaping and
 9938: splitting on '&', supports elements that are arrayrefs and hashrefs
 9939: 
 9940: =back
 9941: 
 9942: =head2 Logging Routines
 9943: 
 9944: =over 4
 9945: 
 9946: These routines allow one to make log messages in the lonnet.log and
 9947: lonnet.perm logfiles.
 9948: 
 9949: =item *
 9950: 
 9951: logtouch() : make sure the logfile, lonnet.log, exists
 9952: 
 9953: =item *
 9954: 
 9955: logthis() : append message to the normal lonnet.log file, it gets
 9956: preiodically rolled over and deleted.
 9957: 
 9958: =item *
 9959: 
 9960: logperm() : append a permanent message to lonnet.perm.log, this log
 9961: file never gets deleted by any automated portion of the system, only
 9962: messages of critical importance should go in here.
 9963: 
 9964: =back
 9965: 
 9966: =head2 General File Helper Routines
 9967: 
 9968: =over 4
 9969: 
 9970: =item *
 9971: 
 9972: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9973: (a) files in /uploaded
 9974:   (i) If a local copy of the file exists - 
 9975:       compares modification date of local copy with last-modified date for 
 9976:       definitive version stored on home server for course. If local copy is 
 9977:       stale, requests a new version from the home server and stores it. 
 9978:       If the original has been removed from the home server, then local copy 
 9979:       is unlinked.
 9980:   (ii) If local copy does not exist -
 9981:       requests the file from the home server and stores it. 
 9982:   
 9983:   If $caller is 'uploadrep':  
 9984:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9985:     for request for files originally uploaded via DOCS. 
 9986:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9987:   
 9988:   Otherwise:
 9989:      This indicates a call from the content generation phase of the request.
 9990:      -  returns the entire contents of the file or -1.
 9991:      
 9992: (b) files in /res
 9993:    - returns the entire contents of a file or -1; 
 9994:    it properly subscribes to and replicates the file if neccessary.
 9995: 
 9996: 
 9997: =item *
 9998: 
 9999: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10000:                   reference
10001: 
10002: returns either a stat() list of data about the file or an empty list
10003: if the file doesn't exist or couldn't find out about it (connection
10004: problems or user unknown)
10005: 
10006: =item *
10007: 
10008: filelocation($dir,$file) : returns file system location of a file
10009: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10010: directory that relative $file lookups are to looked in ($dir of /a/dir
10011: and a file of ../bob will become /a/bob)
10012: 
10013: =item *
10014: 
10015: hreflocation($dir,$file) : returns file system location or a URL; same as
10016: filelocation except for hrefs
10017: 
10018: =item *
10019: 
10020: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10021: 
10022: =back
10023: 
10024: =head2 Usererfile file routines (/uploaded*)
10025: 
10026: =over 4
10027: 
10028: =item *
10029: 
10030: userfileupload(): main rotine for putting a file in a user or course's
10031:                   filespace, arguments are,
10032: 
10033:  formname - required - this is the name of the element in $env where the
10034:            filename, and the contents of the file to create/modifed exist
10035:            the filename is in $env{'form.'.$formname.'.filename'} and the
10036:            contents of the file is located in $env{'form.'.$formname}
10037:  coursedoc - if true, store the file in the course of the active role
10038:              of the current user
10039:  subdir - required - subdirectory to put the file in under ../userfiles/
10040:          if undefined, it will be placed in "unknown"
10041: 
10042:  (This routine calls clean_filename() to remove any dangerous
10043:  characters from the filename, and then calls finuserfileupload() to
10044:  complete the transaction)
10045: 
10046:  returns either the url of the uploaded file (/uploaded/....) if successful
10047:  and /adm/notfound.html if unsuccessful
10048: 
10049: =item *
10050: 
10051: clean_filename(): routine for cleaing a filename up for storage in
10052:                  userfile space, argument is:
10053: 
10054:  filename - proposed filename
10055: 
10056: returns: the new clean filename
10057: 
10058: =item *
10059: 
10060: finishuserfileupload(): routine that creaes and sends the file to
10061: userspace, probably shouldn't be called directly
10062: 
10063:   docuname: username or courseid of destination for the file
10064:   docudom: domain of user/course of destination for the file
10065:   formname: same as for userfileupload()
10066:   fname: filename (inculding subdirectories) for the file
10067: 
10068:  returns either the url of the uploaded file (/uploaded/....) if successful
10069:  and /adm/notfound.html if unsuccessful
10070: 
10071: =item *
10072: 
10073: renameuserfile(): renames an existing userfile to a new name
10074: 
10075:   Args:
10076:    docuname: username or courseid of destination for the file
10077:    docudom: domain of user/course of destination for the file
10078:    old: current file name (including any subdirs under userfiles)
10079:    new: desired file name (including any subdirs under userfiles)
10080: 
10081: =item *
10082: 
10083: mkdiruserfile(): creates a directory is a userfiles dir
10084: 
10085:   Args:
10086:    docuname: username or courseid of destination for the file
10087:    docudom: domain of user/course of destination for the file
10088:    dir: dir to create (including any subdirs under userfiles)
10089: 
10090: =item *
10091: 
10092: removeuserfile(): removes a file that exists in userfiles
10093: 
10094:   Args:
10095:    docuname: username or courseid of destination for the file
10096:    docudom: domain of user/course of destination for the file
10097:    fname: filname to delete (including any subdirs under userfiles)
10098: 
10099: =item *
10100: 
10101: removeuploadedurl(): convience function for removeuserfile()
10102: 
10103:   Args:
10104:    url:  a full /uploaded/... url to delete
10105: 
10106: =item * 
10107: 
10108: get_portfile_permissions():
10109:   Args:
10110:     domain: domain of user or course contain the portfolio files
10111:     user: name of user or num of course contain the portfolio files
10112:   Returns:
10113:     hashref of a dump of the proper file_permissions.db
10114:    
10115: 
10116: =item * 
10117: 
10118: get_access_controls():
10119: 
10120: Args:
10121:   current_permissions: the hash ref returned from get_portfile_permissions()
10122:   group: (optional) the group you want the files associated with
10123:   file: (optional) the file you want access info on
10124: 
10125: Returns:
10126:     a hash (keys are file names) of hashes containing
10127:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10128:         values are XML containing access control settings (see below) 
10129: 
10130: Internal notes:
10131: 
10132:  access controls are stored in file_permissions.db as key=value pairs.
10133:     key -> path to file/file_name\0uniqueID:scope_end_start
10134:         where scope -> public,guest,course,group,domains or users.
10135:               end -> UNIX time for end of access (0 -> no end date)
10136:               start -> UNIX time for start of access
10137: 
10138:     value -> XML description of access control
10139:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10140:             <start></start>
10141:             <end></end>
10142: 
10143:             <password></password>  for scope type = guest
10144: 
10145:             <domain></domain>     for scope type = course or group
10146:             <number></number>
10147:             <roles id="">
10148:              <role></role>
10149:              <access></access>
10150:              <section></section>
10151:              <group></group>
10152:             </roles>
10153: 
10154:             <dom></dom>         for scope type = domains
10155: 
10156:             <users>             for scope type = users
10157:              <user>
10158:               <uname></uname>
10159:               <udom></udom>
10160:              </user>
10161:             </users>
10162:            </scope> 
10163:               
10164:  Access data is also aggregated for each file in an additional key=value pair:
10165:  key -> path to file/file_name\0accesscontrol 
10166:  value -> reference to hash
10167:           hash contains key = value pairs
10168:           where key = uniqueID:scope_end_start
10169:                 value = UNIX time record was last updated
10170: 
10171:           Used to improve speed of look-ups of access controls for each file.  
10172:  
10173:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10174: 
10175: modify_access_controls():
10176: 
10177: Modifies access controls for a portfolio file
10178: Args
10179: 1. file name
10180: 2. reference to hash of required changes,
10181: 3. domain
10182: 4. username
10183:   where domain,username are the domain of the portfolio owner 
10184:   (either a user or a course) 
10185: 
10186: Returns:
10187: 1. result of additions or updates ('ok' or 'error', with error message). 
10188: 2. result of deletions ('ok' or 'error', with error message).
10189: 3. reference to hash of any new or updated access controls.
10190: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10191:    key = integer (inbound ID)
10192:    value = uniqueID  
10193: 
10194: =back
10195: 
10196: =head2 HTTP Helper Routines
10197: 
10198: =over 4
10199: 
10200: =item *
10201: 
10202: escape() : unpack non-word characters into CGI-compatible hex codes
10203: 
10204: =item *
10205: 
10206: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10207: 
10208: =back
10209: 
10210: =head1 PRIVATE SUBROUTINES
10211: 
10212: =head2 Underlying communication routines (Shouldn't call)
10213: 
10214: =over 4
10215: 
10216: =item *
10217: 
10218: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10219: 
10220: =item *
10221: 
10222: reply() : uses subreply to send a message to remote machine, logs all failures
10223: 
10224: =item *
10225: 
10226: critical() : passes a critical message to another server; if cannot
10227: get through then place message in connection buffer directory and
10228: returns con_delayed, if incapable of saving message, returns
10229: con_failed
10230: 
10231: =item *
10232: 
10233: reconlonc() : tries to reconnect lonc client processes.
10234: 
10235: =back
10236: 
10237: =head2 Resource Access Logging
10238: 
10239: =over 4
10240: 
10241: =item *
10242: 
10243: flushcourselogs() : flush (save) buffer logs and access logs
10244: 
10245: =item *
10246: 
10247: courselog($what) : save message for course in hash
10248: 
10249: =item *
10250: 
10251: courseacclog($what) : save message for course using &courselog().  Perform
10252: special processing for specific resource types (problems, exams, quizzes, etc).
10253: 
10254: =item *
10255: 
10256: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10257: as a PerlChildExitHandler
10258: 
10259: =back
10260: 
10261: =head2 Other
10262: 
10263: =over 4
10264: 
10265: =item *
10266: 
10267: symblist($mapname,%newhash) : update symbolic storage links
10268: 
10269: =back
10270: 
10271: =cut
10272: 

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