File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.983: download - view: text, annotated - select for diffs
Fri Jan 2 23:07:49 2009 UTC (15 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- When course activity log data are stored in $cnum_$cdom_activity tables, timestamps are stored using lonmysql::sqltime() which employs the server localtime.
- Student Activity displayed with trackstudent needs to have these timestamps converted to the time zone set for the course.
   - &server_timezone_handler() in lond retrieves server time zone from /etc/sysconfig/clock or /etc/timezone depending on distro.
   - &get_server_timezone() in lonnet.pm gets server time zone from course's homeserver.
   - &gettimezone() in lonlocal.pm can now take a timezone as an argument.
       - will validate it, and return it if valid, 'local' otherwise
   - &convert_timezone() in lontrackstudent.pm converts timestamps prior to display, and includes course time zone.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.983 2009/01/02 23:07:49 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: # use Date::Parse;
   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   80:             $_64bit %env %protocol);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  103: 
  104: require Exporter;
  105: 
  106: our @ISA = qw (Exporter);
  107: our @EXPORT = qw(%env);
  108: 
  109: 
  110: # --------------------------------------------------------------------- Logging
  111: {
  112:     my $logid;
  113:     sub instructor_log {
  114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  115:         if (($cnum eq '') || ($cdom eq '')) {
  116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  118:         }
  119: 	$logid++;
  120:         my $now = time();
  121: 	my $id=$now.'00000'.$$.'00000'.$logid;
  122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  123: 				    { $id => {
  124: 					'exe_uname' => $env{'user.name'},
  125: 					'exe_udom'  => $env{'user.domain'},
  126: 					'exe_time'  => $now,
  127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  128: 					'delflag'   => $delflag,
  129: 					'logentry'  => $storehash,
  130: 					'uname'     => $uname,
  131: 					'udom'      => $udom,
  132: 				    }
  133: 				  },$cdom,$cnum);
  134:     }
  135: }
  136: 
  137: sub logtouch {
  138:     my $execdir=$perlvar{'lonDaemons'};
  139:     unless (-e "$execdir/logs/lonnet.log") {	
  140: 	open(my $fh,">>$execdir/logs/lonnet.log");
  141: 	close $fh;
  142:     }
  143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  145: }
  146: 
  147: sub logthis {
  148:     my $message=shift;
  149:     my $execdir=$perlvar{'lonDaemons'};
  150:     my $now=time;
  151:     my $local=localtime($now);
  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  153: 	print $fh "$local ($$): $message\n";
  154: 	close($fh);
  155:     }
  156:     return 1;
  157: }
  158: 
  159: sub logperm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  165: 	print $fh "$now:$message:$local\n";
  166: 	close($fh);
  167:     }
  168:     return 1;
  169: }
  170: 
  171: sub create_connection {
  172:     my ($hostname,$lonid) = @_;
  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  174: 				     Type    => SOCK_STREAM,
  175: 				     Timeout => 10);
  176:     return 0 if (!$client);
  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  178:     my $result = <$client>;
  179:     chomp($result);
  180:     return 1 if ($result eq 'done');
  181:     return 0;
  182: }
  183: 
  184: sub get_server_timezone {
  185:     my ($cnum,$cdom) = @_;
  186:     my $home=&homeserver($cnum,$cdom);
  187:     if ($home ne 'no_host') {
  188:         my $cachetime = 24*3600;
  189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  190:         if (defined($cached)) {
  191:             return $timezone;
  192:         } else {
  193:             my $timezone = &reply('servertimezone',$home);
  194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  195:         }
  196:     }
  197: }
  198: 
  199: # -------------------------------------------------- Non-critical communication
  200: sub subreply {
  201:     my ($cmd,$server)=@_;
  202:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  203:     #
  204:     #  With loncnew process trimming, there's a timing hole between lonc server
  205:     #  process exit and the master server picking up the listen on the AF_UNIX
  206:     #  socket.  In that time interval, a lock file will exist:
  207: 
  208:     my $lockfile=$peerfile.".lock";
  209:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  210: 	sleep(1);
  211:     }
  212:     # At this point, either a loncnew parent is listening or an old lonc
  213:     # or loncnew child is listening so we can connect or everything's dead.
  214:     #
  215:     #   We'll give the connection a few tries before abandoning it.  If
  216:     #   connection is not possible, we'll con_lost back to the client.
  217:     #   
  218:     my $client;
  219:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  220: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  221: 				      Type    => SOCK_STREAM,
  222: 				      Timeout => 10);
  223: 	if ($client) {
  224: 	    last;		# Connected!
  225: 	} else {
  226: 	    &create_connection(&hostname($server),$server);
  227: 	}
  228:         sleep(1);		# Try again later if failed connection.
  229:     }
  230:     my $answer;
  231:     if ($client) {
  232: 	print $client "sethost:$server:$cmd\n";
  233: 	$answer=<$client>;
  234: 	if (!$answer) { $answer="con_lost"; }
  235: 	chomp($answer);
  236:     } else {
  237: 	$answer = 'con_lost';	# Failed connection.
  238:     }
  239:     return $answer;
  240: }
  241: 
  242: sub reply {
  243:     my ($cmd,$server)=@_;
  244:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  245:     my $answer=subreply($cmd,$server);
  246:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  247:        &logthis("<font color=\"blue\">WARNING:".
  248:                 " $cmd to $server returned $answer</font>");
  249:     }
  250:     return $answer;
  251: }
  252: 
  253: # ----------------------------------------------------------- Send USR1 to lonc
  254: 
  255: sub reconlonc {
  256:     my ($lonid) = @_;
  257:     my $hostname = &hostname($lonid);
  258:     if ($lonid) {
  259: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  260: 	if ($hostname && -e $peerfile) {
  261: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  262: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  263: 					     Type    => SOCK_STREAM,
  264: 					     Timeout => 10);
  265: 	    if ($client) {
  266: 		print $client ("reset_retries\n");
  267: 		my $answer=<$client>;
  268: 		#reset just this one.
  269: 	    }
  270: 	}
  271: 	return;
  272:     }
  273: 
  274:     &logthis("Trying to reconnect lonc");
  275:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  276:     if (open(my $fh,"<$loncfile")) {
  277: 	my $loncpid=<$fh>;
  278:         chomp($loncpid);
  279:         if (kill 0 => $loncpid) {
  280: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  281:             kill USR1 => $loncpid;
  282:             sleep 1;
  283:          } else {
  284: 	    &logthis(
  285:                "<font color=\"blue\">WARNING:".
  286:                " lonc at pid $loncpid not responding, giving up</font>");
  287:         }
  288:     } else {
  289: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  290:     }
  291: }
  292: 
  293: # ------------------------------------------------------ Critical communication
  294: 
  295: sub critical {
  296:     my ($cmd,$server)=@_;
  297:     unless (&hostname($server)) {
  298:         &logthis("<font color=\"blue\">WARNING:".
  299:                " Critical message to unknown server ($server)</font>");
  300:         return 'no_such_host';
  301:     }
  302:     my $answer=reply($cmd,$server);
  303:     if ($answer eq 'con_lost') {
  304: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  305: 	my $answer=reply($cmd,$server);
  306:         if ($answer eq 'con_lost') {
  307:             my $now=time;
  308:             my $middlename=$cmd;
  309:             $middlename=substr($middlename,0,16);
  310:             $middlename=~s/\W//g;
  311:             my $dfilename=
  312:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  313:             $dumpcount++;
  314:             {
  315: 		my $dfh;
  316: 		if (open($dfh,">$dfilename")) {
  317: 		    print $dfh "$cmd\n"; 
  318: 		    close($dfh);
  319: 		}
  320:             }
  321:             sleep 2;
  322:             my $wcmd='';
  323:             {
  324: 		my $dfh;
  325: 		if (open($dfh,"<$dfilename")) {
  326: 		    $wcmd=<$dfh>; 
  327: 		    close($dfh);
  328: 		}
  329:             }
  330:             chomp($wcmd);
  331:             if ($wcmd eq $cmd) {
  332: 		&logthis("<font color=\"blue\">WARNING: ".
  333:                          "Connection buffer $dfilename: $cmd</font>");
  334:                 &logperm("D:$server:$cmd");
  335: 	        return 'con_delayed';
  336:             } else {
  337:                 &logthis("<font color=\"red\">CRITICAL:"
  338:                         ." Critical connection failed: $server $cmd</font>");
  339:                 &logperm("F:$server:$cmd");
  340:                 return 'con_failed';
  341:             }
  342:         }
  343:     }
  344:     return $answer;
  345: }
  346: 
  347: # ------------------------------------------- check if return value is an error
  348: 
  349: sub error {
  350:     my ($result) = @_;
  351:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  352: 	if ($2 == 2) { return undef; }
  353: 	return $1;
  354:     }
  355:     return undef;
  356: }
  357: 
  358: sub convert_and_load_session_env {
  359:     my ($lonidsdir,$handle)=@_;
  360:     my @profile;
  361:     {
  362: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  363: 	if (!$opened) {
  364: 	    return 0;
  365: 	}
  366: 	flock($idf,LOCK_SH);
  367: 	@profile=<$idf>;
  368: 	close($idf);
  369:     }
  370:     my %temp_env;
  371:     foreach my $line (@profile) {
  372: 	if ($line !~ m/=/) {
  373: 	    return 0;
  374: 	}
  375: 	chomp($line);
  376: 	my ($envname,$envvalue)=split(/=/,$line,2);
  377: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  378:     }
  379:     unlink("$lonidsdir/$handle.id");
  380:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  381: 	    0640)) {
  382: 	%disk_env = %temp_env;
  383: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  384: 	untie(%disk_env);
  385:     }
  386:     return 1;
  387: }
  388: 
  389: # ------------------------------------------- Transfer profile into environment
  390: my $env_loaded;
  391: sub transfer_profile_to_env {
  392:     my ($lonidsdir,$handle,$force_transfer) = @_;
  393:     if (!$force_transfer && $env_loaded) { return; } 
  394: 
  395:     if (!defined($lonidsdir)) {
  396: 	$lonidsdir = $perlvar{'lonIDsDir'};
  397:     }
  398:     if (!defined($handle)) {
  399:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  400:     }
  401: 
  402:     my $convert;
  403:     {
  404:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  405: 	if (!$opened) {
  406: 	    return;
  407: 	}
  408: 	flock($idf,LOCK_SH);
  409: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  410: 		&GDBM_READER(),0640)) {
  411: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  412: 	    untie(%disk_env);
  413: 	} else {
  414: 	    $convert = 1;
  415: 	}
  416:     }
  417:     if ($convert) {
  418: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  419: 	    &logthis("Failed to load session, or convert session.");
  420: 	}
  421:     }
  422: 
  423:     my %remove;
  424:     while ( my $envname = each(%env) ) {
  425:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  426:             if ($time < time-300) {
  427:                 $remove{$key}++;
  428:             }
  429:         }
  430:     }
  431: 
  432:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  433:     $env_loaded=1;
  434:     foreach my $expired_key (keys(%remove)) {
  435:         &delenv($expired_key);
  436:     }
  437: }
  438: 
  439: # ---------------------------------------------------- Check for valid session 
  440: sub check_for_valid_session {
  441:     my ($r) = @_;
  442:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  443:     my $lonid=$cookies{'lonID'};
  444:     return undef if (!$lonid);
  445: 
  446:     my $handle=&LONCAPA::clean_handle($lonid->value);
  447:     my $lonidsdir=$r->dir_config('lonIDsDir');
  448:     return undef if (!-e "$lonidsdir/$handle.id");
  449: 
  450:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  451:     return undef if (!$opened);
  452: 
  453:     flock($idf,LOCK_SH);
  454:     my %disk_env;
  455:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  456: 	    &GDBM_READER(),0640)) {
  457: 	return undef;	
  458:     }
  459: 
  460:     if (!defined($disk_env{'user.name'})
  461: 	|| !defined($disk_env{'user.domain'})) {
  462: 	return undef;
  463:     }
  464:     return $handle;
  465: }
  466: 
  467: sub timed_flock {
  468:     my ($file,$lock_type) = @_;
  469:     my $failed=0;
  470:     eval {
  471: 	local $SIG{__DIE__}='DEFAULT';
  472: 	local $SIG{ALRM}=sub {
  473: 	    $failed=1;
  474: 	    die("failed lock");
  475: 	};
  476: 	alarm(13);
  477: 	flock($file,$lock_type);
  478: 	alarm(0);
  479:     };
  480:     if ($failed) {
  481: 	return undef;
  482:     } else {
  483: 	return 1;
  484:     }
  485: }
  486: 
  487: # ---------------------------------------------------------- Append Environment
  488: 
  489: sub appenv {
  490:     my ($newenv,$roles) = @_;
  491:     if (ref($newenv) eq 'HASH') {
  492:         foreach my $key (keys(%{$newenv})) {
  493:             my $refused = 0;
  494: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  495:                 $refused = 1;
  496:                 if (ref($roles) eq 'ARRAY') {
  497:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  498:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  499:                         $refused = 0;
  500:                     }
  501:                 }
  502:             }
  503:             if ($refused) {
  504:                 &logthis("<font color=\"blue\">WARNING: ".
  505:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  506:                          .'</font>');
  507: 	        delete($newenv->{$key});
  508:             } else {
  509:                 $env{$key}=$newenv->{$key};
  510:             }
  511:         }
  512:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  513:         if ($opened
  514: 	    && &timed_flock($env_file,LOCK_EX)
  515: 	    &&
  516: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  517: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  518: 	    while (my ($key,$value) = each(%{$newenv})) {
  519: 	        $disk_env{$key} = $value;
  520: 	    }
  521: 	    untie(%disk_env);
  522:         }
  523:     }
  524:     return 'ok';
  525: }
  526: # ----------------------------------------------------- Delete from Environment
  527: 
  528: sub delenv {
  529:     my $delthis=shift;
  530:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  531:         &logthis("<font color=\"blue\">WARNING: ".
  532:                 "Attempt to delete from environment ".$delthis);
  533:         return 'error';
  534:     }
  535:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  536:     if ($opened
  537: 	&& &timed_flock($env_file,LOCK_EX)
  538: 	&&
  539: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  540: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  541: 	foreach my $key (keys(%disk_env)) {
  542: 	    if ($key=~/^\Q$delthis\E/) { 
  543: 		delete($env{$key});
  544: 		delete($disk_env{$key});
  545: 	    }
  546: 	}
  547: 	untie(%disk_env);
  548:     }
  549:     return 'ok';
  550: }
  551: 
  552: sub get_env_multiple {
  553:     my ($name) = @_;
  554:     my @values;
  555:     if (defined($env{$name})) {
  556:         # exists is it an array
  557:         if (ref($env{$name})) {
  558:             @values=@{ $env{$name} };
  559:         } else {
  560:             $values[0]=$env{$name};
  561:         }
  562:     }
  563:     return(@values);
  564: }
  565: 
  566: # ------------------------------------------------------------------- Locking
  567: 
  568: sub set_lock {
  569:     my ($text)=@_;
  570:     $locknum++;
  571:     my $id=$$.'-'.$locknum;
  572:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  573:              'session.lock.'.$id => $text});
  574:     return $id;
  575: }
  576: 
  577: sub get_locks {
  578:     my $num=0;
  579:     my %texts=();
  580:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  581:        if ($lock=~/\w/) {
  582:           $num++;
  583:           $texts{$lock}=$env{'session.lock.'.$lock};
  584:        }
  585:    }
  586:    return ($num,%texts);
  587: }
  588: 
  589: sub remove_lock {
  590:     my ($id)=@_;
  591:     my $newlocks='';
  592:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  593:        if (($lock=~/\w/) && ($lock ne $id)) {
  594:           $newlocks.=','.$lock;
  595:        }
  596:     }
  597:     &appenv({'session.locks' => $newlocks});
  598:     &delenv('session.lock.'.$id);
  599: }
  600: 
  601: sub remove_all_locks {
  602:     my $activelocks=$env{'session.locks'};
  603:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  604:        if ($lock=~/\w/) {
  605:           &remove_lock($lock);
  606:        }
  607:     }
  608: }
  609: 
  610: 
  611: # ------------------------------------------ Find out current server userload
  612: sub userload {
  613:     my $numusers=0;
  614:     {
  615: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  616: 	my $filename;
  617: 	my $curtime=time;
  618: 	while ($filename=readdir(LONIDS)) {
  619: 	    next if ($filename eq '.' || $filename eq '..');
  620: 	    next if ($filename =~ /publicuser_\d+\.id/);
  621: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  622: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  623: 	}
  624: 	closedir(LONIDS);
  625:     }
  626:     my $userloadpercent=0;
  627:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  628:     if ($maxuserload) {
  629: 	$userloadpercent=100*$numusers/$maxuserload;
  630:     }
  631:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  632:     return $userloadpercent;
  633: }
  634: 
  635: # ------------------------------------------ Fight off request when overloaded
  636: 
  637: sub overloaderror {
  638:     my ($r,$checkserver)=@_;
  639:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  640:     my $loadavg;
  641:     if ($checkserver eq $perlvar{'lonHostID'}) {
  642:        open(my $loadfile,'/proc/loadavg');
  643:        $loadavg=<$loadfile>;
  644:        $loadavg =~ s/\s.*//g;
  645:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  646:        close($loadfile);
  647:     } else {
  648:        $loadavg=&reply('load',$checkserver);
  649:     }
  650:     my $overload=$loadavg-100;
  651:     if ($overload>0) {
  652: 	$r->err_headers_out->{'Retry-After'}=$overload;
  653:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  654:         return 413;
  655:     }    
  656:     return '';
  657: }
  658: 
  659: # ------------------------------ Find server with least workload from spare.tab
  660: 
  661: sub spareserver {
  662:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  663:     my $spare_server;
  664:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  665:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  666:                                                      :  $userloadpercent;
  667:     
  668:     foreach my $try_server (@{ $spareid{'primary'} }) {
  669: 	($spare_server, $lowest_load) =
  670: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  671:     }
  672: 
  673:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  674: 
  675:     if (!$found_server) {
  676: 	foreach my $try_server (@{ $spareid{'default'} }) {
  677: 	    ($spare_server, $lowest_load) =
  678: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  679: 	}
  680:     }
  681: 
  682:     if (!$want_server_name) {
  683:         my $protocol = 'http';
  684:         if ($protocol{$spare_server} eq 'https') {
  685:             $protocol = $protocol{$spare_server};
  686:         }
  687: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  688:     }
  689:     return $spare_server;
  690: }
  691: 
  692: sub compare_server_load {
  693:     my ($try_server, $spare_server, $lowest_load) = @_;
  694: 
  695:     my $loadans     = &reply('load',    $try_server);
  696:     my $userloadans = &reply('userload',$try_server);
  697: 
  698:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  699: 	next; #didn't get a number from the server
  700:     }
  701: 
  702:     my $load;
  703:     if ($loadans =~ /\d/) {
  704: 	if ($userloadans =~ /\d/) {
  705: 	    #both are numbers, pick the bigger one
  706: 	    $load = ($loadans > $userloadans) ? $loadans 
  707: 		                              : $userloadans;
  708: 	} else {
  709: 	    $load = $loadans;
  710: 	}
  711:     } else {
  712: 	$load = $userloadans;
  713:     }
  714: 
  715:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  716: 	$spare_server = $try_server;
  717: 	$lowest_load  = $load;
  718:     }
  719:     return ($spare_server,$lowest_load);
  720: }
  721: 
  722: # --------------------------- ask offload servers if user already has a session
  723: sub find_existing_session {
  724:     my ($udom,$uname) = @_;
  725:     foreach my $try_server (@{ $spareid{'primary'} },
  726: 			    @{ $spareid{'default'} }) {
  727: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  728:     }
  729:     return;
  730: }
  731: 
  732: # -------------------------------- ask if server already has a session for user
  733: sub has_user_session {
  734:     my ($lonid,$udom,$uname) = @_;
  735:     my $result = &reply(join(':','userhassession',
  736: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  737:     return 1 if ($result eq 'ok');
  738: 
  739:     return 0;
  740: }
  741: 
  742: # --------------------------------------------- Try to change a user's password
  743: 
  744: sub changepass {
  745:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  746:     $currentpass = &escape($currentpass);
  747:     $newpass     = &escape($newpass);
  748:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  749: 		       $server);
  750:     if (! $answer) {
  751: 	&logthis("No reply on password change request to $server ".
  752: 		 "by $uname in domain $udom.");
  753:     } elsif ($answer =~ "^ok") {
  754:         &logthis("$uname in $udom successfully changed their password ".
  755: 		 "on $server.");
  756:     } elsif ($answer =~ "^pwchange_failure") {
  757: 	&logthis("$uname in $udom was unable to change their password ".
  758: 		 "on $server.  The action was blocked by either lcpasswd ".
  759: 		 "or pwchange");
  760:     } elsif ($answer =~ "^non_authorized") {
  761:         &logthis("$uname in $udom did not get their password correct when ".
  762: 		 "attempting to change it on $server.");
  763:     } elsif ($answer =~ "^auth_mode_error") {
  764:         &logthis("$uname in $udom attempted to change their password despite ".
  765: 		 "not being locally or internally authenticated on $server.");
  766:     } elsif ($answer =~ "^unknown_user") {
  767:         &logthis("$uname in $udom attempted to change their password ".
  768: 		 "on $server but were unable to because $server is not ".
  769: 		 "their home server.");
  770:     } elsif ($answer =~ "^refused") {
  771: 	&logthis("$server refused to change $uname in $udom password because ".
  772: 		 "it was sent an unencrypted request to change the password.");
  773:     }
  774:     return $answer;
  775: }
  776: 
  777: # ----------------------- Try to determine user's current authentication scheme
  778: 
  779: sub queryauthenticate {
  780:     my ($uname,$udom)=@_;
  781:     my $uhome=&homeserver($uname,$udom);
  782:     if (!$uhome) {
  783: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  784: 	return 'no_host';
  785:     }
  786:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  787:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  788: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  789:     }
  790:     return $answer;
  791: }
  792: 
  793: # --------- Try to authenticate user from domain's lib servers (first this one)
  794: 
  795: sub authenticate {
  796:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  797:     $upass=&escape($upass);
  798:     $uname= &LONCAPA::clean_username($uname);
  799:     my $uhome=&homeserver($uname,$udom,1);
  800:     my $newhome;
  801:     if ((!$uhome) || ($uhome eq 'no_host')) {
  802: # Maybe the machine was offline and only re-appeared again recently?
  803:         &reconlonc();
  804: # One more
  805: 	$uhome=&homeserver($uname,$udom,1);
  806:         if (($uhome eq 'no_host') && $checkdefauth) {
  807:             if (defined(&domain($udom,'primary'))) {
  808:                 $newhome=&domain($udom,'primary');
  809:             }
  810:             if ($newhome ne '') {
  811:                 $uhome = $newhome;
  812:             }
  813:         }
  814: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  815: 	    &logthis("User $uname at $udom is unknown in authenticate");
  816: 	    return 'no_host';
  817:         }
  818:     }
  819:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  820:     if ($answer eq 'authorized') {
  821:         if ($newhome) {
  822:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  823:             return 'no_account_on_host'; 
  824:         } else {
  825:             &logthis("User $uname at $udom authorized by $uhome");
  826:             return $uhome;
  827:         }
  828:     }
  829:     if ($answer eq 'non_authorized') {
  830: 	&logthis("User $uname at $udom rejected by $uhome");
  831: 	return 'no_host'; 
  832:     }
  833:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  834:     return 'no_host';
  835: }
  836: 
  837: # ---------------------- Find the homebase for a user from domain's lib servers
  838: 
  839: my %homecache;
  840: sub homeserver {
  841:     my ($uname,$udom,$ignoreBadCache)=@_;
  842:     my $index="$uname:$udom";
  843: 
  844:     if (exists($homecache{$index})) { return $homecache{$index}; }
  845: 
  846:     my %servers = &get_servers($udom,'library');
  847:     foreach my $tryserver (keys(%servers)) {
  848:         next if ($ignoreBadCache ne 'true' && 
  849: 		 exists($badServerCache{$tryserver}));
  850: 
  851: 	my $answer=reply("home:$udom:$uname",$tryserver);
  852: 	if ($answer eq 'found') {
  853: 	    delete($badServerCache{$tryserver}); 
  854: 	    return $homecache{$index}=$tryserver;
  855: 	} elsif ($answer eq 'no_host') {
  856: 	    $badServerCache{$tryserver}=1;
  857: 	}
  858:     }    
  859:     return 'no_host';
  860: }
  861: 
  862: # ------------------------------------- Find the usernames behind a list of IDs
  863: 
  864: sub idget {
  865:     my ($udom,@ids)=@_;
  866:     my %returnhash=();
  867:     
  868:     my %servers = &get_servers($udom,'library');
  869:     foreach my $tryserver (keys(%servers)) {
  870: 	my $idlist=join('&',@ids);
  871: 	$idlist=~tr/A-Z/a-z/; 
  872: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  873: 	my @answer=();
  874: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  875: 	    @answer=split(/\&/,$reply);
  876: 	}                    ;
  877: 	my $i;
  878: 	for ($i=0;$i<=$#ids;$i++) {
  879: 	    if ($answer[$i]) {
  880: 		$returnhash{$ids[$i]}=$answer[$i];
  881: 	    } 
  882: 	}
  883:     } 
  884:     return %returnhash;
  885: }
  886: 
  887: # ------------------------------------- Find the IDs behind a list of usernames
  888: 
  889: sub idrget {
  890:     my ($udom,@unames)=@_;
  891:     my %returnhash=();
  892:     foreach my $uname (@unames) {
  893:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  894:     }
  895:     return %returnhash;
  896: }
  897: 
  898: # ------------------------------- Store away a list of names and associated IDs
  899: 
  900: sub idput {
  901:     my ($udom,%ids)=@_;
  902:     my %servers=();
  903:     foreach my $uname (keys(%ids)) {
  904: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  905:         my $uhom=&homeserver($uname,$udom);
  906:         if ($uhom ne 'no_host') {
  907:             my $id=&escape($ids{$uname});
  908:             $id=~tr/A-Z/a-z/;
  909:             my $esc_unam=&escape($uname);
  910: 	    if ($servers{$uhom}) {
  911: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  912:             } else {
  913:                 $servers{$uhom}=$id.'='.$esc_unam;
  914:             }
  915:         }
  916:     }
  917:     foreach my $server (keys(%servers)) {
  918:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  919:     }
  920: }
  921: 
  922: # ------------------------------------------- get items from domain db files   
  923: 
  924: sub get_dom {
  925:     my ($namespace,$storearr,$udom,$uhome)=@_;
  926:     my $items='';
  927:     foreach my $item (@$storearr) {
  928:         $items.=&escape($item).'&';
  929:     }
  930:     $items=~s/\&$//;
  931:     if (!$udom) {
  932:         $udom=$env{'user.domain'};
  933:         if (defined(&domain($udom,'primary'))) {
  934:             $uhome=&domain($udom,'primary');
  935:         } else {
  936:             undef($uhome);
  937:         }
  938:     } else {
  939:         if (!$uhome) {
  940:             if (defined(&domain($udom,'primary'))) {
  941:                 $uhome=&domain($udom,'primary');
  942:             }
  943:         }
  944:     }
  945:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  946:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  947:         my %returnhash;
  948:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  949:             return %returnhash;
  950:         }
  951:         my @pairs=split(/\&/,$rep);
  952:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  953:             return @pairs;
  954:         }
  955:         my $i=0;
  956:         foreach my $item (@$storearr) {
  957:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  958:             $i++;
  959:         }
  960:         return %returnhash;
  961:     } else {
  962:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  963:     }
  964: }
  965: 
  966: # -------------------------------------------- put items in domain db files 
  967: 
  968: sub put_dom {
  969:     my ($namespace,$storehash,$udom,$uhome)=@_;
  970:     if (!$udom) {
  971:         $udom=$env{'user.domain'};
  972:         if (defined(&domain($udom,'primary'))) {
  973:             $uhome=&domain($udom,'primary');
  974:         } else {
  975:             undef($uhome);
  976:         }
  977:     } else {
  978:         if (!$uhome) {
  979:             if (defined(&domain($udom,'primary'))) {
  980:                 $uhome=&domain($udom,'primary');
  981:             }
  982:         }
  983:     } 
  984:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  985:         my $items='';
  986:         foreach my $item (keys(%$storehash)) {
  987:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  988:         }
  989:         $items=~s/\&$//;
  990:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  991:     } else {
  992:         &logthis("put_dom failed - no homeserver and/or domain");
  993:     }
  994: }
  995: 
  996: sub retrieve_inst_usertypes {
  997:     my ($udom) = @_;
  998:     my (%returnhash,@order);
  999:     if (defined(&domain($udom,'primary'))) {
 1000:         my $uhome=&domain($udom,'primary');
 1001:         my $rep=&reply("inst_usertypes:$udom",$uhome);
 1002:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1003:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1004:             return (\%returnhash,\@order);
 1005:         }
 1006:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1007:         my @pairs=split(/\&/,$hashitems);
 1008:         foreach my $item (@pairs) {
 1009:             my ($key,$value)=split(/=/,$item,2);
 1010:             $key = &unescape($key);
 1011:             next if ($key =~ /^error: 2 /);
 1012:             $returnhash{$key}=&thaw_unescape($value);
 1013:         }
 1014:         my @esc_order = split(/\&/,$orderitems);
 1015:         foreach my $item (@esc_order) {
 1016:             push(@order,&unescape($item));
 1017:         }
 1018:     } else {
 1019:         &logthis("get_dom failed - no primary domain server for $udom");
 1020:     }
 1021:     return (\%returnhash,\@order);
 1022: }
 1023: 
 1024: sub is_domainimage {
 1025:     my ($url) = @_;
 1026:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1027:         if (&domain($1) ne '') {
 1028:             return '1';
 1029:         }
 1030:     }
 1031:     return;
 1032: }
 1033: 
 1034: sub inst_directory_query {
 1035:     my ($srch) = @_;
 1036:     my $udom = $srch->{'srchdomain'};
 1037:     my %results;
 1038:     my $homeserver = &domain($udom,'primary');
 1039:     my $outcome;
 1040:     if ($homeserver ne '') {
 1041: 	my $queryid=&reply("querysend:instdirsearch:".
 1042: 			   &escape($srch->{'srchby'}).':'.
 1043: 			   &escape($srch->{'srchterm'}).':'.
 1044: 			   &escape($srch->{'srchtype'}),$homeserver);
 1045: 	my $host=&hostname($homeserver);
 1046: 	if ($queryid !~/^\Q$host\E\_/) {
 1047: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1048: 	    return;
 1049: 	}
 1050: 	my $response = &get_query_reply($queryid);
 1051: 	my $maxtries = 5;
 1052: 	my $tries = 1;
 1053: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1054: 	    $response = &get_query_reply($queryid);
 1055: 	    $tries ++;
 1056: 	}
 1057: 
 1058:         if (!&error($response) && $response ne 'refused') {
 1059:             if ($response eq 'unavailable') {
 1060:                 $outcome = $response;
 1061:             } else {
 1062:                 $outcome = 'ok';
 1063:                 my @matches = split(/\n/,$response);
 1064:                 foreach my $match (@matches) {
 1065:                     my ($key,$value) = split(/=/,$match);
 1066:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1067:                 }
 1068:             }
 1069:         }
 1070:     }
 1071:     return ($outcome,%results);
 1072: }
 1073: 
 1074: sub usersearch {
 1075:     my ($srch) = @_;
 1076:     my $dom = $srch->{'srchdomain'};
 1077:     my %results;
 1078:     my %libserv = &all_library();
 1079:     my $query = 'usersearch';
 1080:     foreach my $tryserver (keys(%libserv)) {
 1081:         if (&host_domain($tryserver) eq $dom) {
 1082:             my $host=&hostname($tryserver);
 1083:             my $queryid=
 1084:                 &reply("querysend:".&escape($query).':'.
 1085:                        &escape($srch->{'srchby'}).':'.
 1086:                        &escape($srch->{'srchtype'}).':'.
 1087:                        &escape($srch->{'srchterm'}),$tryserver);
 1088:             if ($queryid !~/^\Q$host\E\_/) {
 1089:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1090:                 next;
 1091:             }
 1092:             my $reply = &get_query_reply($queryid);
 1093:             my $maxtries = 1;
 1094:             my $tries = 1;
 1095:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1096:                 $reply = &get_query_reply($queryid);
 1097:                 $tries ++;
 1098:             }
 1099:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1100:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1101:             } else {
 1102:                 my @matches;
 1103:                 if ($reply =~ /\n/) {
 1104:                     @matches = split(/\n/,$reply);
 1105:                 } else {
 1106:                     @matches = split(/\&/,$reply);
 1107:                 }
 1108:                 foreach my $match (@matches) {
 1109:                     my ($uname,$udom,%userhash);
 1110:                     foreach my $entry (split(/:/,$match)) {
 1111:                         my ($key,$value) =
 1112:                             map {&unescape($_);} split(/=/,$entry);
 1113:                         $userhash{$key} = $value;
 1114:                         if ($key eq 'username') {
 1115:                             $uname = $value;
 1116:                         } elsif ($key eq 'domain') {
 1117:                             $udom = $value;
 1118:                         }
 1119:                     }
 1120:                     $results{$uname.':'.$udom} = \%userhash;
 1121:                 }
 1122:             }
 1123:         }
 1124:     }
 1125:     return %results;
 1126: }
 1127: 
 1128: sub get_instuser {
 1129:     my ($udom,$uname,$id) = @_;
 1130:     my $homeserver = &domain($udom,'primary');
 1131:     my ($outcome,%results);
 1132:     if ($homeserver ne '') {
 1133:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1134:                            &escape($id).':'.&escape($udom),$homeserver);
 1135:         my $host=&hostname($homeserver);
 1136:         if ($queryid !~/^\Q$host\E\_/) {
 1137:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1138:             return;
 1139:         }
 1140:         my $response = &get_query_reply($queryid);
 1141:         my $maxtries = 5;
 1142:         my $tries = 1;
 1143:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1144:             $response = &get_query_reply($queryid);
 1145:             $tries ++;
 1146:         }
 1147:         if (!&error($response) && $response ne 'refused') {
 1148:             if ($response eq 'unavailable') {
 1149:                 $outcome = $response;
 1150:             } else {
 1151:                 $outcome = 'ok';
 1152:                 my @matches = split(/\n/,$response);
 1153:                 foreach my $match (@matches) {
 1154:                     my ($key,$value) = split(/=/,$match);
 1155:                     $results{&unescape($key)} = &thaw_unescape($value);
 1156:                 }
 1157:             }
 1158:         }
 1159:     }
 1160:     my %userinfo;
 1161:     if (ref($results{$uname}) eq 'HASH') {
 1162:         %userinfo = %{$results{$uname}};
 1163:     } 
 1164:     return ($outcome,%userinfo);
 1165: }
 1166: 
 1167: sub inst_rulecheck {
 1168:     my ($udom,$uname,$id,$item,$rules) = @_;
 1169:     my %returnhash;
 1170:     if ($udom ne '') {
 1171:         if (ref($rules) eq 'ARRAY') {
 1172:             @{$rules} = map {&escape($_);} (@{$rules});
 1173:             my $rulestr = join(':',@{$rules});
 1174:             my $homeserver=&domain($udom,'primary');
 1175:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1176:                 my $response;
 1177:                 if ($item eq 'username') {                
 1178:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1179:                                               ':'.&escape($uname).':'.$rulestr,
 1180:                                               $homeserver));
 1181:                 } elsif ($item eq 'id') {
 1182:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1183:                                               ':'.&escape($id).':'.$rulestr,
 1184:                                               $homeserver));
 1185:                 } elsif ($item eq 'selfcreate') {
 1186:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1187:                                                &escape($udom).':'.&escape($uname).
 1188:                                               ':'.$rulestr,$homeserver));
 1189:                 }
 1190:                 if ($response ne 'refused') {
 1191:                     my @pairs=split(/\&/,$response);
 1192:                     foreach my $item (@pairs) {
 1193:                         my ($key,$value)=split(/=/,$item,2);
 1194:                         $key = &unescape($key);
 1195:                         next if ($key =~ /^error: 2 /);
 1196:                         $returnhash{$key}=&thaw_unescape($value);
 1197:                     }
 1198:                 }
 1199:             }
 1200:         }
 1201:     }
 1202:     return %returnhash;
 1203: }
 1204: 
 1205: sub inst_userrules {
 1206:     my ($udom,$check) = @_;
 1207:     my (%ruleshash,@ruleorder);
 1208:     if ($udom ne '') {
 1209:         my $homeserver=&domain($udom,'primary');
 1210:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1211:             my $response;
 1212:             if ($check eq 'id') {
 1213:                 $response=&reply('instidrules:'.&escape($udom),
 1214:                                  $homeserver);
 1215:             } elsif ($check eq 'email') {
 1216:                 $response=&reply('instemailrules:'.&escape($udom),
 1217:                                  $homeserver);
 1218:             } else {
 1219:                 $response=&reply('instuserrules:'.&escape($udom),
 1220:                                  $homeserver);
 1221:             }
 1222:             if (($response ne 'refused') && ($response ne 'error') && 
 1223:                 ($response ne 'unknown_cmd') && 
 1224:                 ($response ne 'no_such_host')) {
 1225:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1226:                 my @pairs=split(/\&/,$hashitems);
 1227:                 foreach my $item (@pairs) {
 1228:                     my ($key,$value)=split(/=/,$item,2);
 1229:                     $key = &unescape($key);
 1230:                     next if ($key =~ /^error: 2 /);
 1231:                     $ruleshash{$key}=&thaw_unescape($value);
 1232:                 }
 1233:                 my @esc_order = split(/\&/,$orderitems);
 1234:                 foreach my $item (@esc_order) {
 1235:                     push(@ruleorder,&unescape($item));
 1236:                 }
 1237:             }
 1238:         }
 1239:     }
 1240:     return (\%ruleshash,\@ruleorder);
 1241: }
 1242: 
 1243: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1244: 
 1245: sub get_domain_defaults {
 1246:     my ($domain) = @_;
 1247:     my $cachetime = 60*60*24;
 1248:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1249:     if (defined($cached)) {
 1250:         if (ref($result) eq 'HASH') {
 1251:             return %{$result};
 1252:         }
 1253:     }
 1254:     my %domdefaults;
 1255:     my %domconfig =
 1256:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1257:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1258:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1259:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1260:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1261:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1262:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'}
 1263:     } else {
 1264:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1265:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1266:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1267:     }
 1268:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1269:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1270:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1271:         } else {
 1272:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1273:         } 
 1274:         my @usertools = ('aboutme','blog','portfolio');
 1275:         foreach my $item (@usertools) {
 1276:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1277:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1278:             }
 1279:         }
 1280:     }
 1281:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1282:                                   $cachetime);
 1283:     return %domdefaults;
 1284: }
 1285: 
 1286: # --------------------------------------------------- Assign a key to a student
 1287: 
 1288: sub assign_access_key {
 1289: #
 1290: # a valid key looks like uname:udom#comments
 1291: # comments are being appended
 1292: #
 1293:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1294:     $kdom=
 1295:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1296:     $knum=
 1297:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1298:     $cdom=
 1299:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1300:     $cnum=
 1301:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1302:     $udom=$env{'user.name'} unless (defined($udom));
 1303:     $uname=$env{'user.domain'} unless (defined($uname));
 1304:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1305:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1306:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1307:                                                   # assigned to this person
 1308:                                                   # - this should not happen,
 1309:                                                   # unless something went wrong
 1310:                                                   # the first time around
 1311: # ready to assign
 1312:         $logentry=$1.'; '.$logentry;
 1313:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1314:                                                  $kdom,$knum) eq 'ok') {
 1315: # key now belongs to user
 1316: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1317:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1318:                 &appenv({'environment.'.$envkey => $ckey});
 1319:                 return 'ok';
 1320:             } else {
 1321:                 return 
 1322:   'error: Count not permanently assign key, will need to be re-entered later.';
 1323: 	    }
 1324:         } else {
 1325:             return 'error: Could not assign key, try again later.';
 1326:         }
 1327:     } elsif (!$existing{$ckey}) {
 1328: # the key does not exist
 1329: 	return 'error: The key does not exist';
 1330:     } else {
 1331: # the key is somebody else's
 1332: 	return 'error: The key is already in use';
 1333:     }
 1334: }
 1335: 
 1336: # ------------------------------------------ put an additional comment on a key
 1337: 
 1338: sub comment_access_key {
 1339: #
 1340: # a valid key looks like uname:udom#comments
 1341: # comments are being appended
 1342: #
 1343:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1344:     $cdom=
 1345:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1346:     $cnum=
 1347:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1348:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1349:     if ($existing{$ckey}) {
 1350:         $existing{$ckey}.='; '.$logentry;
 1351: # ready to assign
 1352:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1353:                                                  $cdom,$cnum) eq 'ok') {
 1354: 	    return 'ok';
 1355:         } else {
 1356: 	    return 'error: Count not store comment.';
 1357:         }
 1358:     } else {
 1359: # the key does not exist
 1360: 	return 'error: The key does not exist';
 1361:     }
 1362: }
 1363: 
 1364: # ------------------------------------------------------ Generate a set of keys
 1365: 
 1366: sub generate_access_keys {
 1367:     my ($number,$cdom,$cnum,$logentry)=@_;
 1368:     $cdom=
 1369:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1370:     $cnum=
 1371:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1372:     unless (&allowed('mky',$cdom)) { return 0; }
 1373:     unless (($cdom) && ($cnum)) { return 0; }
 1374:     if ($number>10000) { return 0; }
 1375:     sleep(2); # make sure don't get same seed twice
 1376:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1377:     my $total=0;
 1378:     for (my $i=1;$i<=$number;$i++) {
 1379:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1380:                   sprintf("%lx",int(100000*rand)).'-'.
 1381:                   sprintf("%lx",int(100000*rand));
 1382:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1383:        $newkey=~s/0/h/g; # and also 0 and O
 1384:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1385:        if ($existing{$newkey}) {
 1386:            $i--;
 1387:        } else {
 1388: 	  if (&put('accesskeys',
 1389:               { $newkey => '# generated '.localtime().
 1390:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1391:                            '; '.$logentry },
 1392: 		   $cdom,$cnum) eq 'ok') {
 1393:               $total++;
 1394: 	  }
 1395:        }
 1396:     }
 1397:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1398:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1399:     return $total;
 1400: }
 1401: 
 1402: # ------------------------------------------------------- Validate an accesskey
 1403: 
 1404: sub validate_access_key {
 1405:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1406:     $cdom=
 1407:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1408:     $cnum=
 1409:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1410:     $udom=$env{'user.domain'} unless (defined($udom));
 1411:     $uname=$env{'user.name'} unless (defined($uname));
 1412:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1413:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1414: }
 1415: 
 1416: # ------------------------------------- Find the section of student in a course
 1417: sub devalidate_getsection_cache {
 1418:     my ($udom,$unam,$courseid)=@_;
 1419:     my $hashid="$udom:$unam:$courseid";
 1420:     &devalidate_cache_new('getsection',$hashid);
 1421: }
 1422: 
 1423: sub courseid_to_courseurl {
 1424:     my ($courseid) = @_;
 1425:     #already url style courseid
 1426:     return $courseid if ($courseid =~ m{^/});
 1427: 
 1428:     if (exists($env{'course.'.$courseid.'.num'})) {
 1429: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1430: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1431: 	return "/$cdom/$cnum";
 1432:     }
 1433: 
 1434:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1435:     if (exists($courseinfo{'num'})) {
 1436: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1437:     }
 1438: 
 1439:     return undef;
 1440: }
 1441: 
 1442: sub getsection {
 1443:     my ($udom,$unam,$courseid)=@_;
 1444:     my $cachetime=1800;
 1445: 
 1446:     my $hashid="$udom:$unam:$courseid";
 1447:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1448:     if (defined($cached)) { return $result; }
 1449: 
 1450:     my %Pending; 
 1451:     my %Expired;
 1452:     #
 1453:     # Each role can either have not started yet (pending), be active, 
 1454:     #    or have expired.
 1455:     #
 1456:     # If there is an active role, we are done.
 1457:     #
 1458:     # If there is more than one role which has not started yet, 
 1459:     #     choose the one which will start sooner
 1460:     # If there is one role which has not started yet, return it.
 1461:     #
 1462:     # If there is more than one expired role, choose the one which ended last.
 1463:     # If there is a role which has expired, return it.
 1464:     #
 1465:     $courseid = &courseid_to_courseurl($courseid);
 1466:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1467:     foreach my $key (keys(%roleshash)) {
 1468:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1469:         my $section=$1;
 1470:         if ($key eq $courseid.'_st') { $section=''; }
 1471:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1472:         my $now=time;
 1473:         if (defined($end) && $end && ($now > $end)) {
 1474:             $Expired{$end}=$section;
 1475:             next;
 1476:         }
 1477:         if (defined($start) && $start && ($now < $start)) {
 1478:             $Pending{$start}=$section;
 1479:             next;
 1480:         }
 1481:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1482:     }
 1483:     #
 1484:     # Presumedly there will be few matching roles from the above
 1485:     # loop and the sorting time will be negligible.
 1486:     if (scalar(keys(%Pending))) {
 1487:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1488:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1489:     } 
 1490:     if (scalar(keys(%Expired))) {
 1491:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1492:         my $time = pop(@sorted);
 1493:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1494:     }
 1495:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1496: }
 1497: 
 1498: sub save_cache {
 1499:     &purge_remembered();
 1500:     #&Apache::loncommon::validate_page();
 1501:     undef(%env);
 1502:     undef($env_loaded);
 1503: }
 1504: 
 1505: my $to_remember=-1;
 1506: my %remembered;
 1507: my %accessed;
 1508: my $kicks=0;
 1509: my $hits=0;
 1510: sub make_key {
 1511:     my ($name,$id) = @_;
 1512:     if (length($id) > 65 
 1513: 	&& length(&escape($id)) > 200) {
 1514: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1515:     }
 1516:     return &escape($name.':'.$id);
 1517: }
 1518: 
 1519: sub devalidate_cache_new {
 1520:     my ($name,$id,$debug) = @_;
 1521:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1522:     $id=&make_key($name,$id);
 1523:     $memcache->delete($id);
 1524:     delete($remembered{$id});
 1525:     delete($accessed{$id});
 1526: }
 1527: 
 1528: sub is_cached_new {
 1529:     my ($name,$id,$debug) = @_;
 1530:     $id=&make_key($name,$id);
 1531:     if (exists($remembered{$id})) {
 1532: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1533: 	$accessed{$id}=[&gettimeofday()];
 1534: 	$hits++;
 1535: 	return ($remembered{$id},1);
 1536:     }
 1537:     my $value = $memcache->get($id);
 1538:     if (!(defined($value))) {
 1539: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1540: 	return (undef,undef);
 1541:     }
 1542:     if ($value eq '__undef__') {
 1543: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1544: 	$value=undef;
 1545:     }
 1546:     &make_room($id,$value,$debug);
 1547:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1548:     return ($value,1);
 1549: }
 1550: 
 1551: sub do_cache_new {
 1552:     my ($name,$id,$value,$time,$debug) = @_;
 1553:     $id=&make_key($name,$id);
 1554:     my $setvalue=$value;
 1555:     if (!defined($setvalue)) {
 1556: 	$setvalue='__undef__';
 1557:     }
 1558:     if (!defined($time) ) {
 1559: 	$time=600;
 1560:     }
 1561:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1562:     my $result = $memcache->set($id,$setvalue,$time);
 1563:     if (! $result) {
 1564: 	&logthis("caching of id -> $id  failed");
 1565: 	$memcache->disconnect_all();
 1566:     }
 1567:     # need to make a copy of $value
 1568:     &make_room($id,$value,$debug);
 1569:     return $value;
 1570: }
 1571: 
 1572: sub make_room {
 1573:     my ($id,$value,$debug)=@_;
 1574: 
 1575:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1576:                                     : $value;
 1577:     if ($to_remember<0) { return; }
 1578:     $accessed{$id}=[&gettimeofday()];
 1579:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1580:     my $to_kick;
 1581:     my $max_time=0;
 1582:     foreach my $other (keys(%accessed)) {
 1583: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1584: 	    $to_kick=$other;
 1585: 	    $max_time=&tv_interval($accessed{$other});
 1586: 	}
 1587:     }
 1588:     delete($remembered{$to_kick});
 1589:     delete($accessed{$to_kick});
 1590:     $kicks++;
 1591:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1592:     return;
 1593: }
 1594: 
 1595: sub purge_remembered {
 1596:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1597:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1598:     undef(%remembered);
 1599:     undef(%accessed);
 1600: }
 1601: # ------------------------------------- Read an entry from a user's environment
 1602: 
 1603: sub userenvironment {
 1604:     my ($udom,$unam,@what)=@_;
 1605:     my $items;
 1606:     foreach my $item (@what) {
 1607:         $items.=&escape($item).'&';
 1608:     }
 1609:     $items=~s/\&$//;
 1610:     my %returnhash=();
 1611:     my @answer=split(/\&/,
 1612:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1613:                       &homeserver($unam,$udom)));
 1614:     my $i;
 1615:     for ($i=0;$i<=$#what;$i++) {
 1616: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1617:     }
 1618:     return %returnhash;
 1619: }
 1620: 
 1621: # ---------------------------------------------------------- Get a studentphoto
 1622: sub studentphoto {
 1623:     my ($udom,$unam,$ext) = @_;
 1624:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1625:     if (defined($env{'request.course.id'})) {
 1626:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1627:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1628:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1629:             } else {
 1630:                 my ($result,$perm_reqd)=
 1631: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1632:                 if ($result eq 'ok') {
 1633:                     if (!($perm_reqd eq 'yes')) {
 1634:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1635:                     }
 1636:                 }
 1637:             }
 1638:         }
 1639:     } else {
 1640:         my ($result,$perm_reqd) = 
 1641: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1642:         if ($result eq 'ok') {
 1643:             if (!($perm_reqd eq 'yes')) {
 1644:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1645:             }
 1646:         }
 1647:     }
 1648:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1649: }
 1650: 
 1651: sub retrievestudentphoto {
 1652:     my ($udom,$unam,$ext,$type) = @_;
 1653:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1654:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1655:     if ($ret eq 'ok') {
 1656:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1657:         if ($type eq 'thumbnail') {
 1658:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1659:         }
 1660:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1661:         return $tokenurl;
 1662:     } else {
 1663:         if ($type eq 'thumbnail') {
 1664:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1665:         } else { 
 1666:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1667:         }
 1668:     }
 1669: }
 1670: 
 1671: # -------------------------------------------------------------------- New chat
 1672: 
 1673: sub chatsend {
 1674:     my ($newentry,$anon,$group)=@_;
 1675:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1676:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1677:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1678:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1679: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1680: 		   &escape($newentry)).':'.$group,$chome);
 1681: }
 1682: 
 1683: # ------------------------------------------ Find current version of a resource
 1684: 
 1685: sub getversion {
 1686:     my $fname=&clutter(shift);
 1687:     unless ($fname=~/^\/res\//) { return -1; }
 1688:     return &currentversion(&filelocation('',$fname));
 1689: }
 1690: 
 1691: sub currentversion {
 1692:     my $fname=shift;
 1693:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1694:     if (defined($cached)) { return $result; }
 1695:     my $author=$fname;
 1696:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1697:     my ($udom,$uname)=split(/\//,$author);
 1698:     my $home=homeserver($uname,$udom);
 1699:     if ($home eq 'no_host') { 
 1700:         return -1; 
 1701:     }
 1702:     my $answer=reply("currentversion:$fname",$home);
 1703:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1704: 	return -1;
 1705:     }
 1706:     return &do_cache_new('resversion',$fname,$answer,600);
 1707: }
 1708: 
 1709: # ----------------------------- Subscribe to a resource, return URL if possible
 1710: 
 1711: sub subscribe {
 1712:     my $fname=shift;
 1713:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1714:     $fname=~s/[\n\r]//g;
 1715:     my $author=$fname;
 1716:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1717:     my ($udom,$uname)=split(/\//,$author);
 1718:     my $home=homeserver($uname,$udom);
 1719:     if ($home eq 'no_host') {
 1720:         return 'not_found';
 1721:     }
 1722:     my $answer=reply("sub:$fname",$home);
 1723:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1724: 	$answer.=' by '.$home;
 1725:     }
 1726:     return $answer;
 1727: }
 1728:     
 1729: # -------------------------------------------------------------- Replicate file
 1730: 
 1731: sub repcopy {
 1732:     my $filename=shift;
 1733:     $filename=~s/\/+/\//g;
 1734:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1735:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1736:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1737: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1738: 	return &repcopy_userfile($filename);
 1739:     }
 1740:     $filename=~s/[\n\r]//g;
 1741:     my $transname="$filename.in.transfer";
 1742: # FIXME: this should flock
 1743:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1744:     my $remoteurl=subscribe($filename);
 1745:     if ($remoteurl =~ /^con_lost by/) {
 1746: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1747:            return 'unavailable';
 1748:     } elsif ($remoteurl eq 'not_found') {
 1749: 	   #&logthis("Subscribe returned not_found: $filename");
 1750: 	   return 'not_found';
 1751:     } elsif ($remoteurl =~ /^rejected by/) {
 1752: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1753:            return 'forbidden';
 1754:     } elsif ($remoteurl eq 'directory') {
 1755:            return 'ok';
 1756:     } else {
 1757:         my $author=$filename;
 1758:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1759:         my ($udom,$uname)=split(/\//,$author);
 1760:         my $home=homeserver($uname,$udom);
 1761:         unless ($home eq $perlvar{'lonHostID'}) {
 1762:            my @parts=split(/\//,$filename);
 1763:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1764:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1765:                &logthis("Malconfiguration for replication: $filename");
 1766: 	       return 'bad_request';
 1767:            }
 1768:            my $count;
 1769:            for ($count=5;$count<$#parts;$count++) {
 1770:                $path.="/$parts[$count]";
 1771:                if ((-e $path)!=1) {
 1772: 		   mkdir($path,0777);
 1773:                }
 1774:            }
 1775:            my $ua=new LWP::UserAgent;
 1776:            my $request=new HTTP::Request('GET',"$remoteurl");
 1777:            my $response=$ua->request($request,$transname);
 1778:            if ($response->is_error()) {
 1779: 	       unlink($transname);
 1780:                my $message=$response->status_line;
 1781:                &logthis("<font color=\"blue\">WARNING:"
 1782:                        ." LWP get: $message: $filename</font>");
 1783:                return 'unavailable';
 1784:            } else {
 1785: 	       if ($remoteurl!~/\.meta$/) {
 1786:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1787:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1788:                   if ($mresponse->is_error()) {
 1789: 		      unlink($filename.'.meta');
 1790:                       &logthis(
 1791:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1792:                   }
 1793: 	       }
 1794:                rename($transname,$filename);
 1795:                return 'ok';
 1796:            }
 1797:        }
 1798:     }
 1799: }
 1800: 
 1801: # ------------------------------------------------ Get server side include body
 1802: sub ssi_body {
 1803:     my ($filelink,%form)=@_;
 1804:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1805:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1806:     }
 1807:     my $output='';
 1808:     my $response;
 1809:     if ($filelink=~/^https?\:/) {
 1810:        ($output,$response)=&externalssi($filelink);
 1811:     } else {
 1812:        ($output,$response)=&ssi($filelink,%form);
 1813:     }
 1814:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1815:     $output=~s/^.*?\<body[^\>]*\>//si;
 1816:     $output=~s/\<\/body\s*\>.*?$//si;
 1817:     if (wantarray) {
 1818:         return ($output, $response);
 1819:     } else {
 1820:         return $output;
 1821:     }
 1822: }
 1823: 
 1824: # --------------------------------------------------------- Server Side Include
 1825: 
 1826: sub absolute_url {
 1827:     my ($host_name) = @_;
 1828:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1829:     if ($host_name eq '') {
 1830: 	$host_name = $ENV{'SERVER_NAME'};
 1831:     }
 1832:     return $protocol.$host_name;
 1833: }
 1834: 
 1835: #
 1836: #   Server side include.
 1837: # Parameters:
 1838: #  fn     Possibly encrypted resource name/id.
 1839: #  form   Hash that describes how the rendering should be done
 1840: #         and other things.
 1841: # Returns:
 1842: #   Scalar context: The content of the response.
 1843: #   Array context:  2 element list of the content and the full response object.
 1844: #     
 1845: sub ssi {
 1846: 
 1847:     my ($fn,%form)=@_;
 1848:     my $ua=new LWP::UserAgent;
 1849:     my $request;
 1850: 
 1851:     $form{'no_update_last_known'}=1;
 1852:     &Apache::lonenc::check_encrypt(\$fn);
 1853:     if (%form) {
 1854:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1855:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1856:     } else {
 1857:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1858:     }
 1859: 
 1860:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1861:     my $response=$ua->request($request);
 1862: 
 1863:     if (wantarray) {
 1864: 	return ($response->content, $response);
 1865:     } else {
 1866: 	return $response->content;
 1867:     }
 1868: }
 1869: 
 1870: sub externalssi {
 1871:     my ($url)=@_;
 1872:     my $ua=new LWP::UserAgent;
 1873:     my $request=new HTTP::Request('GET',$url);
 1874:     my $response=$ua->request($request);
 1875:     if (wantarray) {
 1876:         return ($response->content, $response);
 1877:     } else {
 1878:         return $response->content;
 1879:     }
 1880: }
 1881: 
 1882: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1883: 
 1884: sub allowuploaded {
 1885:     my ($srcurl,$url)=@_;
 1886:     $url=&clutter(&declutter($url));
 1887:     my $dir=$url;
 1888:     $dir=~s/\/[^\/]+$//;
 1889:     my %httpref=();
 1890:     my $httpurl=&hreflocation('',$url);
 1891:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1892:     &Apache::lonnet::appenv(\%httpref);
 1893: }
 1894: 
 1895: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1896: # input: action, courseID, current domain, intended
 1897: #        path to file, source of file, instruction to parse file for objects,
 1898: #        ref to hash for embedded objects,
 1899: #        ref to hash for codebase of java objects.
 1900: #
 1901: # output: url to file (if action was uploaddoc), 
 1902: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1903: #
 1904: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1905: # course.
 1906: #
 1907: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1908: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1909: #          course's home server.
 1910: #
 1911: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1912: #          be copied from $source (current location) to 
 1913: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1914: #         and will then be copied to
 1915: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1916: #         course's home server.
 1917: #
 1918: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1919: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1920: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1921: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1922: #         in course's home server.
 1923: #
 1924: 
 1925: sub process_coursefile {
 1926:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1927:     my $fetchresult;
 1928:     my $home=&homeserver($docuname,$docudom);
 1929:     if ($action eq 'propagate') {
 1930:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1931: 			     $home);
 1932:     } else {
 1933:         my $fpath = '';
 1934:         my $fname = $file;
 1935:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1936:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1937:         my $filepath = &build_filepath($fpath);
 1938:         if ($action eq 'copy') {
 1939:             if ($source eq '') {
 1940:                 $fetchresult = 'no source file';
 1941:                 return $fetchresult;
 1942:             } else {
 1943:                 my $destination = $filepath.'/'.$fname;
 1944:                 rename($source,$destination);
 1945:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1946:                                  $home);
 1947:             }
 1948:         } elsif ($action eq 'uploaddoc') {
 1949:             open(my $fh,'>'.$filepath.'/'.$fname);
 1950:             print $fh $env{'form.'.$source};
 1951:             close($fh);
 1952:             if ($parser eq 'parse') {
 1953:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1954:                 unless ($parse_result eq 'ok') {
 1955:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1956:                 }
 1957:             }
 1958:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1959:                                  $home);
 1960:             if ($fetchresult eq 'ok') {
 1961:                 return '/uploaded/'.$fpath.'/'.$fname;
 1962:             } else {
 1963:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1964:                         ' to host '.$home.': '.$fetchresult);
 1965:                 return '/adm/notfound.html';
 1966:             }
 1967:         }
 1968:     }
 1969:     unless ( $fetchresult eq 'ok') {
 1970:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1971:              ' to host '.$home.': '.$fetchresult);
 1972:     }
 1973:     return $fetchresult;
 1974: }
 1975: 
 1976: sub build_filepath {
 1977:     my ($fpath) = @_;
 1978:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1979:     unless ($fpath eq '') {
 1980:         my @parts=split('/',$fpath);
 1981:         foreach my $part (@parts) {
 1982:             $filepath.= '/'.$part;
 1983:             if ((-e $filepath)!=1) {
 1984:                 mkdir($filepath,0777);
 1985:             }
 1986:         }
 1987:     }
 1988:     return $filepath;
 1989: }
 1990: 
 1991: sub store_edited_file {
 1992:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1993:     my $file = $primary_url;
 1994:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1995:     my $fpath = '';
 1996:     my $fname = $file;
 1997:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1998:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1999:     my $filepath = &build_filepath($fpath);
 2000:     open(my $fh,'>'.$filepath.'/'.$fname);
 2001:     print $fh $content;
 2002:     close($fh);
 2003:     my $home=&homeserver($docuname,$docudom);
 2004:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2005: 			  $home);
 2006:     if ($$fetchresult eq 'ok') {
 2007:         return '/uploaded/'.$fpath.'/'.$fname;
 2008:     } else {
 2009:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2010: 		 ' to host '.$home.': '.$$fetchresult);
 2011:         return '/adm/notfound.html';
 2012:     }
 2013: }
 2014: 
 2015: sub clean_filename {
 2016:     my ($fname,$args)=@_;
 2017: # Replace Windows backslashes by forward slashes
 2018:     $fname=~s/\\/\//g;
 2019:     if (!$args->{'keep_path'}) {
 2020:         # Get rid of everything but the actual filename
 2021: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2022:     }
 2023: # Replace spaces by underscores
 2024:     $fname=~s/\s+/\_/g;
 2025: # Replace all other weird characters by nothing
 2026:     $fname=~s{[^/\w\.\-]}{}g;
 2027: # Replace all .\d. sequences with _\d. so they no longer look like version
 2028: # numbers
 2029:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2030:     return $fname;
 2031: }
 2032: 
 2033: #Wrapper function for userphotoupload
 2034: sub userphotoupload
 2035: {
 2036: 	my($formname,$subdir) = @_;
 2037: 	$upload_photo_form = 1;
 2038: 	return &userfileupload($formname,undef,$subdir);
 2039: }
 2040: 
 2041: # --------------- Take an uploaded file and put it into the userfiles directory
 2042: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2043: #                    the desired filenam is in $env{"form.$formname.filename"}
 2044: #        $coursedoc - if true up to the current course
 2045: #                     if false
 2046: #        $subdir - directory in userfile to store the file into
 2047: #        $parser - instruction to parse file for objects ($parser = parse)    
 2048: #        $allfiles - reference to hash for embedded objects
 2049: #        $codebase - reference to hash for codebase of java objects
 2050: #        $desuname - username for permanent storage of uploaded file
 2051: #        $dsetudom - domain for permanaent storage of uploaded file
 2052: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2053: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2054: # 
 2055: # output: url of file in userspace, or error: <message> 
 2056: #             or /adm/notfound.html if failure to upload occurse
 2057: 
 2058: 
 2059: sub userfileupload {
 2060:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2061:         $destudom,$thumbwidth,$thumbheight)=@_;
 2062:     if (!defined($subdir)) { $subdir='unknown'; }
 2063:     my $fname=$env{'form.'.$formname.'.filename'};
 2064:     $fname=&clean_filename($fname);
 2065: # See if there is anything left
 2066:     unless ($fname) { return 'error: no uploaded file'; }
 2067:     chop($env{'form.'.$formname});
 2068:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2069:         my $now = time;
 2070:         my $filepath = 'tmp/helprequests/'.$now;
 2071:         my @parts=split(/\//,$filepath);
 2072:         my $fullpath = $perlvar{'lonDaemons'};
 2073:         for (my $i=0;$i<@parts;$i++) {
 2074:             $fullpath .= '/'.$parts[$i];
 2075:             if ((-e $fullpath)!=1) {
 2076:                 mkdir($fullpath,0777);
 2077:             }
 2078:         }
 2079:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2080:         print $fh $env{'form.'.$formname};
 2081:         close($fh);
 2082:         return $fullpath.'/'.$fname;
 2083:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2084:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2085:                        '_'.$env{'user.domain'}.'/pending';
 2086:         my @parts=split(/\//,$filepath);
 2087:         my $fullpath = $perlvar{'lonDaemons'};
 2088:         for (my $i=0;$i<@parts;$i++) {
 2089:             $fullpath .= '/'.$parts[$i];
 2090:             if ((-e $fullpath)!=1) {
 2091:                 mkdir($fullpath,0777);
 2092:             }
 2093:         }
 2094:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2095:         print $fh $env{'form.'.$formname};
 2096:         close($fh);
 2097:         return $fullpath.'/'.$fname;
 2098:     }
 2099:     
 2100: # Create the directory if not present
 2101:     $fname="$subdir/$fname";
 2102:     if ($coursedoc) {
 2103: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2104: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2105:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2106:             return &finishuserfileupload($docuname,$docudom,
 2107: 					 $formname,$fname,$parser,$allfiles,
 2108: 					 $codebase,$thumbwidth,$thumbheight);
 2109:         } else {
 2110:             $fname=$env{'form.folder'}.'/'.$fname;
 2111:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2112: 				       $fname,$formname,$parser,
 2113: 				       $allfiles,$codebase);
 2114:         }
 2115:     } elsif (defined($destuname)) {
 2116:         my $docuname=$destuname;
 2117:         my $docudom=$destudom;
 2118: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2119: 				     $parser,$allfiles,$codebase,
 2120:                                      $thumbwidth,$thumbheight);
 2121:         
 2122:     } else {
 2123:         my $docuname=$env{'user.name'};
 2124:         my $docudom=$env{'user.domain'};
 2125:         if (exists($env{'form.group'})) {
 2126:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2127:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2128:         }
 2129: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2130: 				     $parser,$allfiles,$codebase,
 2131:                                      $thumbwidth,$thumbheight);
 2132:     }
 2133: }
 2134: 
 2135: sub finishuserfileupload {
 2136:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2137:         $thumbwidth,$thumbheight) = @_;
 2138:     my $path=$docudom.'/'.$docuname.'/';
 2139:     my $filepath=$perlvar{'lonDocRoot'};
 2140:     my ($fnamepath,$file,$fetchthumb);
 2141:     $file=$fname;
 2142:     if ($fname=~m|/|) {
 2143:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2144: 	$path.=$fnamepath.'/';
 2145:     }
 2146:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2147:     my $count;
 2148:     for ($count=4;$count<=$#parts;$count++) {
 2149:         $filepath.="/$parts[$count]";
 2150:         if ((-e $filepath)!=1) {
 2151: 	    mkdir($filepath,0777);
 2152:         }
 2153:     }
 2154: # Save the file
 2155:     {
 2156: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2157: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2158: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2159: 	    return '/adm/notfound.html';
 2160: 	}
 2161: 	if (!print FH ($env{'form.'.$formname})) {
 2162: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2163: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2164: 	    return '/adm/notfound.html';
 2165: 	}
 2166: 	close(FH);
 2167: 	if($upload_photo_form==1)
 2168: 	{
 2169: 		my $ima = Image::Magick->new;                       
 2170:             	$ima->Read($filepath.'/'.$file);
 2171: 		if($ima->Get('width') > 300)
 2172: 		{
 2173: 			my $factor = $ima->Get('width')/300;
 2174:              		$ima->Scale( width=>300, height=>$ima->Get('height')/$factor );
 2175: 		}
 2176: 		if($ima->Get('height') > 400)
 2177:                 {
 2178:                         my $factor = $ima->Get('height')/400;
 2179:                         $ima->Scale( width=>$ima->Get('width')/$factor, height=>400);
 2180:                 }
 2181:  
 2182: 		
 2183: 		$ima->Write($filepath.'/'.$file);
 2184: 		$upload_photo_form = 0;
 2185: 	}
 2186:     }
 2187:     if ($parser eq 'parse') {
 2188:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2189: 						   $codebase);
 2190:         unless ($parse_result eq 'ok') {
 2191:             &logthis('Failed to parse '.$filepath.$file.
 2192: 		     ' for embedded media: '.$parse_result); 
 2193:         }
 2194:     }
 2195:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2196:         my $input = $filepath.'/'.$file;
 2197:         my $output = $filepath.'/'.'tn-'.$file;
 2198:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2199:         system("convert -sample $thumbsize $input $output");
 2200:         if (-e $filepath.'/'.'tn-'.$file) {
 2201:             $fetchthumb  = 1; 
 2202:         }
 2203:     }
 2204:  
 2205: # Notify homeserver to grep it
 2206: #
 2207:     my $docuhome=&homeserver($docuname,$docudom);
 2208:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2209:     if ($fetchresult eq 'ok') {
 2210:         if ($fetchthumb) {
 2211:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2212:             if ($thumbresult ne 'ok') {
 2213:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2214:                          $docuhome.': '.$thumbresult);
 2215:             }
 2216:         }
 2217: #
 2218: # Return the URL to it
 2219:         return '/uploaded/'.$path.$file;
 2220:     } else {
 2221:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2222: 		 ': '.$fetchresult);
 2223:         return '/adm/notfound.html';
 2224:     }
 2225: }
 2226: 
 2227: sub extract_embedded_items {
 2228:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2229:     my @state = ();
 2230:     my %javafiles = (
 2231:                       codebase => '',
 2232:                       code => '',
 2233:                       archive => ''
 2234:                     );
 2235:     my %mediafiles = (
 2236:                       src => '',
 2237:                       movie => '',
 2238:                      );
 2239:     my $p;
 2240:     if ($content) {
 2241:         $p = HTML::LCParser->new($content);
 2242:     } else {
 2243:         $p = HTML::LCParser->new($fullpath);
 2244:     }
 2245:     while (my $t=$p->get_token()) {
 2246: 	if ($t->[0] eq 'S') {
 2247: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2248: 	    push(@state, $tagname);
 2249:             if (lc($tagname) eq 'allow') {
 2250:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2251:             }
 2252: 	    if (lc($tagname) eq 'img') {
 2253: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2254: 	    }
 2255: 	    if (lc($tagname) eq 'a') {
 2256: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2257: 	    }
 2258:             if (lc($tagname) eq 'script') {
 2259:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2260:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2261:                 } else {
 2262:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2263:                 }
 2264:             }
 2265:             if (lc($tagname) eq 'link') {
 2266:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2267:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2268:                 }
 2269:             }
 2270: 	    if (lc($tagname) eq 'object' ||
 2271: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2272: 		foreach my $item (keys(%javafiles)) {
 2273: 		    $javafiles{$item} = '';
 2274: 		}
 2275: 	    }
 2276: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2277: 		my $name = lc($attr->{'name'});
 2278: 		foreach my $item (keys(%javafiles)) {
 2279: 		    if ($name eq $item) {
 2280: 			$javafiles{$item} = $attr->{'value'};
 2281: 			last;
 2282: 		    }
 2283: 		}
 2284: 		foreach my $item (keys(%mediafiles)) {
 2285: 		    if ($name eq $item) {
 2286: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2287: 			last;
 2288: 		    }
 2289: 		}
 2290: 	    }
 2291: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2292: 		foreach my $item (keys(%javafiles)) {
 2293: 		    if ($attr->{$item}) {
 2294: 			$javafiles{$item} = $attr->{$item};
 2295: 			last;
 2296: 		    }
 2297: 		}
 2298: 		foreach my $item (keys(%mediafiles)) {
 2299: 		    if ($attr->{$item}) {
 2300: 			&add_filetype($allfiles,$attr->{$item},$item);
 2301: 			last;
 2302: 		    }
 2303: 		}
 2304: 	    }
 2305: 	} elsif ($t->[0] eq 'E') {
 2306: 	    my ($tagname) = ($t->[1]);
 2307: 	    if ($javafiles{'codebase'} ne '') {
 2308: 		$javafiles{'codebase'} .= '/';
 2309: 	    }  
 2310: 	    if (lc($tagname) eq 'applet' ||
 2311: 		lc($tagname) eq 'object' ||
 2312: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2313: 		) {
 2314: 		foreach my $item (keys(%javafiles)) {
 2315: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2316: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2317: 			&add_filetype($allfiles,$file,$item);
 2318: 		    }
 2319: 		}
 2320: 	    } 
 2321: 	    pop @state;
 2322: 	}
 2323:     }
 2324:     return 'ok';
 2325: }
 2326: 
 2327: sub add_filetype {
 2328:     my ($allfiles,$file,$type)=@_;
 2329:     if (exists($allfiles->{$file})) {
 2330: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2331: 	    push(@{$allfiles->{$file}}, &escape($type));
 2332: 	}
 2333:     } else {
 2334: 	@{$allfiles->{$file}} = (&escape($type));
 2335:     }
 2336: }
 2337: 
 2338: sub removeuploadedurl {
 2339:     my ($url)=@_;
 2340:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2341:     return &removeuserfile($uname,$udom,$fname);
 2342: }
 2343: 
 2344: sub removeuserfile {
 2345:     my ($docuname,$docudom,$fname)=@_;
 2346:     my $home=&homeserver($docuname,$docudom);
 2347:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2348:     if ($result eq 'ok') {
 2349:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2350:             my $metafile = $fname.'.meta';
 2351:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2352: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2353:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2354:             my $sqlresult = 
 2355:                 &update_portfolio_table($docuname,$docudom,$file,
 2356:                                         'portfolio_metadata',$group,
 2357:                                         'delete');
 2358:         }
 2359:     }
 2360:     return $result;
 2361: }
 2362: 
 2363: sub mkdiruserfile {
 2364:     my ($docuname,$docudom,$dir)=@_;
 2365:     my $home=&homeserver($docuname,$docudom);
 2366:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2367: }
 2368: 
 2369: sub renameuserfile {
 2370:     my ($docuname,$docudom,$old,$new)=@_;
 2371:     my $home=&homeserver($docuname,$docudom);
 2372:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2373:                         &escape("$old").':'.&escape("$new"),$home);
 2374:     if ($result eq 'ok') {
 2375:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2376:             my $oldmeta = $old.'.meta';
 2377:             my $newmeta = $new.'.meta';
 2378:             my $metaresult = 
 2379:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2380: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2381:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2382:             my $sqlresult = 
 2383:                 &update_portfolio_table($docuname,$docudom,$file,
 2384:                                         'portfolio_metadata',$group,
 2385:                                         'delete');
 2386:         }
 2387:     }
 2388:     return $result;
 2389: }
 2390: 
 2391: # ------------------------------------------------------------------------- Log
 2392: 
 2393: sub log {
 2394:     my ($dom,$nam,$hom,$what)=@_;
 2395:     return critical("log:$dom:$nam:$what",$hom);
 2396: }
 2397: 
 2398: # ------------------------------------------------------------------ Course Log
 2399: #
 2400: # This routine flushes several buffers of non-mission-critical nature
 2401: #
 2402: 
 2403: sub flushcourselogs {
 2404:     &logthis('Flushing log buffers');
 2405: #
 2406: # course logs
 2407: # This is a log of all transactions in a course, which can be used
 2408: # for data mining purposes
 2409: #
 2410: # It also collects the courseid database, which lists last transaction
 2411: # times and course titles for all courseids
 2412: #
 2413:     my %courseidbuffer=();
 2414:     foreach my $crsid (keys(%courselogs)) {
 2415:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2416: 		          &escape($courselogs{$crsid}),
 2417: 		          $coursehombuf{$crsid}) eq 'ok') {
 2418: 	    delete $courselogs{$crsid};
 2419:         } else {
 2420:             &logthis('Failed to flush log buffer for '.$crsid);
 2421:             if (length($courselogs{$crsid})>40000) {
 2422:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2423:                         " exceeded maximum size, deleting.</font>");
 2424:                delete $courselogs{$crsid};
 2425:             }
 2426:         }
 2427:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2428:             'description' => $coursedescrbuf{$crsid},
 2429:             'inst_code'    => $courseinstcodebuf{$crsid},
 2430:             'type'        => $coursetypebuf{$crsid},
 2431:             'owner'       => $courseownerbuf{$crsid},
 2432:         };
 2433:     }
 2434: #
 2435: # Write course id database (reverse lookup) to homeserver of courses 
 2436: # Is used in pickcourse
 2437: #
 2438:     foreach my $crs_home (keys(%courseidbuffer)) {
 2439:         my $response = &courseidput(&host_domain($crs_home),
 2440:                                     $courseidbuffer{$crs_home},
 2441:                                     $crs_home,'timeonly');
 2442:     }
 2443: #
 2444: # File accesses
 2445: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2446: #
 2447:     foreach my $entry (keys(%accesshash)) {
 2448:         if ($entry =~ /___count$/) {
 2449:             my ($dom,$name);
 2450:             ($dom,$name,undef)=
 2451: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2452:             if (! defined($dom) || $dom eq '' || 
 2453:                 ! defined($name) || $name eq '') {
 2454:                 my $cid = $env{'request.course.id'};
 2455:                 $dom  = $env{'request.'.$cid.'.domain'};
 2456:                 $name = $env{'request.'.$cid.'.num'};
 2457:             }
 2458:             my $value = $accesshash{$entry};
 2459:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2460:             my %temphash=($url => $value);
 2461:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2462:             if ($result eq 'ok') {
 2463:                 delete $accesshash{$entry};
 2464:             } elsif ($result eq 'unknown_cmd') {
 2465:                 # Target server has old code running on it.
 2466:                 my %temphash=($entry => $value);
 2467:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2468:                     delete $accesshash{$entry};
 2469:                 }
 2470:             }
 2471:         } else {
 2472:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2473:             my %temphash=($entry => $accesshash{$entry});
 2474:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2475:                 delete $accesshash{$entry};
 2476:             }
 2477:         }
 2478:     }
 2479: #
 2480: # Roles
 2481: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2482: #
 2483:     foreach my $entry (keys(%userrolehash)) {
 2484:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2485: 	    split(/\:/,$entry);
 2486:         if (&Apache::lonnet::put('nohist_userroles',
 2487:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2488:                 $rudom,$runame) eq 'ok') {
 2489: 	    delete $userrolehash{$entry};
 2490:         }
 2491:     }
 2492: #
 2493: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2494: #
 2495:     my %domrolebuffer = ();
 2496:     foreach my $entry (keys %domainrolehash) {
 2497:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2498:         if ($domrolebuffer{$rudom}) {
 2499:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2500:                       '='.&escape($domainrolehash{$entry});
 2501:         } else {
 2502:             $domrolebuffer{$rudom}.=&escape($entry).
 2503:                       '='.&escape($domainrolehash{$entry});
 2504:         }
 2505:         delete $domainrolehash{$entry};
 2506:     }
 2507:     foreach my $dom (keys(%domrolebuffer)) {
 2508: 	my %servers = &get_servers($dom,'library');
 2509: 	foreach my $tryserver (keys(%servers)) {
 2510: 	    unless (&reply('domroleput:'.$dom.':'.
 2511: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2512: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2513: 	    }
 2514:         }
 2515:     }
 2516:     $dumpcount++;
 2517: }
 2518: 
 2519: sub courselog {
 2520:     my $what=shift;
 2521:     $what=time.':'.$what;
 2522:     unless ($env{'request.course.id'}) { return ''; }
 2523:     $coursedombuf{$env{'request.course.id'}}=
 2524:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2525:     $coursenumbuf{$env{'request.course.id'}}=
 2526:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2527:     $coursehombuf{$env{'request.course.id'}}=
 2528:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2529:     $coursedescrbuf{$env{'request.course.id'}}=
 2530:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2531:     $courseinstcodebuf{$env{'request.course.id'}}=
 2532:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2533:     $courseownerbuf{$env{'request.course.id'}}=
 2534:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2535:     $coursetypebuf{$env{'request.course.id'}}=
 2536:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2537:     if (defined $courselogs{$env{'request.course.id'}}) {
 2538: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2539:     } else {
 2540: 	$courselogs{$env{'request.course.id'}}.=$what;
 2541:     }
 2542:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2543: 	&flushcourselogs();
 2544:     }
 2545: }
 2546: 
 2547: sub courseacclog {
 2548:     my $fnsymb=shift;
 2549:     unless ($env{'request.course.id'}) { return ''; }
 2550:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2551:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2552:         $what.=':POST';
 2553:         # FIXME: Probably ought to escape things....
 2554: 	foreach my $key (keys(%env)) {
 2555:             if ($key=~/^form\.(.*)/) {
 2556:                 my $formitem = $1;
 2557:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2558:                     $what.=':'.$formitem.'='.$env{$key};
 2559:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2560:                     $what.=':'.$formitem.'='.$env{$key};
 2561:                 }
 2562:             }
 2563:         }
 2564:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2565:         # FIXME: We should not be depending on a form parameter that someone
 2566:         # editing lonsearchcat.pm might change in the future.
 2567:         if ($env{'form.phase'} eq 'course_search') {
 2568:             $what.= ':POST';
 2569:             # FIXME: Probably ought to escape things....
 2570:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2571:                                  'crsdiscuss') {
 2572:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2573:             }
 2574:         }
 2575:     }
 2576:     &courselog($what);
 2577: }
 2578: 
 2579: sub countacc {
 2580:     my $url=&declutter(shift);
 2581:     return if (! defined($url) || $url eq '');
 2582:     unless ($env{'request.course.id'}) { return ''; }
 2583:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2584:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2585:     $accesshash{$key}++;
 2586: }
 2587: 
 2588: sub linklog {
 2589:     my ($from,$to)=@_;
 2590:     $from=&declutter($from);
 2591:     $to=&declutter($to);
 2592:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2593:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2594: }
 2595:   
 2596: sub userrolelog {
 2597:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2598:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2599:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2600:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2601:         ($trole=~/^ta/)) {
 2602:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2603:        $userrolehash
 2604:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2605:                     =$tend.':'.$tstart;
 2606:     }
 2607:     if (($env{'request.role'} =~ /dc\./) &&
 2608: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2609: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2610: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2611:        $userrolehash
 2612:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2613:                     =$tend.':'.$tstart;
 2614:     }
 2615:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2616:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2617:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2618:         ($trole=~/^sc/)) {
 2619:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2620:        $domainrolehash
 2621:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2622:                     = $tend.':'.$tstart;
 2623:     }
 2624: }
 2625: 
 2626: sub courserolelog {
 2627:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2628:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2629:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2630:         ($trole eq 'ta') || ($trole eq 'st') ||
 2631:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2632:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2633:             my $cdom = $1;
 2634:             my $cnum = $2;
 2635:             my $sec = $3;
 2636:             my $namespace = 'rolelog';
 2637:             my %storehash = (
 2638:                                role    => $trole,
 2639:                                start   => $tstart,
 2640:                                end     => $tend,
 2641:                                selfenroll => $selfenroll,
 2642:                                context    => $context,
 2643:                             );
 2644:             if ($trole eq 'gr') {
 2645:                 $namespace = 'groupslog';
 2646:                 $storehash{'group'} = $sec;
 2647:             } else {
 2648:                 $storehash{'section'} = $sec;
 2649:             }
 2650:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2651:         }
 2652:     }
 2653:     return;
 2654: }
 2655: 
 2656: sub get_course_adv_roles {
 2657:     my ($cid,$codes) = @_;
 2658:     $cid=$env{'request.course.id'} unless (defined($cid));
 2659:     my %coursehash=&coursedescription($cid);
 2660:     my %nothide=();
 2661:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2662:         if ($user !~ /:/) {
 2663: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2664:         } else {
 2665:             $nothide{$user}=1;
 2666:         }
 2667:     }
 2668:     my %returnhash=();
 2669:     my %dumphash=
 2670:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2671:     my $now=time;
 2672:     foreach my $entry (keys %dumphash) {
 2673: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2674:         if (($tstart) && ($tstart<0)) { next; }
 2675:         if (($tend) && ($tend<$now)) { next; }
 2676:         if (($tstart) && ($now<$tstart)) { next; }
 2677:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2678: 	if ($username eq '' || $domain eq '') { next; }
 2679: 	if ((&privileged($username,$domain)) && 
 2680: 	    (!$nothide{$username.':'.$domain})) { next; }
 2681: 	if ($role eq 'cr') { next; }
 2682:         if ($codes) {
 2683:             if ($section) { $role .= ':'.$section; }
 2684:             if ($returnhash{$role}) {
 2685:                 $returnhash{$role}.=','.$username.':'.$domain;
 2686:             } else {
 2687:                 $returnhash{$role}=$username.':'.$domain;
 2688:             }
 2689:         } else {
 2690:             my $key=&plaintext($role);
 2691:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2692:             if ($returnhash{$key}) {
 2693: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2694:             } else {
 2695:                 $returnhash{$key}=$username.':'.$domain;
 2696:             }
 2697:         }
 2698:     }
 2699:     return %returnhash;
 2700: }
 2701: 
 2702: sub get_my_roles {
 2703:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2704:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2705:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2706:     my (%dumphash,%nothide);
 2707:     if ($context eq 'userroles') { 
 2708:         %dumphash = &dump('roles',$udom,$uname);
 2709:     } else {
 2710:         %dumphash=
 2711:             &dump('nohist_userroles',$udom,$uname);
 2712:         if ($hidepriv) {
 2713:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2714:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2715:                 if ($user !~ /:/) {
 2716:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2717:                 } else {
 2718:                     $nothide{$user} = 1;
 2719:                 }
 2720:             }
 2721:         }
 2722:     }
 2723:     my %returnhash=();
 2724:     my $now=time;
 2725:     foreach my $entry (keys(%dumphash)) {
 2726:         my ($role,$tend,$tstart);
 2727:         if ($context eq 'userroles') {
 2728: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2729:         } else {
 2730:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2731:         }
 2732:         if (($tstart) && ($tstart<0)) { next; }
 2733:         my $status = 'active';
 2734:         if (($tend) && ($tend<=$now)) {
 2735:             $status = 'previous';
 2736:         } 
 2737:         if (($tstart) && ($now<$tstart)) {
 2738:             $status = 'future';
 2739:         }
 2740:         if (ref($types) eq 'ARRAY') {
 2741:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2742:                 next;
 2743:             } 
 2744:         } else {
 2745:             if ($status ne 'active') {
 2746:                 next;
 2747:             }
 2748:         }
 2749:         my ($rolecode,$username,$domain,$section,$area);
 2750:         if ($context eq 'userroles') {
 2751:             ($area,$rolecode) = split(/_/,$entry);
 2752:             (undef,$domain,$username,$section) = split(/\//,$area);
 2753:         } else {
 2754:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2755:         }
 2756:         if (ref($roledoms) eq 'ARRAY') {
 2757:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2758:                 next;
 2759:             }
 2760:         }
 2761:         if (ref($roles) eq 'ARRAY') {
 2762:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2763:                 if ($role =~ /^cr\//) {
 2764:                     if (!grep(/^cr$/,@{$roles})) {
 2765:                         next;
 2766:                     }
 2767:                 } else {
 2768:                     next;
 2769:                 }
 2770:             }
 2771:         }
 2772:         if ($hidepriv) {
 2773:             if ((&privileged($username,$domain)) &&
 2774:                 (!$nothide{$username.':'.$domain})) { 
 2775:                 next;
 2776:             }
 2777:         }
 2778:         if ($withsec) {
 2779:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2780:                 $tstart.':'.$tend;
 2781:         } else {
 2782:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2783:         }
 2784:     }
 2785:     return %returnhash;
 2786: }
 2787: 
 2788: # ----------------------------------------------------- Frontpage Announcements
 2789: #
 2790: #
 2791: 
 2792: sub postannounce {
 2793:     my ($server,$text)=@_;
 2794:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2795:     unless ($text=~/\w/) { $text=''; }
 2796:     return &reply('setannounce:'.&escape($text),$server);
 2797: }
 2798: 
 2799: sub getannounce {
 2800: 
 2801:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2802: 	my $announcement='';
 2803: 	while (my $line = <$fh>) { $announcement .= $line; }
 2804: 	close($fh);
 2805: 	if ($announcement=~/\w/) { 
 2806: 	    return 
 2807:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2808:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2809: 	} else {
 2810: 	    return '';
 2811: 	}
 2812:     } else {
 2813: 	return '';
 2814:     }
 2815: }
 2816: 
 2817: # ---------------------------------------------------------- Course ID routines
 2818: # Deal with domain's nohist_courseid.db files
 2819: #
 2820: 
 2821: sub courseidput {
 2822:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2823:     my $outcome;
 2824:     if ($caller eq 'timeonly') {
 2825:         my $cids = '';
 2826:         foreach my $item (keys(%$storehash)) {
 2827:             $cids.=&escape($item).'&';
 2828:         }
 2829:         $cids=~s/\&$//;
 2830:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2831:                           $coursehome);       
 2832:     } else {
 2833:         my $items = '';
 2834:         foreach my $item (keys(%$storehash)) {
 2835:             $items.= &escape($item).'='.
 2836:                      &freeze_escape($$storehash{$item}).'&';
 2837:         }
 2838:         $items=~s/\&$//;
 2839:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2840:                           $coursehome);
 2841:     }
 2842:     if ($outcome eq 'unknown_cmd') {
 2843:         my $what;
 2844:         foreach my $cid (keys(%$storehash)) {
 2845:             $what .= &escape($cid).'=';
 2846:             foreach my $item ('description','inst_code','owner','type') {
 2847:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2848:             }
 2849:             $what =~ s/\:$/&/;
 2850:         }
 2851:         $what =~ s/\&$//;  
 2852:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2853:     } else {
 2854:         return $outcome;
 2855:     }
 2856: }
 2857: 
 2858: sub courseiddump {
 2859:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2860:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2861:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2862:     my $as_hash = 1;
 2863:     my %returnhash;
 2864:     if (!$domfilter) { $domfilter=''; }
 2865:     my %libserv = &all_library();
 2866:     foreach my $tryserver (keys(%libserv)) {
 2867:         if ( (  $hostidflag == 1 
 2868: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2869: 	     || (!defined($hostidflag)) ) {
 2870: 
 2871: 	    if (($domfilter eq '') ||
 2872: 		(&host_domain($tryserver) eq $domfilter)) {
 2873:                 my $rep = 
 2874:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2875:                          $sincefilter.':'.&escape($descfilter).':'.
 2876:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2877:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2878:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2879:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2880:                          $showhidden.':'.$caller,$tryserver);
 2881:                 my @pairs=split(/\&/,$rep);
 2882:                 foreach my $item (@pairs) {
 2883:                     my ($key,$value)=split(/\=/,$item,2);
 2884:                     $key = &unescape($key);
 2885:                     next if ($key =~ /^error: 2 /);
 2886:                     my $result = &thaw_unescape($value);
 2887:                     if (ref($result) eq 'HASH') {
 2888:                         $returnhash{$key}=$result;
 2889:                     } else {
 2890:                         my @responses = split(/:/,$value);
 2891:                         my @items = ('description','inst_code','owner','type');
 2892:                         for (my $i=0; $i<@responses; $i++) {
 2893:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2894:                         }
 2895:                     } 
 2896:                 }
 2897:             }
 2898:         }
 2899:     }
 2900:     return %returnhash;
 2901: }
 2902: 
 2903: # ---------------------------------------------------------- DC e-mail
 2904: 
 2905: sub dcmailput {
 2906:     my ($domain,$msgid,$message,$server)=@_;
 2907:     my $status = &Apache::lonnet::critical(
 2908:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2909:        &escape($message),$server);
 2910:     return $status;
 2911: }
 2912: 
 2913: sub dcmaildump {
 2914:     my ($dom,$startdate,$enddate,$senders) = @_;
 2915:     my %returnhash=();
 2916: 
 2917:     if (defined(&domain($dom,'primary'))) {
 2918:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2919:                                                          &escape($enddate).':';
 2920: 	my @esc_senders=map { &escape($_)} @$senders;
 2921: 	$cmd.=&escape(join('&',@esc_senders));
 2922: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2923:             my ($key,$value) = split(/\=/,$line,2);
 2924:             if (($key) && ($value)) {
 2925:                 $returnhash{&unescape($key)} = &unescape($value);
 2926:             }
 2927:         }
 2928:     }
 2929:     return %returnhash;
 2930: }
 2931: # ---------------------------------------------------------- Domain roles
 2932: 
 2933: sub get_domain_roles {
 2934:     my ($dom,$roles,$startdate,$enddate)=@_;
 2935:     if (undef($startdate) || $startdate eq '') {
 2936:         $startdate = '.';
 2937:     }
 2938:     if (undef($enddate) || $enddate eq '') {
 2939:         $enddate = '.';
 2940:     }
 2941:     my $rolelist;
 2942:     if (ref($roles) eq 'ARRAY') {
 2943:         $rolelist = join(':',@{$roles});
 2944:     }
 2945:     my %personnel = ();
 2946: 
 2947:     my %servers = &get_servers($dom,'library');
 2948:     foreach my $tryserver (keys(%servers)) {
 2949: 	%{$personnel{$tryserver}}=();
 2950: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2951: 					    &escape($startdate).':'.
 2952: 					    &escape($enddate).':'.
 2953: 					    &escape($rolelist), $tryserver))) {
 2954: 	    my ($key,$value) = split(/\=/,$line,2);
 2955: 	    if (($key) && ($value)) {
 2956: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2957: 	    }
 2958: 	}
 2959:     }
 2960:     return %personnel;
 2961: }
 2962: 
 2963: # ----------------------------------------------------------- Check out an item
 2964: 
 2965: sub get_first_access {
 2966:     my ($type,$argsymb)=@_;
 2967:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2968:     if ($argsymb) { $symb=$argsymb; }
 2969:     my ($map,$id,$res)=&decode_symb($symb);
 2970:     if ($type eq 'course') {
 2971: 	$res='course';
 2972:     } elsif ($type eq 'map') {
 2973: 	$res=&symbread($map);
 2974:     } else {
 2975: 	$res=$symb;
 2976:     }
 2977:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2978:     return $times{"$courseid\0$res"};
 2979: }
 2980: 
 2981: sub set_first_access {
 2982:     my ($type)=@_;
 2983:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2984:     my ($map,$id,$res)=&decode_symb($symb);
 2985:     if ($type eq 'course') {
 2986: 	$res='course';
 2987:     } elsif ($type eq 'map') {
 2988: 	$res=&symbread($map);
 2989:     } else {
 2990: 	$res=$symb;
 2991:     }
 2992:     my $firstaccess=&get_first_access($type,$symb);
 2993:     if (!$firstaccess) {
 2994: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2995:     }
 2996:     return 'already_set';
 2997: }
 2998: 
 2999: sub checkout {
 3000:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3001:     my $now=time;
 3002:     my $lonhost=$perlvar{'lonHostID'};
 3003:     my $infostr=&escape(
 3004:                  'CHECKOUTTOKEN&'.
 3005:                  $tuname.'&'.
 3006:                  $tudom.'&'.
 3007:                  $tcrsid.'&'.
 3008:                  $symb.'&'.
 3009: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3010:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3011:     if ($token=~/^error\:/) { 
 3012:         &logthis("<font color=\"blue\">WARNING: ".
 3013:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3014:                  "</font>");
 3015:         return ''; 
 3016:     }
 3017: 
 3018:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3019:     $token=~tr/a-z/A-Z/;
 3020: 
 3021:     my %infohash=('resource.0.outtoken' => $token,
 3022:                   'resource.0.checkouttime' => $now,
 3023:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3024: 
 3025:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3026:        return '';
 3027:     } else {
 3028:         &logthis("<font color=\"blue\">WARNING: ".
 3029:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3030:                  "</font>");
 3031:     }    
 3032: 
 3033:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3034:                          &escape('Checkout '.$infostr.' - '.
 3035:                                                  $token)) ne 'ok') {
 3036: 	return '';
 3037:     } else {
 3038:         &logthis("<font color=\"blue\">WARNING: ".
 3039:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3040:                  "</font>");
 3041:     }
 3042:     return $token;
 3043: }
 3044: 
 3045: # ------------------------------------------------------------ Check in an item
 3046: 
 3047: sub checkin {
 3048:     my $token=shift;
 3049:     my $now=time;
 3050:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3051:     $lonhost=~tr/A-Z/a-z/;
 3052:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3053:     $dtoken=~s/\W/\_/g;
 3054:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3055:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3056: 
 3057:     unless (($tuname) && ($tudom)) {
 3058:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3059:         return '';
 3060:     }
 3061:     
 3062:     unless (&allowed('mgr',$tcrsid)) {
 3063:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3064:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3065:         return '';
 3066:     }
 3067: 
 3068:     my %infohash=('resource.0.intoken' => $token,
 3069:                   'resource.0.checkintime' => $now,
 3070:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3071: 
 3072:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3073:        return '';
 3074:     }    
 3075: 
 3076:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3077:                          &escape('Checkin - '.$token)) ne 'ok') {
 3078: 	return '';
 3079:     }
 3080: 
 3081:     return ($symb,$tuname,$tudom,$tcrsid);    
 3082: }
 3083: 
 3084: # --------------------------------------------- Set Expire Date for Spreadsheet
 3085: 
 3086: sub expirespread {
 3087:     my ($uname,$udom,$stype,$usymb)=@_;
 3088:     my $cid=$env{'request.course.id'}; 
 3089:     if ($cid) {
 3090:        my $now=time;
 3091:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3092:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3093:                             $env{'course.'.$cid.'.num'}.
 3094: 	        	    ':nohist_expirationdates:'.
 3095:                             &escape($key).'='.$now,
 3096:                             $env{'course.'.$cid.'.home'})
 3097:     }
 3098:     return 'ok';
 3099: }
 3100: 
 3101: # ----------------------------------------------------- Devalidate Spreadsheets
 3102: 
 3103: sub devalidate {
 3104:     my ($symb,$uname,$udom)=@_;
 3105:     my $cid=$env{'request.course.id'}; 
 3106:     if ($cid) {
 3107:         # delete the stored spreadsheets for
 3108:         # - the student level sheet of this user in course's homespace
 3109:         # - the assessment level sheet for this resource 
 3110:         #   for this user in user's homespace
 3111: 	# - current conditional state info
 3112: 	my $key=$uname.':'.$udom.':';
 3113:         my $status=
 3114: 	    &del('nohist_calculatedsheets',
 3115: 		 [$key.'studentcalc:'],
 3116: 		 $env{'course.'.$cid.'.domain'},
 3117: 		 $env{'course.'.$cid.'.num'})
 3118: 		.' '.
 3119: 	    &del('nohist_calculatedsheets_'.$cid,
 3120: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3121:         unless ($status eq 'ok ok') {
 3122:            &logthis('Could not devalidate spreadsheet '.
 3123:                     $uname.' at '.$udom.' for '.
 3124: 		    $symb.': '.$status);
 3125:         }
 3126: 	&delenv('user.state.'.$cid);
 3127:     }
 3128: }
 3129: 
 3130: sub get_scalar {
 3131:     my ($string,$end) = @_;
 3132:     my $value;
 3133:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3134: 	$value = $1;
 3135:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3136: 	$value = $1;
 3137:     }
 3138:     return &unescape($value);
 3139: }
 3140: 
 3141: sub array2str {
 3142:   my (@array) = @_;
 3143:   my $result=&arrayref2str(\@array);
 3144:   $result=~s/^__ARRAY_REF__//;
 3145:   $result=~s/__END_ARRAY_REF__$//;
 3146:   return $result;
 3147: }
 3148: 
 3149: sub arrayref2str {
 3150:   my ($arrayref) = @_;
 3151:   my $result='__ARRAY_REF__';
 3152:   foreach my $elem (@$arrayref) {
 3153:     if(ref($elem) eq 'ARRAY') {
 3154:       $result.=&arrayref2str($elem).'&';
 3155:     } elsif(ref($elem) eq 'HASH') {
 3156:       $result.=&hashref2str($elem).'&';
 3157:     } elsif(ref($elem)) {
 3158:       #print("Got a ref of ".(ref($elem))." skipping.");
 3159:     } else {
 3160:       $result.=&escape($elem).'&';
 3161:     }
 3162:   }
 3163:   $result=~s/\&$//;
 3164:   $result .= '__END_ARRAY_REF__';
 3165:   return $result;
 3166: }
 3167: 
 3168: sub hash2str {
 3169:   my (%hash) = @_;
 3170:   my $result=&hashref2str(\%hash);
 3171:   $result=~s/^__HASH_REF__//;
 3172:   $result=~s/__END_HASH_REF__$//;
 3173:   return $result;
 3174: }
 3175: 
 3176: sub hashref2str {
 3177:   my ($hashref)=@_;
 3178:   my $result='__HASH_REF__';
 3179:   foreach my $key (sort(keys(%$hashref))) {
 3180:     if (ref($key) eq 'ARRAY') {
 3181:       $result.=&arrayref2str($key).'=';
 3182:     } elsif (ref($key) eq 'HASH') {
 3183:       $result.=&hashref2str($key).'=';
 3184:     } elsif (ref($key)) {
 3185:       $result.='=';
 3186:       #print("Got a ref of ".(ref($key))." skipping.");
 3187:     } else {
 3188: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3189:     }
 3190: 
 3191:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3192:       $result.=&arrayref2str($hashref->{$key}).'&';
 3193:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3194:       $result.=&hashref2str($hashref->{$key}).'&';
 3195:     } elsif(ref($hashref->{$key})) {
 3196:        $result.='&';
 3197:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3198:     } else {
 3199:       $result.=&escape($hashref->{$key}).'&';
 3200:     }
 3201:   }
 3202:   $result=~s/\&$//;
 3203:   $result .= '__END_HASH_REF__';
 3204:   return $result;
 3205: }
 3206: 
 3207: sub str2hash {
 3208:     my ($string)=@_;
 3209:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3210:     return %$hash;
 3211: }
 3212: 
 3213: sub str2hashref {
 3214:   my ($string) = @_;
 3215: 
 3216:   my %hash;
 3217: 
 3218:   if($string !~ /^__HASH_REF__/) {
 3219:       if (! ($string eq '' || !defined($string))) {
 3220: 	  $hash{'error'}='Not hash reference';
 3221:       }
 3222:       return (\%hash, $string);
 3223:   }
 3224: 
 3225:   $string =~ s/^__HASH_REF__//;
 3226: 
 3227:   while($string !~ /^__END_HASH_REF__/) {
 3228:       #key
 3229:       my $key='';
 3230:       if($string =~ /^__HASH_REF__/) {
 3231:           ($key, $string)=&str2hashref($string);
 3232:           if(defined($key->{'error'})) {
 3233:               $hash{'error'}='Bad data';
 3234:               return (\%hash, $string);
 3235:           }
 3236:       } elsif($string =~ /^__ARRAY_REF__/) {
 3237:           ($key, $string)=&str2arrayref($string);
 3238:           if($key->[0] eq 'Array reference error') {
 3239:               $hash{'error'}='Bad data';
 3240:               return (\%hash, $string);
 3241:           }
 3242:       } else {
 3243:           $string =~ s/^(.*?)=//;
 3244: 	  $key=&unescape($1);
 3245:       }
 3246:       $string =~ s/^=//;
 3247: 
 3248:       #value
 3249:       my $value='';
 3250:       if($string =~ /^__HASH_REF__/) {
 3251:           ($value, $string)=&str2hashref($string);
 3252:           if(defined($value->{'error'})) {
 3253:               $hash{'error'}='Bad data';
 3254:               return (\%hash, $string);
 3255:           }
 3256:       } elsif($string =~ /^__ARRAY_REF__/) {
 3257:           ($value, $string)=&str2arrayref($string);
 3258:           if($value->[0] eq 'Array reference error') {
 3259:               $hash{'error'}='Bad data';
 3260:               return (\%hash, $string);
 3261:           }
 3262:       } else {
 3263: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3264:       }
 3265:       $string =~ s/^&//;
 3266: 
 3267:       $hash{$key}=$value;
 3268:   }
 3269: 
 3270:   $string =~ s/^__END_HASH_REF__//;
 3271: 
 3272:   return (\%hash, $string);
 3273: }
 3274: 
 3275: sub str2array {
 3276:     my ($string)=@_;
 3277:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3278:     return @$array;
 3279: }
 3280: 
 3281: sub str2arrayref {
 3282:   my ($string) = @_;
 3283:   my @array;
 3284: 
 3285:   if($string !~ /^__ARRAY_REF__/) {
 3286:       if (! ($string eq '' || !defined($string))) {
 3287: 	  $array[0]='Array reference error';
 3288:       }
 3289:       return (\@array, $string);
 3290:   }
 3291: 
 3292:   $string =~ s/^__ARRAY_REF__//;
 3293: 
 3294:   while($string !~ /^__END_ARRAY_REF__/) {
 3295:       my $value='';
 3296:       if($string =~ /^__HASH_REF__/) {
 3297:           ($value, $string)=&str2hashref($string);
 3298:           if(defined($value->{'error'})) {
 3299:               $array[0] ='Array reference error';
 3300:               return (\@array, $string);
 3301:           }
 3302:       } elsif($string =~ /^__ARRAY_REF__/) {
 3303:           ($value, $string)=&str2arrayref($string);
 3304:           if($value->[0] eq 'Array reference error') {
 3305:               $array[0] ='Array reference error';
 3306:               return (\@array, $string);
 3307:           }
 3308:       } else {
 3309: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3310:       }
 3311:       $string =~ s/^&//;
 3312: 
 3313:       push(@array, $value);
 3314:   }
 3315: 
 3316:   $string =~ s/^__END_ARRAY_REF__//;
 3317: 
 3318:   return (\@array, $string);
 3319: }
 3320: 
 3321: # -------------------------------------------------------------------Temp Store
 3322: 
 3323: sub tmpreset {
 3324:   my ($symb,$namespace,$domain,$stuname) = @_;
 3325:   if (!$symb) {
 3326:     $symb=&symbread();
 3327:     if (!$symb) { $symb= $env{'request.url'}; }
 3328:   }
 3329:   $symb=escape($symb);
 3330: 
 3331:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3332:   $namespace=~s/\//\_/g;
 3333:   $namespace=~s/\W//g;
 3334: 
 3335:   if (!$domain) { $domain=$env{'user.domain'}; }
 3336:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3337:   if ($domain eq 'public' && $stuname eq 'public') {
 3338:       $stuname=$ENV{'REMOTE_ADDR'};
 3339:   }
 3340:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3341:   my %hash;
 3342:   if (tie(%hash,'GDBM_File',
 3343: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3344: 	  &GDBM_WRCREAT(),0640)) {
 3345:     foreach my $key (keys %hash) {
 3346:       if ($key=~ /:$symb/) {
 3347: 	delete($hash{$key});
 3348:       }
 3349:     }
 3350:   }
 3351: }
 3352: 
 3353: sub tmpstore {
 3354:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3355: 
 3356:   if (!$symb) {
 3357:     $symb=&symbread();
 3358:     if (!$symb) { $symb= $env{'request.url'}; }
 3359:   }
 3360:   $symb=escape($symb);
 3361: 
 3362:   if (!$namespace) {
 3363:     # I don't think we would ever want to store this for a course.
 3364:     # it seems this will only be used if we don't have a course.
 3365:     #$namespace=$env{'request.course.id'};
 3366:     #if (!$namespace) {
 3367:       $namespace=$env{'request.state'};
 3368:     #}
 3369:   }
 3370:   $namespace=~s/\//\_/g;
 3371:   $namespace=~s/\W//g;
 3372:   if (!$domain) { $domain=$env{'user.domain'}; }
 3373:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3374:   if ($domain eq 'public' && $stuname eq 'public') {
 3375:       $stuname=$ENV{'REMOTE_ADDR'};
 3376:   }
 3377:   my $now=time;
 3378:   my %hash;
 3379:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3380:   if (tie(%hash,'GDBM_File',
 3381: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3382: 	  &GDBM_WRCREAT(),0640)) {
 3383:     $hash{"version:$symb"}++;
 3384:     my $version=$hash{"version:$symb"};
 3385:     my $allkeys=''; 
 3386:     foreach my $key (keys(%$storehash)) {
 3387:       $allkeys.=$key.':';
 3388:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3389:     }
 3390:     $hash{"$version:$symb:timestamp"}=$now;
 3391:     $allkeys.='timestamp';
 3392:     $hash{"$version:keys:$symb"}=$allkeys;
 3393:     if (untie(%hash)) {
 3394:       return 'ok';
 3395:     } else {
 3396:       return "error:$!";
 3397:     }
 3398:   } else {
 3399:     return "error:$!";
 3400:   }
 3401: }
 3402: 
 3403: # -----------------------------------------------------------------Temp Restore
 3404: 
 3405: sub tmprestore {
 3406:   my ($symb,$namespace,$domain,$stuname) = @_;
 3407: 
 3408:   if (!$symb) {
 3409:     $symb=&symbread();
 3410:     if (!$symb) { $symb= $env{'request.url'}; }
 3411:   }
 3412:   $symb=escape($symb);
 3413: 
 3414:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3415: 
 3416:   if (!$domain) { $domain=$env{'user.domain'}; }
 3417:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3418:   if ($domain eq 'public' && $stuname eq 'public') {
 3419:       $stuname=$ENV{'REMOTE_ADDR'};
 3420:   }
 3421:   my %returnhash;
 3422:   $namespace=~s/\//\_/g;
 3423:   $namespace=~s/\W//g;
 3424:   my %hash;
 3425:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3426:   if (tie(%hash,'GDBM_File',
 3427: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3428: 	  &GDBM_READER(),0640)) {
 3429:     my $version=$hash{"version:$symb"};
 3430:     $returnhash{'version'}=$version;
 3431:     my $scope;
 3432:     for ($scope=1;$scope<=$version;$scope++) {
 3433:       my $vkeys=$hash{"$scope:keys:$symb"};
 3434:       my @keys=split(/:/,$vkeys);
 3435:       my $key;
 3436:       $returnhash{"$scope:keys"}=$vkeys;
 3437:       foreach $key (@keys) {
 3438: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3439: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3440:       }
 3441:     }
 3442:     if (!(untie(%hash))) {
 3443:       return "error:$!";
 3444:     }
 3445:   } else {
 3446:     return "error:$!";
 3447:   }
 3448:   return %returnhash;
 3449: }
 3450: 
 3451: # ----------------------------------------------------------------------- Store
 3452: 
 3453: sub store {
 3454:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3455:     my $home='';
 3456: 
 3457:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3458: 
 3459:     $symb=&symbclean($symb);
 3460:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3461: 
 3462:     if (!$domain) { $domain=$env{'user.domain'}; }
 3463:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3464: 
 3465:     &devalidate($symb,$stuname,$domain);
 3466: 
 3467:     $symb=escape($symb);
 3468:     if (!$namespace) { 
 3469:        unless ($namespace=$env{'request.course.id'}) { 
 3470:           return ''; 
 3471:        } 
 3472:     }
 3473:     if (!$home) { $home=$env{'user.home'}; }
 3474: 
 3475:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3476:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3477: 
 3478:     my $namevalue='';
 3479:     foreach my $key (keys(%$storehash)) {
 3480:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3481:     }
 3482:     $namevalue=~s/\&$//;
 3483:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3484:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3485: }
 3486: 
 3487: # -------------------------------------------------------------- Critical Store
 3488: 
 3489: sub cstore {
 3490:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3491:     my $home='';
 3492: 
 3493:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3494: 
 3495:     $symb=&symbclean($symb);
 3496:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3497: 
 3498:     if (!$domain) { $domain=$env{'user.domain'}; }
 3499:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3500: 
 3501:     &devalidate($symb,$stuname,$domain);
 3502: 
 3503:     $symb=escape($symb);
 3504:     if (!$namespace) { 
 3505:        unless ($namespace=$env{'request.course.id'}) { 
 3506:           return ''; 
 3507:        } 
 3508:     }
 3509:     if (!$home) { $home=$env{'user.home'}; }
 3510: 
 3511:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3512:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3513: 
 3514:     my $namevalue='';
 3515:     foreach my $key (keys(%$storehash)) {
 3516:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3517:     }
 3518:     $namevalue=~s/\&$//;
 3519:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3520:     return critical
 3521:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3522: }
 3523: 
 3524: # --------------------------------------------------------------------- Restore
 3525: 
 3526: sub restore {
 3527:     my ($symb,$namespace,$domain,$stuname) = @_;
 3528:     my $home='';
 3529: 
 3530:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3531: 
 3532:     if (!$symb) {
 3533:       unless ($symb=escape(&symbread())) { return ''; }
 3534:     } else {
 3535:       $symb=&escape(&symbclean($symb));
 3536:     }
 3537:     if (!$namespace) { 
 3538:        unless ($namespace=$env{'request.course.id'}) { 
 3539:           return ''; 
 3540:        } 
 3541:     }
 3542:     if (!$domain) { $domain=$env{'user.domain'}; }
 3543:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3544:     if (!$home) { $home=$env{'user.home'}; }
 3545:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3546: 
 3547:     my %returnhash=();
 3548:     foreach my $line (split(/\&/,$answer)) {
 3549: 	my ($name,$value)=split(/\=/,$line);
 3550:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3551:     }
 3552:     my $version;
 3553:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3554:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3555:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3556:        }
 3557:     }
 3558:     return %returnhash;
 3559: }
 3560: 
 3561: # ---------------------------------------------------------- Course Description
 3562: 
 3563: sub coursedescription {
 3564:     my ($courseid,$args)=@_;
 3565:     $courseid=~s/^\///;
 3566:     $courseid=~s/\_/\//g;
 3567:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3568:     my $chome=&homeserver($cnum,$cdomain);
 3569:     my $normalid=$cdomain.'_'.$cnum;
 3570:     # need to always cache even if we get errors otherwise we keep 
 3571:     # trying and trying and trying to get the course description.
 3572:     my %envhash=();
 3573:     my %returnhash=();
 3574:     
 3575:     my $expiretime=600;
 3576:     if ($env{'request.course.id'} eq $normalid) {
 3577: 	$expiretime=120;
 3578:     }
 3579: 
 3580:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3581:     if (!$args->{'freshen_cache'}
 3582: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3583: 	foreach my $key (keys(%env)) {
 3584: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3585: 	    my ($setting) = $1;
 3586: 	    $returnhash{$setting} = $env{$key};
 3587: 	}
 3588: 	return %returnhash;
 3589:     }
 3590: 
 3591:     # get the data agin
 3592:     if (!$args->{'one_time'}) {
 3593: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3594:     }
 3595: 
 3596:     if ($chome ne 'no_host') {
 3597:        %returnhash=&dump('environment',$cdomain,$cnum);
 3598:        if (!exists($returnhash{'con_lost'})) {
 3599:            $returnhash{'home'}= $chome;
 3600: 	   $returnhash{'domain'} = $cdomain;
 3601: 	   $returnhash{'num'} = $cnum;
 3602:            if (!defined($returnhash{'type'})) {
 3603:                $returnhash{'type'} = 'Course';
 3604:            }
 3605:            while (my ($name,$value) = each %returnhash) {
 3606:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3607:            }
 3608:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3609:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3610: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3611:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3612:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3613:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3614:        }
 3615:     }
 3616:     if (!$args->{'one_time'}) {
 3617: 	&appenv(\%envhash);
 3618:     }
 3619:     return %returnhash;
 3620: }
 3621: 
 3622: # -------------------------------------------------See if a user is privileged
 3623: 
 3624: sub privileged {
 3625:     my ($username,$domain)=@_;
 3626:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3627: 			&homeserver($username,$domain));
 3628:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3629:     my $now=time;
 3630:     if ($rolesdump ne '') {
 3631:         foreach my $entry (split(/&/,$rolesdump)) {
 3632: 	    if ($entry!~/^rolesdef_/) {
 3633: 		my ($area,$role)=split(/=/,$entry);
 3634: 		$area=~s/\_\w\w$//;
 3635: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3636: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3637: 		    my $active=1;
 3638: 		    if ($tend) {
 3639: 			if ($tend<$now) { $active=0; }
 3640: 		    }
 3641: 		    if ($tstart) {
 3642: 			if ($tstart>$now) { $active=0; }
 3643: 		    }
 3644: 		    if ($active) { return 1; }
 3645: 		}
 3646: 	    }
 3647: 	}
 3648:     }
 3649:     return 0;
 3650: }
 3651: 
 3652: # -------------------------------------------------------- Get user privileges
 3653: 
 3654: sub rolesinit {
 3655:     my ($domain,$username,$authhost)=@_;
 3656:     my %userroles;
 3657:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3658:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3659:     my %allroles=();
 3660:     my %allgroups=();   
 3661:     my $now=time;
 3662:     %userroles = ('user.login.time' => $now);
 3663:     my $group_privs;
 3664: 
 3665:     if ($rolesdump ne '') {
 3666:         foreach my $entry (split(/&/,$rolesdump)) {
 3667: 	  if ($entry!~/^rolesdef_/) {
 3668:             my ($area,$role)=split(/=/,$entry);
 3669: 	    $area=~s/\_\w\w$//;
 3670:             my ($trole,$tend,$tstart,$group_privs);
 3671: 	    if ($role=~/^cr/) { 
 3672: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3673: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3674: 		    ($tend,$tstart)=split('_',$trest);
 3675: 		} else {
 3676: 		    $trole=$role;
 3677: 		}
 3678:             } elsif ($role =~ m|^gr/|) {
 3679:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3680:                 ($trole,$group_privs) = split(/\//,$trole);
 3681:                 $group_privs = &unescape($group_privs);
 3682: 	    } else {
 3683: 		($trole,$tend,$tstart)=split(/_/,$role);
 3684: 	    }
 3685: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3686: 					 $username);
 3687: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3688:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3689:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3690:             if (($area ne '') && ($trole ne '')) {
 3691: 		my $spec=$trole.'.'.$area;
 3692: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3693: 		if ($trole =~ /^cr\//) {
 3694:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3695:                 } elsif ($trole eq 'gr') {
 3696:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3697: 		} else {
 3698:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3699: 		}
 3700:             }
 3701:           }
 3702:         }
 3703:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3704:         $userroles{'user.adv'}    = $adv;
 3705: 	$userroles{'user.author'} = $author;
 3706:         $env{'user.adv'}=$adv;
 3707:     }
 3708:     return \%userroles;  
 3709: }
 3710: 
 3711: sub set_arearole {
 3712:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3713: # log the associated role with the area
 3714:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3715:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3716: }
 3717: 
 3718: sub custom_roleprivs {
 3719:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3720:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3721:     my $homsvr=homeserver($rauthor,$rdomain);
 3722:     if (&hostname($homsvr) ne '') {
 3723:         my ($rdummy,$roledef)=
 3724:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3725:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3726:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3727:             if (defined($syspriv)) {
 3728:                 $$allroles{'cm./'}.=':'.$syspriv;
 3729:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3730:             }
 3731:             if ($tdomain ne '') {
 3732:                 if (defined($dompriv)) {
 3733:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3734:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3735:                 }
 3736:                 if (($trest ne '') && (defined($coursepriv))) {
 3737:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3738:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3739:                 }
 3740:             }
 3741:         }
 3742:     }
 3743: }
 3744: 
 3745: sub group_roleprivs {
 3746:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3747:     my $access = 1;
 3748:     my $now = time;
 3749:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3750:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3751:     if ($access) {
 3752:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3753:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3754:     }
 3755: }
 3756: 
 3757: sub standard_roleprivs {
 3758:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3759:     if (defined($pr{$trole.':s'})) {
 3760:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3761:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3762:     }
 3763:     if ($tdomain ne '') {
 3764:         if (defined($pr{$trole.':d'})) {
 3765:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3766:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3767:         }
 3768:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3769:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3770:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3771:         }
 3772:     }
 3773: }
 3774: 
 3775: sub set_userprivs {
 3776:     my ($userroles,$allroles,$allgroups) = @_; 
 3777:     my $author=0;
 3778:     my $adv=0;
 3779:     my %grouproles = ();
 3780:     if (keys(%{$allgroups}) > 0) {
 3781:         foreach my $role (keys %{$allroles}) {
 3782:             my ($trole,$area,$sec,$extendedarea);
 3783:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3784:                 $trole = $1;
 3785:                 $area = $2;
 3786:                 $sec = $3;
 3787:                 $extendedarea = $area.$sec;
 3788:                 if (exists($$allgroups{$area})) {
 3789:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3790:                         my $spec = $trole.'.'.$extendedarea;
 3791:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3792:                                                 $$allgroups{$area}{$group};
 3793:                     }
 3794:                 }
 3795:             }
 3796:         }
 3797:     }
 3798:     foreach my $group (keys(%grouproles)) {
 3799:         $$allroles{$group} = $grouproles{$group};
 3800:     }
 3801:     foreach my $role (keys(%{$allroles})) {
 3802:         my %thesepriv;
 3803:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3804:         foreach my $item (split(/:/,$$allroles{$role})) {
 3805:             if ($item ne '') {
 3806:                 my ($privilege,$restrictions)=split(/&/,$item);
 3807:                 if ($restrictions eq '') {
 3808:                     $thesepriv{$privilege}='F';
 3809:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3810:                     $thesepriv{$privilege}.=$restrictions;
 3811:                 }
 3812:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3813:             }
 3814:         }
 3815:         my $thesestr='';
 3816:         foreach my $priv (keys(%thesepriv)) {
 3817: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3818: 	}
 3819:         $userroles->{'user.priv.'.$role} = $thesestr;
 3820:     }
 3821:     return ($author,$adv);
 3822: }
 3823: 
 3824: # --------------------------------------------------------------- get interface
 3825: 
 3826: sub get {
 3827:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3828:    my $items='';
 3829:    foreach my $item (@$storearr) {
 3830:        $items.=&escape($item).'&';
 3831:    }
 3832:    $items=~s/\&$//;
 3833:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3834:    if (!$uname) { $uname=$env{'user.name'}; }
 3835:    my $uhome=&homeserver($uname,$udomain);
 3836: 
 3837:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3838:    my @pairs=split(/\&/,$rep);
 3839:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3840:      return @pairs;
 3841:    }
 3842:    my %returnhash=();
 3843:    my $i=0;
 3844:    foreach my $item (@$storearr) {
 3845:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3846:       $i++;
 3847:    }
 3848:    return %returnhash;
 3849: }
 3850: 
 3851: # --------------------------------------------------------------- del interface
 3852: 
 3853: sub del {
 3854:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3855:    my $items='';
 3856:    foreach my $item (@$storearr) {
 3857:        $items.=&escape($item).'&';
 3858:    }
 3859:    $items=~s/\&$//;
 3860:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3861:    if (!$uname) { $uname=$env{'user.name'}; }
 3862:    my $uhome=&homeserver($uname,$udomain);
 3863: 
 3864:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3865: }
 3866: 
 3867: # -------------------------------------------------------------- dump interface
 3868: 
 3869: sub dump {
 3870:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3871:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3872:     if (!$uname) { $uname=$env{'user.name'}; }
 3873:     my $uhome=&homeserver($uname,$udomain);
 3874:     if ($regexp) {
 3875: 	$regexp=&escape($regexp);
 3876:     } else {
 3877: 	$regexp='.';
 3878:     }
 3879:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3880:     my @pairs=split(/\&/,$rep);
 3881:     my %returnhash=();
 3882:     foreach my $item (@pairs) {
 3883: 	my ($key,$value)=split(/=/,$item,2);
 3884: 	$key = &unescape($key);
 3885: 	next if ($key =~ /^error: 2 /);
 3886: 	$returnhash{$key}=&thaw_unescape($value);
 3887:     }
 3888:     return %returnhash;
 3889: }
 3890: 
 3891: # --------------------------------------------------------- dumpstore interface
 3892: 
 3893: sub dumpstore {
 3894:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3896:    if (!$uname) { $uname=$env{'user.name'}; }
 3897:    my $uhome=&homeserver($uname,$udomain);
 3898:    if ($regexp) {
 3899:        $regexp=&escape($regexp);
 3900:    } else {
 3901:        $regexp='.';
 3902:    }
 3903:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3904:    my @pairs=split(/\&/,$rep);
 3905:    my %returnhash=();
 3906:    foreach my $item (@pairs) {
 3907:        my ($key,$value)=split(/=/,$item,2);
 3908:        next if ($key =~ /^error: 2 /);
 3909:        $returnhash{$key}=&thaw_unescape($value);
 3910:    }
 3911:    return %returnhash;
 3912: }
 3913: 
 3914: # -------------------------------------------------------------- keys interface
 3915: 
 3916: sub getkeys {
 3917:    my ($namespace,$udomain,$uname)=@_;
 3918:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3919:    if (!$uname) { $uname=$env{'user.name'}; }
 3920:    my $uhome=&homeserver($uname,$udomain);
 3921:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3922:    my @keyarray=();
 3923:    foreach my $key (split(/\&/,$rep)) {
 3924:       next if ($key =~ /^error: 2 /);
 3925:       push(@keyarray,&unescape($key));
 3926:    }
 3927:    return @keyarray;
 3928: }
 3929: 
 3930: # --------------------------------------------------------------- currentdump
 3931: sub currentdump {
 3932:    my ($courseid,$sdom,$sname)=@_;
 3933:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3934:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3935:    $sname    = $env{'user.name'}         if (! defined($sname));
 3936:    my $uhome = &homeserver($sname,$sdom);
 3937:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3938:    return if ($rep =~ /^(error:|no_such_host)/);
 3939:    #
 3940:    my %returnhash=();
 3941:    #
 3942:    if ($rep eq "unknown_cmd") { 
 3943:        # an old lond will not know currentdump
 3944:        # Do a dump and make it look like a currentdump
 3945:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3946:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3947:        my %hash = @tmp;
 3948:        @tmp=();
 3949:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3950:    } else {
 3951:        my @pairs=split(/\&/,$rep);
 3952:        foreach my $pair (@pairs) {
 3953:            my ($key,$value)=split(/=/,$pair,2);
 3954:            my ($symb,$param) = split(/:/,$key);
 3955:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3956:                                                         &thaw_unescape($value);
 3957:        }
 3958:    }
 3959:    return %returnhash;
 3960: }
 3961: 
 3962: sub convert_dump_to_currentdump{
 3963:     my %hash = %{shift()};
 3964:     my %returnhash;
 3965:     # Code ripped from lond, essentially.  The only difference
 3966:     # here is the unescaping done by lonnet::dump().  Conceivably
 3967:     # we might run in to problems with parameter names =~ /^v\./
 3968:     while (my ($key,$value) = each(%hash)) {
 3969:         my ($v,$symb,$param) = split(/:/,$key);
 3970: 	$symb  = &unescape($symb);
 3971: 	$param = &unescape($param);
 3972:         next if ($v eq 'version' || $symb eq 'keys');
 3973:         next if (exists($returnhash{$symb}) &&
 3974:                  exists($returnhash{$symb}->{$param}) &&
 3975:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3976:         $returnhash{$symb}->{$param}=$value;
 3977:         $returnhash{$symb}->{'v.'.$param}=$v;
 3978:     }
 3979:     #
 3980:     # Remove all of the keys in the hashes which keep track of
 3981:     # the version of the parameter.
 3982:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3983:         # use a foreach because we are going to delete from the hash.
 3984:         foreach my $key (keys(%$param_hash)) {
 3985:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3986:         }
 3987:     }
 3988:     return \%returnhash;
 3989: }
 3990: 
 3991: # ------------------------------------------------------ critical inc interface
 3992: 
 3993: sub cinc {
 3994:     return &inc(@_,'critical');
 3995: }
 3996: 
 3997: # --------------------------------------------------------------- inc interface
 3998: 
 3999: sub inc {
 4000:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4001:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4002:     if (!$uname) { $uname=$env{'user.name'}; }
 4003:     my $uhome=&homeserver($uname,$udomain);
 4004:     my $items='';
 4005:     if (! ref($store)) {
 4006:         # got a single value, so use that instead
 4007:         $items = &escape($store).'=&';
 4008:     } elsif (ref($store) eq 'SCALAR') {
 4009:         $items = &escape($$store).'=&';        
 4010:     } elsif (ref($store) eq 'ARRAY') {
 4011:         $items = join('=&',map {&escape($_);} @{$store});
 4012:     } elsif (ref($store) eq 'HASH') {
 4013:         while (my($key,$value) = each(%{$store})) {
 4014:             $items.= &escape($key).'='.&escape($value).'&';
 4015:         }
 4016:     }
 4017:     $items=~s/\&$//;
 4018:     if ($critical) {
 4019: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4020:     } else {
 4021: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4022:     }
 4023: }
 4024: 
 4025: # --------------------------------------------------------------- put interface
 4026: 
 4027: sub put {
 4028:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4029:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4030:    if (!$uname) { $uname=$env{'user.name'}; }
 4031:    my $uhome=&homeserver($uname,$udomain);
 4032:    my $items='';
 4033:    foreach my $item (keys(%$storehash)) {
 4034:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4035:    }
 4036:    $items=~s/\&$//;
 4037:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4038: }
 4039: 
 4040: # ------------------------------------------------------------ newput interface
 4041: 
 4042: sub newput {
 4043:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4044:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4045:    if (!$uname) { $uname=$env{'user.name'}; }
 4046:    my $uhome=&homeserver($uname,$udomain);
 4047:    my $items='';
 4048:    foreach my $key (keys(%$storehash)) {
 4049:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4050:    }
 4051:    $items=~s/\&$//;
 4052:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4053: }
 4054: 
 4055: # ---------------------------------------------------------  putstore interface
 4056: 
 4057: sub putstore {
 4058:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4059:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4060:    if (!$uname) { $uname=$env{'user.name'}; }
 4061:    my $uhome=&homeserver($uname,$udomain);
 4062:    my $items='';
 4063:    foreach my $key (keys(%$storehash)) {
 4064:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4065:    }
 4066:    $items=~s/\&$//;
 4067:    my $esc_symb=&escape($symb);
 4068:    my $esc_v=&escape($version);
 4069:    my $reply =
 4070:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4071: 	      $uhome);
 4072:    if ($reply eq 'unknown_cmd') {
 4073:        # gfall back to way things use to be done
 4074:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4075: 			    $uname);
 4076:    }
 4077:    return $reply;
 4078: }
 4079: 
 4080: sub old_putstore {
 4081:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4082:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4083:     if (!$uname) { $uname=$env{'user.name'}; }
 4084:     my $uhome=&homeserver($uname,$udomain);
 4085:     my %newstorehash;
 4086:     foreach my $item (keys(%$storehash)) {
 4087: 	my $key = $version.':'.&escape($symb).':'.$item;
 4088: 	$newstorehash{$key} = $storehash->{$item};
 4089:     }
 4090:     my $items='';
 4091:     my %allitems = ();
 4092:     foreach my $item (keys(%newstorehash)) {
 4093: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4094: 	    my $key = $1.':keys:'.$2;
 4095: 	    $allitems{$key} .= $3.':';
 4096: 	}
 4097: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4098:     }
 4099:     foreach my $item (keys(%allitems)) {
 4100: 	$allitems{$item} =~ s/\:$//;
 4101: 	$items.= $item.'='.$allitems{$item}.'&';
 4102:     }
 4103:     $items=~s/\&$//;
 4104:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4105: }
 4106: 
 4107: # ------------------------------------------------------ critical put interface
 4108: 
 4109: sub cput {
 4110:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4111:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4112:    if (!$uname) { $uname=$env{'user.name'}; }
 4113:    my $uhome=&homeserver($uname,$udomain);
 4114:    my $items='';
 4115:    foreach my $item (keys(%$storehash)) {
 4116:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4117:    }
 4118:    $items=~s/\&$//;
 4119:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4120: }
 4121: 
 4122: # -------------------------------------------------------------- eget interface
 4123: 
 4124: sub eget {
 4125:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4126:    my $items='';
 4127:    foreach my $item (@$storearr) {
 4128:        $items.=&escape($item).'&';
 4129:    }
 4130:    $items=~s/\&$//;
 4131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4132:    if (!$uname) { $uname=$env{'user.name'}; }
 4133:    my $uhome=&homeserver($uname,$udomain);
 4134:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4135:    my @pairs=split(/\&/,$rep);
 4136:    my %returnhash=();
 4137:    my $i=0;
 4138:    foreach my $item (@$storearr) {
 4139:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4140:       $i++;
 4141:    }
 4142:    return %returnhash;
 4143: }
 4144: 
 4145: # ------------------------------------------------------------ tmpput interface
 4146: sub tmpput {
 4147:     my ($storehash,$server,$context)=@_;
 4148:     my $items='';
 4149:     foreach my $item (keys(%$storehash)) {
 4150: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4151:     }
 4152:     $items=~s/\&$//;
 4153:     if (defined($context)) {
 4154:         $items .= ':'.&escape($context);
 4155:     }
 4156:     return &reply("tmpput:$items",$server);
 4157: }
 4158: 
 4159: # ------------------------------------------------------------ tmpget interface
 4160: sub tmpget {
 4161:     my ($token,$server)=@_;
 4162:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4163:     my $rep=&reply("tmpget:$token",$server);
 4164:     my %returnhash;
 4165:     foreach my $item (split(/\&/,$rep)) {
 4166: 	my ($key,$value)=split(/=/,$item);
 4167:         next if ($key =~ /^error: 2 /);
 4168: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4169:     }
 4170:     return %returnhash;
 4171: }
 4172: 
 4173: # ------------------------------------------------------------ tmpget interface
 4174: sub tmpdel {
 4175:     my ($token,$server)=@_;
 4176:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4177:     return &reply("tmpdel:$token",$server);
 4178: }
 4179: 
 4180: # -------------------------------------------------- portfolio access checking
 4181: 
 4182: sub portfolio_access {
 4183:     my ($requrl) = @_;
 4184:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4185:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4186:     if ($result) {
 4187:         my %setters;
 4188:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4189:             my ($startblock,$endblock) =
 4190:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4191:             if ($startblock && $endblock) {
 4192:                 return 'B';
 4193:             }
 4194:         } else {
 4195:             my ($startblock,$endblock) =
 4196:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4197:             if ($startblock && $endblock) {
 4198:                 return 'B';
 4199:             }
 4200:         }
 4201:     }
 4202:     if ($result eq 'ok') {
 4203:        return 'F';
 4204:     } elsif ($result =~ /^[^:]+:guest_/) {
 4205:        return 'A';
 4206:     }
 4207:     return '';
 4208: }
 4209: 
 4210: sub get_portfolio_access {
 4211:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4212: 
 4213:     if (!ref($access_hash)) {
 4214: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4215: 	my %access_controls = &get_access_controls($current_perms,$group,
 4216: 						   $file_name);
 4217: 	$access_hash = $access_controls{$file_name};
 4218:     }
 4219: 
 4220:     my ($public,$guest,@domains,@users,@courses,@groups);
 4221:     my $now = time;
 4222:     if (ref($access_hash) eq 'HASH') {
 4223:         foreach my $key (keys(%{$access_hash})) {
 4224:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4225:             if ($start > $now) {
 4226:                 next;
 4227:             }
 4228:             if ($end && $end<$now) {
 4229:                 next;
 4230:             }
 4231:             if ($scope eq 'public') {
 4232:                 $public = $key;
 4233:                 last;
 4234:             } elsif ($scope eq 'guest') {
 4235:                 $guest = $key;
 4236:             } elsif ($scope eq 'domains') {
 4237:                 push(@domains,$key);
 4238:             } elsif ($scope eq 'users') {
 4239:                 push(@users,$key);
 4240:             } elsif ($scope eq 'course') {
 4241:                 push(@courses,$key);
 4242:             } elsif ($scope eq 'group') {
 4243:                 push(@groups,$key);
 4244:             }
 4245:         }
 4246:         if ($public) {
 4247:             return 'ok';
 4248:         }
 4249:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4250:             if ($guest) {
 4251:                 return $guest;
 4252:             }
 4253:         } else {
 4254:             if (@domains > 0) {
 4255:                 foreach my $domkey (@domains) {
 4256:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4257:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4258:                             return 'ok';
 4259:                         }
 4260:                     }
 4261:                 }
 4262:             }
 4263:             if (@users > 0) {
 4264:                 foreach my $userkey (@users) {
 4265:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4266:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4267:                             if (ref($item) eq 'HASH') {
 4268:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4269:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4270:                                     return 'ok';
 4271:                                 }
 4272:                             }
 4273:                         }
 4274:                     } 
 4275:                 }
 4276:             }
 4277:             my %roleshash;
 4278:             my @courses_and_groups = @courses;
 4279:             push(@courses_and_groups,@groups); 
 4280:             if (@courses_and_groups > 0) {
 4281:                 my (%allgroups,%allroles); 
 4282:                 my ($start,$end,$role,$sec,$group);
 4283:                 foreach my $envkey (%env) {
 4284:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4285:                         my $cid = $2.'_'.$3; 
 4286:                         if ($1 eq 'gr') {
 4287:                             $group = $4;
 4288:                             $allgroups{$cid}{$group} = $env{$envkey};
 4289:                         } else {
 4290:                             if ($4 eq '') {
 4291:                                 $sec = 'none';
 4292:                             } else {
 4293:                                 $sec = $4;
 4294:                             }
 4295:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4296:                         }
 4297:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4298:                         my $cid = $2.'_'.$3;
 4299:                         if ($4 eq '') {
 4300:                             $sec = 'none';
 4301:                         } else {
 4302:                             $sec = $4;
 4303:                         }
 4304:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4305:                     }
 4306:                 }
 4307:                 if (keys(%allroles) == 0) {
 4308:                     return;
 4309:                 }
 4310:                 foreach my $key (@courses_and_groups) {
 4311:                     my %content = %{$$access_hash{$key}};
 4312:                     my $cnum = $content{'number'};
 4313:                     my $cdom = $content{'domain'};
 4314:                     my $cid = $cdom.'_'.$cnum;
 4315:                     if (!exists($allroles{$cid})) {
 4316:                         next;
 4317:                     }    
 4318:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4319:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4320:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4321:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4322:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4323:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4324:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4325:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4326:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4327:                                         if (grep/^all$/,@sections) {
 4328:                                             return 'ok';
 4329:                                         } else {
 4330:                                             if (grep/^$sec$/,@sections) {
 4331:                                                 return 'ok';
 4332:                                             }
 4333:                                         }
 4334:                                     }
 4335:                                 }
 4336:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4337:                                     if (grep/^none$/,@groups) {
 4338:                                         return 'ok';
 4339:                                     }
 4340:                                 } else {
 4341:                                     if (grep/^all$/,@groups) {
 4342:                                         return 'ok';
 4343:                                     } 
 4344:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4345:                                         if (grep/^$group$/,@groups) {
 4346:                                             return 'ok';
 4347:                                         }
 4348:                                     }
 4349:                                 } 
 4350:                             }
 4351:                         }
 4352:                     }
 4353:                 }
 4354:             }
 4355:             if ($guest) {
 4356:                 return $guest;
 4357:             }
 4358:         }
 4359:     }
 4360:     return;
 4361: }
 4362: 
 4363: sub course_group_datechecker {
 4364:     my ($dates,$now,$status) = @_;
 4365:     my ($start,$end) = split(/\./,$dates);
 4366:     if (!$start && !$end) {
 4367:         return 'ok';
 4368:     }
 4369:     if (grep/^active$/,@{$status}) {
 4370:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4371:             return 'ok';
 4372:         }
 4373:     }
 4374:     if (grep/^previous$/,@{$status}) {
 4375:         if ($end > $now ) {
 4376:             return 'ok';
 4377:         }
 4378:     }
 4379:     if (grep/^future$/,@{$status}) {
 4380:         if ($start > $now) {
 4381:             return 'ok';
 4382:         }
 4383:     }
 4384:     return; 
 4385: }
 4386: 
 4387: sub parse_portfolio_url {
 4388:     my ($url) = @_;
 4389: 
 4390:     my ($type,$udom,$unum,$group,$file_name);
 4391:     
 4392:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4393: 	$type = 1;
 4394:         $udom = $1;
 4395:         $unum = $2;
 4396:         $file_name = $3;
 4397:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4398: 	$type = 2;
 4399:         $udom = $1;
 4400:         $unum = $2;
 4401:         $group = $3;
 4402:         $file_name = $3.'/'.$4;
 4403:     }
 4404:     if (wantarray) {
 4405: 	return ($type,$udom,$unum,$file_name,$group);
 4406:     }
 4407:     return $type;
 4408: }
 4409: 
 4410: sub is_portfolio_url {
 4411:     my ($url) = @_;
 4412:     return scalar(&parse_portfolio_url($url));
 4413: }
 4414: 
 4415: sub is_portfolio_file {
 4416:     my ($file) = @_;
 4417:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4418:         return 1;
 4419:     }
 4420:     return;
 4421: }
 4422: 
 4423: sub usertools_access {
 4424:     my ($uname,$udom,$tool,$action) = @_;
 4425:     my $access;
 4426:     my %tools = (
 4427:                   aboutme   => 1,
 4428:                   blog      => 1,
 4429:                   portfolio => 1,
 4430:                 );
 4431:     return if (!defined($tools{$tool}));
 4432: 
 4433:     if ((!defined($udom)) || (!defined($uname))) {
 4434:         $udom = $env{'user.domain'};
 4435:         $uname = $env{'user.name'};
 4436:     }
 4437: 
 4438:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4439:         if ($action ne 'reload') {
 4440:             return $env{'environment.availabletools.'.$tool};
 4441:         } 
 4442:     }
 4443: 
 4444:     my ($toolstatus,$inststatus);
 4445: 
 4446:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4447:         $toolstatus = $env{'environment.tools.'.$tool};
 4448:         $inststatus = $env{'environment.inststatus'};
 4449:     } else {
 4450:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4451:         $toolstatus = $userenv{'tools.'.$tool};
 4452:         $inststatus = $userenv{'inststatus'};
 4453:     }
 4454: 
 4455:     if ($toolstatus ne '') {
 4456:         if ($toolstatus) {
 4457:             $access = 1;
 4458:         } else {
 4459:             $access = 0;
 4460:         }
 4461:         return $access;
 4462:     }
 4463: 
 4464:     my $is_adv = &is_advanced_user($udom,$uname);
 4465:     my %domdef = &get_domain_defaults($udom);
 4466:     if (ref($domdef{$tool}) eq 'HASH') {
 4467:         if ($is_adv) {
 4468:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4469:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4470:                     $access = 1;
 4471:                 } else {
 4472:                     $access = 0;
 4473:                 }
 4474:                 return $access;
 4475:             }
 4476:         }
 4477:         if ($inststatus ne '') {
 4478:             my ($hasaccess,$hasnoaccess);
 4479:             foreach my $affiliation (split(/:/,$inststatus)) {
 4480:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4481:                     if ($domdef{$tool}{$affiliation}) {
 4482:                         $hasaccess = 1;
 4483:                     } else {
 4484:                         $hasnoaccess = 1;
 4485:                     }
 4486:                 }
 4487:             }
 4488:             if ($hasaccess || $hasnoaccess) {
 4489:                 if ($hasaccess) {
 4490:                     $access = 1;
 4491:                 } elsif ($hasnoaccess) {
 4492:                     $access = 0; 
 4493:                 }
 4494:                 return $access;
 4495:             }
 4496:         } else {
 4497:             if ($domdef{$tool}{'default'} ne '') {
 4498:                 if ($domdef{$tool}{'default'}) {
 4499:                     $access = 1;
 4500:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4501:                     $access = 0;
 4502:                 }
 4503:                 return $access;
 4504:             }
 4505:         }
 4506:     } else {
 4507:         $access = 1;
 4508:         return $access;
 4509:     }
 4510: }
 4511: 
 4512: sub is_advanced_user {
 4513:     my ($udom,$uname) = @_;
 4514:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4515:     my %allroles;
 4516:     my $is_adv;
 4517:     foreach my $role (keys(%roleshash)) {
 4518:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4519:         my $area = '/'.$tdomain.'/'.$trest;
 4520:         if ($sec ne '') {
 4521:             $area .= '/'.$sec;
 4522:         }
 4523:         if (($area ne '') && ($trole ne '')) {
 4524:             my $spec=$trole.'.'.$area;
 4525:             if ($trole =~ /^cr\//) {
 4526:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4527:             } elsif ($trole ne 'gr') {
 4528:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4529:             }
 4530:         }
 4531:     }
 4532:     foreach my $role (keys(%allroles)) {
 4533:         last if ($is_adv);
 4534:         foreach my $item (split(/:/,$allroles{$role})) {
 4535:             if ($item ne '') {
 4536:                 my ($privilege,$restrictions)=split(/&/,$item);
 4537:                 if ($privilege eq 'adv') {
 4538:                     $is_adv = 1;
 4539:                     last;
 4540:                 }
 4541:             }
 4542:         }
 4543:     }
 4544:     return $is_adv;
 4545: }
 4546: 
 4547: # ---------------------------------------------- Custom access rule evaluation
 4548: 
 4549: sub customaccess {
 4550:     my ($priv,$uri)=@_;
 4551:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4552:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4553:     $udom = &LONCAPA::clean_domain($udom);
 4554:     $ucrs = &LONCAPA::clean_username($ucrs);
 4555:     my $access=0;
 4556:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4557: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4558: 	if ($type eq 'user') {
 4559: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4560: 		my ($tdom,$tuname)=split(m{/},$scope);
 4561: 		if ($tdom) {
 4562: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4563: 		}
 4564: 		if ($tuname) {
 4565: 		    if ($tuname ne $env{'user.name'}) { next; }
 4566: 		}
 4567: 		$access=($effect eq 'allow');
 4568: 		last;
 4569: 	    }
 4570: 	} else {
 4571: 	    if ($role) {
 4572: 		if ($role ne $urole) { next; }
 4573: 	    }
 4574: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4575: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4576: 		if ($tdom) {
 4577: 		    if ($tdom ne $udom) { next; }
 4578: 		}
 4579: 		if ($tcrs) {
 4580: 		    if ($tcrs ne $ucrs) { next; }
 4581: 		}
 4582: 		if ($tsec) {
 4583: 		    if ($tsec ne $usec) { next; }
 4584: 		}
 4585: 		$access=($effect eq 'allow');
 4586: 		last;
 4587: 	    }
 4588: 	    if ($realm eq '' && $role eq '') {
 4589: 		$access=($effect eq 'allow');
 4590: 	    }
 4591: 	}
 4592:     }
 4593:     return $access;
 4594: }
 4595: 
 4596: # ------------------------------------------------- Check for a user privilege
 4597: 
 4598: sub allowed {
 4599:     my ($priv,$uri,$symb,$role)=@_;
 4600:     my $ver_orguri=$uri;
 4601:     $uri=&deversion($uri);
 4602:     my $orguri=$uri;
 4603:     $uri=&declutter($uri);
 4604: 
 4605:     if ($priv eq 'evb') {
 4606: # Evade communication block restrictions for specified role in a course
 4607:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4608:             return $1;
 4609:         } else {
 4610:             return;
 4611:         }
 4612:     }
 4613: 
 4614:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4615: # Free bre access to adm and meta resources
 4616:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4617: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4618: 	&& ($priv eq 'bre')) {
 4619: 	return 'F';
 4620:     }
 4621: 
 4622: # Free bre access to user's own portfolio contents
 4623:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4624:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4625: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4626:         my %setters;
 4627:         my ($startblock,$endblock) = 
 4628:             &Apache::loncommon::blockcheck(\%setters,'port');
 4629:         if ($startblock && $endblock) {
 4630:             return 'B';
 4631:         } else {
 4632:             return 'F';
 4633:         }
 4634:     }
 4635: 
 4636: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4637:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4638:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4639:         if (exists($env{'request.course.id'})) {
 4640:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4641:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4642:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4643:                 my $courseprivid=$env{'request.course.id'};
 4644:                 $courseprivid=~s/\_/\//;
 4645:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4646:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4647:                     return $1; 
 4648:                 } else {
 4649:                     if ($env{'request.course.sec'}) {
 4650:                         $courseprivid.='/'.$env{'request.course.sec'};
 4651:                     }
 4652:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4653:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4654:                         return $2;
 4655:                     }
 4656:                 }
 4657:             }
 4658:         }
 4659:     }
 4660: 
 4661: # Free bre to public access
 4662: 
 4663:     if ($priv eq 'bre') {
 4664:         my $copyright=&metadata($uri,'copyright');
 4665: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4666:            return 'F'; 
 4667:         }
 4668:         if ($copyright eq 'priv') {
 4669:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4670: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4671: 		return '';
 4672:             }
 4673:         }
 4674:         if ($copyright eq 'domain') {
 4675:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4676: 	    unless (($env{'user.domain'} eq $1) ||
 4677:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4678: 		return '';
 4679:             }
 4680:         }
 4681:         if ($env{'request.role'}=~ /li\.\//) {
 4682:             # Library role, so allow browsing of resources in this domain.
 4683:             return 'F';
 4684:         }
 4685:         if ($copyright eq 'custom') {
 4686: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4687:         }
 4688:     }
 4689:     # Domain coordinator is trying to create a course
 4690:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4691:         # uri is the requested domain in this case.
 4692:         # comparison to 'request.role.domain' shows if the user has selected
 4693:         # a role of dc for the domain in question.
 4694:         return 'F' if ($uri eq $env{'request.role.domain'});
 4695:     }
 4696: 
 4697:     my $thisallowed='';
 4698:     my $statecond=0;
 4699:     my $courseprivid='';
 4700: 
 4701: # Course
 4702: 
 4703:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4704:        $thisallowed.=$1;
 4705:     }
 4706: 
 4707: # Domain
 4708: 
 4709:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4710:        =~/\Q$priv\E\&([^\:]*)/) {
 4711:        $thisallowed.=$1;
 4712:     }
 4713: 
 4714: # Course: uri itself is a course
 4715:     my $courseuri=$uri;
 4716:     $courseuri=~s/\_(\d)/\/$1/;
 4717:     $courseuri=~s/^([^\/])/\/$1/;
 4718: 
 4719:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4720:        =~/\Q$priv\E\&([^\:]*)/) {
 4721:        $thisallowed.=$1;
 4722:     }
 4723: 
 4724: # URI is an uploaded document for this course, default permissions don't matter
 4725: # not allowing 'edit' access (editupload) to uploaded course docs
 4726:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4727: 	$thisallowed='';
 4728:         my ($match)=&is_on_map($uri);
 4729:         if ($match) {
 4730:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4731:                   =~/\Q$priv\E\&([^\:]*)/) {
 4732:                 $thisallowed.=$1;
 4733:             }
 4734:         } else {
 4735:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4736:             if ($refuri) {
 4737:                 if ($refuri =~ m|^/adm/|) {
 4738:                     $thisallowed='F';
 4739:                 } else {
 4740:                     $refuri=&declutter($refuri);
 4741:                     my ($match) = &is_on_map($refuri);
 4742:                     if ($match) {
 4743:                         $thisallowed='F';
 4744:                     }
 4745:                 }
 4746:             }
 4747:         }
 4748:     }
 4749: 
 4750:     if ($priv eq 'bre'
 4751: 	&& $thisallowed ne 'F' 
 4752: 	&& $thisallowed ne '2'
 4753: 	&& &is_portfolio_url($uri)) {
 4754: 	$thisallowed = &portfolio_access($uri);
 4755:     }
 4756:     
 4757: # Full access at system, domain or course-wide level? Exit.
 4758:     if ($thisallowed=~/F/) {
 4759: 	return 'F';
 4760:     }
 4761: 
 4762: # If this is generating or modifying users, exit with special codes
 4763: 
 4764:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4765: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4766: 	    my ($audom,$auname)=split('/',$uri);
 4767: # no author name given, so this just checks on the general right to make a co-author in this domain
 4768: 	    unless ($auname) { return $thisallowed; }
 4769: # an author name is given, so we are about to actually make a co-author for a certain account
 4770: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4771: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4772: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4773: 	}
 4774: 	return $thisallowed;
 4775:     }
 4776: #
 4777: # Gathered so far: system, domain and course wide privileges
 4778: #
 4779: # Course: See if uri or referer is an individual resource that is part of 
 4780: # the course
 4781: 
 4782:     if ($env{'request.course.id'}) {
 4783: 
 4784:        $courseprivid=$env{'request.course.id'};
 4785:        if ($env{'request.course.sec'}) {
 4786:           $courseprivid.='/'.$env{'request.course.sec'};
 4787:        }
 4788:        $courseprivid=~s/\_/\//;
 4789:        my $checkreferer=1;
 4790:        my ($match,$cond)=&is_on_map($uri);
 4791:        if ($match) {
 4792:            $statecond=$cond;
 4793:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4794:                =~/\Q$priv\E\&([^\:]*)/) {
 4795:                $thisallowed.=$1;
 4796:                $checkreferer=0;
 4797:            }
 4798:        }
 4799:        
 4800:        if ($checkreferer) {
 4801: 	  my $refuri=$env{'httpref.'.$orguri};
 4802:             unless ($refuri) {
 4803:                 foreach my $key (keys(%env)) {
 4804: 		    if ($key=~/^httpref\..*\*/) {
 4805: 			my $pattern=$key;
 4806:                         $pattern=~s/^httpref\.\/res\///;
 4807:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4808:                         $pattern=~s/\//\\\//g;
 4809:                         if ($orguri=~/$pattern/) {
 4810: 			    $refuri=$env{$key};
 4811:                         }
 4812:                     }
 4813:                 }
 4814:             }
 4815: 
 4816:          if ($refuri) { 
 4817: 	  $refuri=&declutter($refuri);
 4818:           my ($match,$cond)=&is_on_map($refuri);
 4819:             if ($match) {
 4820:               my $refstatecond=$cond;
 4821:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4822:                   =~/\Q$priv\E\&([^\:]*)/) {
 4823:                   $thisallowed.=$1;
 4824:                   $uri=$refuri;
 4825:                   $statecond=$refstatecond;
 4826:               }
 4827:           }
 4828:         }
 4829:        }
 4830:    }
 4831: 
 4832: #
 4833: # Gathered now: all privileges that could apply, and condition number
 4834: # 
 4835: #
 4836: # Full or no access?
 4837: #
 4838: 
 4839:     if ($thisallowed=~/F/) {
 4840: 	return 'F';
 4841:     }
 4842: 
 4843:     unless ($thisallowed) {
 4844:         return '';
 4845:     }
 4846: 
 4847: # Restrictions exist, deal with them
 4848: #
 4849: #   C:according to course preferences
 4850: #   R:according to resource settings
 4851: #   L:unless locked
 4852: #   X:according to user session state
 4853: #
 4854: 
 4855: # Possibly locked functionality, check all courses
 4856: # Locks might take effect only after 10 minutes cache expiration for other
 4857: # courses, and 2 minutes for current course
 4858: 
 4859:     my $envkey;
 4860:     if ($thisallowed=~/L/) {
 4861:         foreach $envkey (keys %env) {
 4862:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4863:                my $courseid=$2;
 4864:                my $roleid=$1.'.'.$2;
 4865:                $courseid=~s/^\///;
 4866:                my $expiretime=600;
 4867:                if ($env{'request.role'} eq $roleid) {
 4868: 		  $expiretime=120;
 4869:                }
 4870: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4871:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4872:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4873: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4874:                }
 4875:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4876:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4877: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4878:                        &log($env{'user.domain'},$env{'user.name'},
 4879:                             $env{'user.home'},
 4880:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4881:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4882:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4883: 		       return '';
 4884:                    }
 4885:                }
 4886:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4887:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4888: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4889:                        &log($env{'user.domain'},$env{'user.name'},
 4890:                             $env{'user.home'},
 4891:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4892:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4893:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4894: 		       return '';
 4895:                    }
 4896:                }
 4897: 	   }
 4898:        }
 4899:     }
 4900:    
 4901: #
 4902: # Rest of the restrictions depend on selected course
 4903: #
 4904: 
 4905:     unless ($env{'request.course.id'}) {
 4906: 	if ($thisallowed eq 'A') {
 4907: 	    return 'A';
 4908:         } elsif ($thisallowed eq 'B') {
 4909:             return 'B';
 4910: 	} else {
 4911: 	    return '1';
 4912: 	}
 4913:     }
 4914: 
 4915: #
 4916: # Now user is definitely in a course
 4917: #
 4918: 
 4919: 
 4920: # Course preferences
 4921: 
 4922:    if ($thisallowed=~/C/) {
 4923:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4924:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4925:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4926: 	   =~/\Q$rolecode\E/) {
 4927: 	   if ($priv ne 'pch') { 
 4928: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4929: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4930: 			$env{'request.course.id'});
 4931: 	   }
 4932:            return '';
 4933:        }
 4934: 
 4935:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4936: 	   =~/\Q$unamedom\E/) {
 4937: 	   if ($priv ne 'pch') { 
 4938: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4939: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4940: 			$env{'request.course.id'});
 4941: 	   }
 4942:            return '';
 4943:        }
 4944:    }
 4945: 
 4946: # Resource preferences
 4947: 
 4948:    if ($thisallowed=~/R/) {
 4949:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4950:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4951: 	   if ($priv ne 'pch') { 
 4952: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4953: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4954: 	   }
 4955: 	   return '';
 4956:        }
 4957:    }
 4958: 
 4959: # Restricted by state or randomout?
 4960: 
 4961:    if ($thisallowed=~/X/) {
 4962:       if ($env{'acc.randomout'}) {
 4963: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4964:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4965:             return ''; 
 4966:          }
 4967:       }
 4968:       if (&condval($statecond)) {
 4969: 	 return '2';
 4970:       } else {
 4971:          return '';
 4972:       }
 4973:    }
 4974: 
 4975:     if ($thisallowed eq 'A') {
 4976: 	return 'A';
 4977:     } elsif ($thisallowed eq 'B') {
 4978:         return 'B';
 4979:     }
 4980:    return 'F';
 4981: }
 4982: 
 4983: sub split_uri_for_cond {
 4984:     my $uri=&deversion(&declutter(shift));
 4985:     my @uriparts=split(/\//,$uri);
 4986:     my $filename=pop(@uriparts);
 4987:     my $pathname=join('/',@uriparts);
 4988:     return ($pathname,$filename);
 4989: }
 4990: # --------------------------------------------------- Is a resource on the map?
 4991: 
 4992: sub is_on_map {
 4993:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4994:     #Trying to find the conditional for the file
 4995:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4996: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4997:     if ($match) {
 4998: 	return (1,$1);
 4999:     } else {
 5000: 	return (0,0);
 5001:     }
 5002: }
 5003: 
 5004: # --------------------------------------------------------- Get symb from alias
 5005: 
 5006: sub get_symb_from_alias {
 5007:     my $symb=shift;
 5008:     my ($map,$resid,$url)=&decode_symb($symb);
 5009: # Already is a symb
 5010:     if ($url) { return $symb; }
 5011: # Must be an alias
 5012:     my $aliassymb='';
 5013:     my %bighash;
 5014:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5015:                             &GDBM_READER(),0640)) {
 5016:         my $rid=$bighash{'mapalias_'.$symb};
 5017: 	if ($rid) {
 5018: 	    my ($mapid,$resid)=split(/\./,$rid);
 5019: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5020: 				    $resid,$bighash{'src_'.$rid});
 5021: 	}
 5022:         untie %bighash;
 5023:     }
 5024:     return $aliassymb;
 5025: }
 5026: 
 5027: # ----------------------------------------------------------------- Define Role
 5028: 
 5029: sub definerole {
 5030:   if (allowed('mcr','/')) {
 5031:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5032:     foreach my $role (split(':',$sysrole)) {
 5033: 	my ($crole,$cqual)=split(/\&/,$role);
 5034:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5035:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5036: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5037:                return "refused:s:$crole&$cqual"; 
 5038:             }
 5039:         }
 5040:     }
 5041:     foreach my $role (split(':',$domrole)) {
 5042: 	my ($crole,$cqual)=split(/\&/,$role);
 5043:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5044:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5045: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5046:                return "refused:d:$crole&$cqual"; 
 5047:             }
 5048:         }
 5049:     }
 5050:     foreach my $role (split(':',$courole)) {
 5051: 	my ($crole,$cqual)=split(/\&/,$role);
 5052:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5053:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5054: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5055:                return "refused:c:$crole&$cqual"; 
 5056:             }
 5057:         }
 5058:     }
 5059:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5060:                 "$env{'user.domain'}:$env{'user.name'}:".
 5061: 	        "rolesdef_$rolename=".
 5062:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5063:     return reply($command,$env{'user.home'});
 5064:   } else {
 5065:     return 'refused';
 5066:   }
 5067: }
 5068: 
 5069: # ---------------- Make a metadata query against the network of library servers
 5070: 
 5071: sub metadata_query {
 5072:     my ($query,$custom,$customshow,$server_array)=@_;
 5073:     my %rhash;
 5074:     my %libserv = &all_library();
 5075:     my @server_list = (defined($server_array) ? @$server_array
 5076:                                               : keys(%libserv) );
 5077:     for my $server (@server_list) {
 5078: 	unless ($custom or $customshow) {
 5079: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5080: 	    $rhash{$server}=$reply;
 5081: 	}
 5082: 	else {
 5083: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5084: 			     &escape($custom).':'.&escape($customshow),
 5085: 			     $server);
 5086: 	    $rhash{$server}=$reply;
 5087: 	}
 5088:     }
 5089:     return \%rhash;
 5090: }
 5091: 
 5092: # ----------------------------------------- Send log queries and wait for reply
 5093: 
 5094: sub log_query {
 5095:     my ($uname,$udom,$query,%filters)=@_;
 5096:     my $uhome=&homeserver($uname,$udom);
 5097:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5098:     my $uhost=&hostname($uhome);
 5099:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5100:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5101:                        $uhome);
 5102:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5103:     return get_query_reply($queryid);
 5104: }
 5105: 
 5106: # -------------------------- Update MySQL table for portfolio file
 5107: 
 5108: sub update_portfolio_table {
 5109:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5110:     if ($group ne '') {
 5111:         $file_name =~s /^\Q$group\E//;
 5112:     }
 5113:     my $homeserver = &homeserver($uname,$udom);
 5114:     my $queryid=
 5115:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5116:                ':'.&escape($file_name).':'.$action,$homeserver);
 5117:     my $reply = &get_query_reply($queryid);
 5118:     return $reply;
 5119: }
 5120: 
 5121: # -------------------------- Update MySQL allusers table
 5122: 
 5123: sub update_allusers_table {
 5124:     my ($uname,$udom,$names) = @_;
 5125:     my $homeserver = &homeserver($uname,$udom);
 5126:     my $queryid=
 5127:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5128:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5129:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5130:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5131:                'generation='.&escape($names->{'generation'}).'%%'.
 5132:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5133:                'id='.&escape($names->{'id'}),$homeserver);
 5134:     my $reply = &get_query_reply($queryid);
 5135:     return $reply;
 5136: }
 5137: 
 5138: # ------- Request retrieval of institutional classlists for course(s)
 5139: 
 5140: sub fetch_enrollment_query {
 5141:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5142:     my $homeserver;
 5143:     my $maxtries = 1;
 5144:     if ($context eq 'automated') {
 5145:         $homeserver = $perlvar{'lonHostID'};
 5146:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5147:     } else {
 5148:         $homeserver = &homeserver($cnum,$dom);
 5149:     }
 5150:     my $host=&hostname($homeserver);
 5151:     my $cmd = '';
 5152:     foreach my $affiliate (keys %{$affiliatesref}) {
 5153:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5154:     }
 5155:     $cmd =~ s/%%$//;
 5156:     $cmd = &escape($cmd);
 5157:     my $query = 'fetchenrollment';
 5158:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5159:     unless ($queryid=~/^\Q$host\E\_/) { 
 5160:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5161:         return 'error: '.$queryid;
 5162:     }
 5163:     my $reply = &get_query_reply($queryid);
 5164:     my $tries = 1;
 5165:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5166:         $reply = &get_query_reply($queryid);
 5167:         $tries ++;
 5168:     }
 5169:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5170:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5171:     } else {
 5172:         my @responses = split(/:/,$reply);
 5173:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5174:             foreach my $line (@responses) {
 5175:                 my ($key,$value) = split(/=/,$line,2);
 5176:                 $$replyref{$key} = $value;
 5177:             }
 5178:         } else {
 5179:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5180:             foreach my $line (@responses) {
 5181:                 my ($key,$value) = split(/=/,$line);
 5182:                 $$replyref{$key} = $value;
 5183:                 if ($value > 0) {
 5184:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5185:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5186:                         my $destname = $pathname.'/'.$filename;
 5187:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5188:                         if ($xml_classlist =~ /^error/) {
 5189:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5190:                         } else {
 5191:                             if ( open(FILE,">$destname") ) {
 5192:                                 print FILE &unescape($xml_classlist);
 5193:                                 close(FILE);
 5194:                             } else {
 5195:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5196:                             }
 5197:                         }
 5198:                     }
 5199:                 }
 5200:             }
 5201:         }
 5202:         return 'ok';
 5203:     }
 5204:     return 'error';
 5205: }
 5206: 
 5207: sub get_query_reply {
 5208:     my $queryid=shift;
 5209:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5210:     my $reply='';
 5211:     for (1..100) {
 5212: 	sleep 2;
 5213:         if (-e $replyfile.'.end') {
 5214: 	    if (open(my $fh,$replyfile)) {
 5215: 		$reply = join('',<$fh>);
 5216: 		close($fh);
 5217: 	   } else { return 'error: reply_file_error'; }
 5218:            return &unescape($reply);
 5219: 	}
 5220:     }
 5221:     return 'timeout:'.$queryid;
 5222: }
 5223: 
 5224: sub courselog_query {
 5225: #
 5226: # possible filters:
 5227: # url: url or symb
 5228: # username
 5229: # domain
 5230: # action: view, submit, grade
 5231: # start: timestamp
 5232: # end: timestamp
 5233: #
 5234:     my (%filters)=@_;
 5235:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5236:     if ($filters{'url'}) {
 5237: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5238:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5239:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5240:     }
 5241:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5242:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5243:     return &log_query($cname,$cdom,'courselog',%filters);
 5244: }
 5245: 
 5246: sub userlog_query {
 5247: #
 5248: # possible filters:
 5249: # action: log check role
 5250: # start: timestamp
 5251: # end: timestamp
 5252: #
 5253:     my ($uname,$udom,%filters)=@_;
 5254:     return &log_query($uname,$udom,'userlog',%filters);
 5255: }
 5256: 
 5257: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5258: 
 5259: sub auto_run {
 5260:     my ($cnum,$cdom) = @_;
 5261:     my $response = 0;
 5262:     my $settings;
 5263:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5264:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5265:         $settings = $domconfig{'autoenroll'};
 5266:         if ($settings->{'run'} eq '1') {
 5267:             $response = 1;
 5268:         }
 5269:     } else {
 5270:         my $homeserver;
 5271:         if (&is_course($cdom,$cnum)) {
 5272:             $homeserver = &homeserver($cnum,$cdom);
 5273:         } else {
 5274:             $homeserver = &domain($cdom,'primary');
 5275:         }
 5276:         if ($homeserver ne 'no_host') {
 5277:             $response = &reply('autorun:'.$cdom,$homeserver);
 5278:         }
 5279:     }
 5280:     return $response;
 5281: }
 5282: 
 5283: sub auto_get_sections {
 5284:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5285:     my $homeserver = &homeserver($cnum,$cdom);
 5286:     my @secs = ();
 5287:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5288:     unless ($response eq 'refused') {
 5289:         @secs = split(/:/,$response);
 5290:     }
 5291:     return @secs;
 5292: }
 5293: 
 5294: sub auto_new_course {
 5295:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5296:     my $homeserver = &homeserver($cnum,$cdom);
 5297:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5298:     return $response;
 5299: }
 5300: 
 5301: sub auto_validate_courseID {
 5302:     my ($cnum,$cdom,$inst_course_id) = @_;
 5303:     my $homeserver = &homeserver($cnum,$cdom);
 5304:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5305:     return $response;
 5306: }
 5307: 
 5308: sub auto_create_password {
 5309:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5310:     my ($homeserver,$response);
 5311:     my $create_passwd = 0;
 5312:     my $authchk = '';
 5313:     if ($udom =~ /^$match_domain$/) {
 5314:         $homeserver = &domain($udom,'primary');
 5315:     }
 5316:     if ($homeserver eq '') {
 5317:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5318:             $homeserver = &homeserver($cnum,$cdom);
 5319:         }
 5320:     }
 5321:     if ($homeserver eq '') {
 5322:         $authchk = 'nodomain';
 5323:     } else {
 5324:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5325:         if ($response eq 'refused') {
 5326:             $authchk = 'refused';
 5327:         } else {
 5328:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5329:         }
 5330:     }
 5331:     return ($authparam,$create_passwd,$authchk);
 5332: }
 5333: 
 5334: sub auto_photo_permission {
 5335:     my ($cnum,$cdom,$students) = @_;
 5336:     my $homeserver = &homeserver($cnum,$cdom);
 5337:     my ($outcome,$perm_reqd,$conditions) = 
 5338: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5339:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5340: 	return (undef,undef);
 5341:     }
 5342:     return ($outcome,$perm_reqd,$conditions);
 5343: }
 5344: 
 5345: sub auto_checkphotos {
 5346:     my ($uname,$udom,$pid) = @_;
 5347:     my $homeserver = &homeserver($uname,$udom);
 5348:     my ($result,$resulttype);
 5349:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5350: 				   &escape($uname).':'.&escape($pid),
 5351: 				   $homeserver));
 5352:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5353: 	return (undef,undef);
 5354:     }
 5355:     if ($outcome) {
 5356:         ($result,$resulttype) = split(/:/,$outcome);
 5357:     } 
 5358:     return ($result,$resulttype);
 5359: }
 5360: 
 5361: sub auto_photochoice {
 5362:     my ($cnum,$cdom) = @_;
 5363:     my $homeserver = &homeserver($cnum,$cdom);
 5364:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5365: 						       &escape($cdom),
 5366: 						       $homeserver)));
 5367:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5368: 	return (undef,undef);
 5369:     }
 5370:     return ($update,$comment);
 5371: }
 5372: 
 5373: sub auto_photoupdate {
 5374:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5375:     my $homeserver = &homeserver($cnum,$dom);
 5376:     my $host=&hostname($homeserver);
 5377:     my $cmd = '';
 5378:     my $maxtries = 1;
 5379:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5380:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5381:     }
 5382:     $cmd =~ s/%%$//;
 5383:     $cmd = &escape($cmd);
 5384:     my $query = 'institutionalphotos';
 5385:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5386:     unless ($queryid=~/^\Q$host\E\_/) {
 5387:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5388:         return 'error: '.$queryid;
 5389:     }
 5390:     my $reply = &get_query_reply($queryid);
 5391:     my $tries = 1;
 5392:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5393:         $reply = &get_query_reply($queryid);
 5394:         $tries ++;
 5395:     }
 5396:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5397:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5398:     } else {
 5399:         my @responses = split(/:/,$reply);
 5400:         my $outcome = shift(@responses); 
 5401:         foreach my $item (@responses) {
 5402:             my ($key,$value) = split(/=/,$item);
 5403:             $$photo{$key} = $value;
 5404:         }
 5405:         return $outcome;
 5406:     }
 5407:     return 'error';
 5408: }
 5409: 
 5410: sub auto_instcode_format {
 5411:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5412: 	$cat_order) = @_;
 5413:     my $courses = '';
 5414:     my @homeservers;
 5415:     if ($caller eq 'global') {
 5416: 	my %servers = &get_servers($codedom,'library');
 5417: 	foreach my $tryserver (keys(%servers)) {
 5418: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5419: 		push(@homeservers,$tryserver);
 5420: 	    }
 5421:         }
 5422:     } else {
 5423:         push(@homeservers,&homeserver($caller,$codedom));
 5424:     }
 5425:     foreach my $code (keys(%{$instcodes})) {
 5426:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5427:     }
 5428:     chop($courses);
 5429:     my $ok_response = 0;
 5430:     my $response;
 5431:     while (@homeservers > 0 && $ok_response == 0) {
 5432:         my $server = shift(@homeservers); 
 5433:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5434:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5435:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5436: 		split(/:/,$response);
 5437:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5438:             push(@{$codetitles},&str2array($codetitles_str));
 5439:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5440:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5441:             $ok_response = 1;
 5442:         }
 5443:     }
 5444:     if ($ok_response) {
 5445:         return 'ok';
 5446:     } else {
 5447:         return $response;
 5448:     }
 5449: }
 5450: 
 5451: sub auto_instcode_defaults {
 5452:     my ($domain,$returnhash,$code_order) = @_;
 5453:     my @homeservers;
 5454: 
 5455:     my %servers = &get_servers($domain,'library');
 5456:     foreach my $tryserver (keys(%servers)) {
 5457: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5458: 	    push(@homeservers,$tryserver);
 5459: 	}
 5460:     }
 5461: 
 5462:     my $response;
 5463:     foreach my $server (@homeservers) {
 5464:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5465:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5466: 	
 5467: 	foreach my $pair (split(/\&/,$response)) {
 5468: 	    my ($name,$value)=split(/\=/,$pair);
 5469: 	    if ($name eq 'code_order') {
 5470: 		@{$code_order} = split(/\&/,&unescape($value));
 5471: 	    } else {
 5472: 		$returnhash->{&unescape($name)}=&unescape($value);
 5473: 	    }
 5474: 	}
 5475: 	return 'ok';
 5476:     }
 5477: 
 5478:     return $response;
 5479: } 
 5480: 
 5481: sub auto_validate_class_sec {
 5482:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5483:     my $homeserver = &homeserver($cnum,$cdom);
 5484:     my $ownerlist;
 5485:     if (ref($owners) eq 'ARRAY') {
 5486:         $ownerlist = join(',',@{$owners});
 5487:     } else {
 5488:         $ownerlist = $owners;
 5489:     }
 5490:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5491:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5492:     return $response;
 5493: }
 5494: 
 5495: # ------------------------------------------------------- Course Group routines
 5496: 
 5497: sub get_coursegroups {
 5498:     my ($cdom,$cnum,$group,$namespace) = @_;
 5499:     return(&dump($namespace,$cdom,$cnum,$group));
 5500: }
 5501: 
 5502: sub modify_coursegroup {
 5503:     my ($cdom,$cnum,$groupsettings) = @_;
 5504:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5505: }
 5506: 
 5507: sub toggle_coursegroup_status {
 5508:     my ($cdom,$cnum,$group,$action) = @_;
 5509:     my ($from_namespace,$to_namespace);
 5510:     if ($action eq 'delete') {
 5511:         $from_namespace = 'coursegroups';
 5512:         $to_namespace = 'deleted_groups';
 5513:     } else {
 5514:         $from_namespace = 'deleted_groups';
 5515:         $to_namespace = 'coursegroups';
 5516:     }
 5517:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5518:     if (my $tmp = &error(%curr_group)) {
 5519:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5520:         return ('read error',$tmp);
 5521:     } else {
 5522:         my %savedsettings = %curr_group; 
 5523:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5524:         my $deloutcome;
 5525:         if ($result eq 'ok') {
 5526:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5527:         } else {
 5528:             return ('write error',$result);
 5529:         }
 5530:         if ($deloutcome eq 'ok') {
 5531:             return 'ok';
 5532:         } else {
 5533:             return ('delete error',$deloutcome);
 5534:         }
 5535:     }
 5536: }
 5537: 
 5538: sub modify_group_roles {
 5539:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5540:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5541:     my $role = 'gr/'.&escape($userprivs);
 5542:     my ($uname,$udom) = split(/:/,$user);
 5543:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5544:     if ($result eq 'ok') {
 5545:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5546:     }
 5547:     return $result;
 5548: }
 5549: 
 5550: sub modify_coursegroup_membership {
 5551:     my ($cdom,$cnum,$membership) = @_;
 5552:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5553:     return $result;
 5554: }
 5555: 
 5556: sub get_active_groups {
 5557:     my ($udom,$uname,$cdom,$cnum) = @_;
 5558:     my $now = time;
 5559:     my %groups = ();
 5560:     foreach my $key (keys(%env)) {
 5561:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5562:             my ($start,$end) = split(/\./,$env{$key});
 5563:             if (($end!=0) && ($end<$now)) { next; }
 5564:             if (($start!=0) && ($start>$now)) { next; }
 5565:             if ($1 eq $cdom && $2 eq $cnum) {
 5566:                 $groups{$3} = $env{$key} ;
 5567:             }
 5568:         }
 5569:     }
 5570:     return %groups;
 5571: }
 5572: 
 5573: sub get_group_membership {
 5574:     my ($cdom,$cnum,$group) = @_;
 5575:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5576: }
 5577: 
 5578: sub get_users_groups {
 5579:     my ($udom,$uname,$courseid) = @_;
 5580:     my @usersgroups;
 5581:     my $cachetime=1800;
 5582: 
 5583:     my $hashid="$udom:$uname:$courseid";
 5584:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5585:     if (defined($cached)) {
 5586:         @usersgroups = split(/:/,$grouplist);
 5587:     } else {  
 5588:         $grouplist = '';
 5589:         my $courseurl = &courseid_to_courseurl($courseid);
 5590:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5591:         my $access_end = $env{'course.'.$courseid.
 5592:                               '.default_enrollment_end_date'};
 5593:         my $now = time;
 5594:         foreach my $key (keys(%roleshash)) {
 5595:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5596:                 my $group = $1;
 5597:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5598:                     my $start = $2;
 5599:                     my $end = $1;
 5600:                     if ($start == -1) { next; } # deleted from group
 5601:                     if (($start!=0) && ($start>$now)) { next; }
 5602:                     if (($end!=0) && ($end<$now)) {
 5603:                         if ($access_end && $access_end < $now) {
 5604:                             if ($access_end - $end < 86400) {
 5605:                                 push(@usersgroups,$group);
 5606:                             }
 5607:                         }
 5608:                         next;
 5609:                     }
 5610:                     push(@usersgroups,$group);
 5611:                 }
 5612:             }
 5613:         }
 5614:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5615:         $grouplist = join(':',@usersgroups);
 5616:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5617:     }
 5618:     return @usersgroups;
 5619: }
 5620: 
 5621: sub devalidate_getgroups_cache {
 5622:     my ($udom,$uname,$cdom,$cnum)=@_;
 5623:     my $courseid = $cdom.'_'.$cnum;
 5624: 
 5625:     my $hashid="$udom:$uname:$courseid";
 5626:     &devalidate_cache_new('getgroups',$hashid);
 5627: }
 5628: 
 5629: # ------------------------------------------------------------------ Plain Text
 5630: 
 5631: sub plaintext {
 5632:     my ($short,$type,$cid) = @_;
 5633:     if ($short =~ /^cr/) {
 5634: 	return (split('/',$short))[-1];
 5635:     }
 5636:     if (!defined($cid)) {
 5637:         $cid = $env{'request.course.id'};
 5638:     }
 5639:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5640:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5641:                                           '.plaintext'});
 5642:     }
 5643:     my %rolenames = (
 5644:                       Course => 'std',
 5645:                       Group => 'alt1',
 5646:                     );
 5647:     if (defined($type) && 
 5648:          defined($rolenames{$type}) && 
 5649:          defined($prp{$short}{$rolenames{$type}})) {
 5650:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5651:     } else {
 5652:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5653:     }
 5654: }
 5655: 
 5656: # ----------------------------------------------------------------- Assign Role
 5657: 
 5658: sub assignrole {
 5659:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5660:         $context)=@_;
 5661:     my $mrole;
 5662:     if ($role =~ /^cr\//) {
 5663:         my $cwosec=$url;
 5664:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5665: 	unless (&allowed('ccr',$cwosec)) {
 5666:            &logthis('Refused custom assignrole: '.
 5667:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5668: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5669:            return 'refused'; 
 5670:         }
 5671:         $mrole='cr';
 5672:     } elsif ($role =~ /^gr\//) {
 5673:         my $cwogrp=$url;
 5674:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5675:         unless (&allowed('mdg',$cwogrp)) {
 5676:             &logthis('Refused group assignrole: '.
 5677:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5678:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5679:             return 'refused';
 5680:         }
 5681:         $mrole='gr';
 5682:     } else {
 5683:         my $cwosec=$url;
 5684:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5685:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5686:             my $refused;
 5687:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5688:                 if (!(&allowed('c'.$role,$url))) {
 5689:                     $refused = 1;
 5690:                 }
 5691:             } else {
 5692:                 $refused = 1;
 5693:             }
 5694:             if ($refused) {
 5695:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5696:                     $refused = '';
 5697:                 } else {
 5698:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5699:                              ' '.$role.' '.$end.' '.$start.' by '.
 5700: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5701:                     return 'refused';
 5702:                 }
 5703:             }
 5704:         }
 5705:         $mrole=$role;
 5706:     }
 5707:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5708:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5709:     if ($end) { $command.='_'.$end; }
 5710:     if ($start) {
 5711: 	if ($end) { 
 5712:            $command.='_'.$start; 
 5713:         } else {
 5714:            $command.='_0_'.$start;
 5715:         }
 5716:     }
 5717:     my $origstart = $start;
 5718:     my $origend = $end;
 5719:     my $delflag;
 5720: # actually delete
 5721:     if ($deleteflag) {
 5722: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5723: # modify command to delete the role
 5724:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5725:                 "$udom:$uname:$url".'_'."$mrole";
 5726: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5727: # set start and finish to negative values for userrolelog
 5728:            $start=-1;
 5729:            $end=-1;
 5730:            $delflag = 1;
 5731:         }
 5732:     }
 5733: # send command
 5734:     my $answer=&reply($command,&homeserver($uname,$udom));
 5735: # log new user role if status is ok
 5736:     if ($answer eq 'ok') {
 5737: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5738: # for course roles, perform group memberships changes triggered by role change.
 5739:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5740:         unless ($role =~ /^gr/) {
 5741:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5742:                                              $origstart,$selfenroll,$context);
 5743:         }
 5744:     }
 5745:     return $answer;
 5746: }
 5747: 
 5748: # -------------------------------------------------- Modify user authentication
 5749: # Overrides without validation
 5750: 
 5751: sub modifyuserauth {
 5752:     my ($udom,$uname,$umode,$upass)=@_;
 5753:     my $uhome=&homeserver($uname,$udom);
 5754:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5755:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5756:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5757:              ' in domain '.$env{'request.role.domain'});  
 5758:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5759: 		     &escape($upass),$uhome);
 5760:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5761:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5762:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5763:     &log($udom,,$uname,$uhome,
 5764:         'Authentication changed by '.$env{'user.domain'}.', '.
 5765:                                      $env{'user.name'}.', '.$umode.
 5766:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5767:     unless ($reply eq 'ok') {
 5768:         &logthis('Authentication mode error: '.$reply);
 5769: 	return 'error: '.$reply;
 5770:     }   
 5771:     return 'ok';
 5772: }
 5773: 
 5774: # --------------------------------------------------------------- Modify a user
 5775: 
 5776: sub modifyuser {
 5777:     my ($udom,    $uname, $uid,
 5778:         $umode,   $upass, $first,
 5779:         $middle,  $last,  $gene,
 5780:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5781:     $udom= &LONCAPA::clean_domain($udom);
 5782:     $uname=&LONCAPA::clean_username($uname);
 5783:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5784:              $umode.', '.$first.', '.$middle.', '.
 5785: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5786:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5787:                                      ' desiredhome not specified'). 
 5788:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5789:              ' in domain '.$env{'request.role.domain'});
 5790:     my $uhome=&homeserver($uname,$udom,'true');
 5791: # ----------------------------------------------------------------- Create User
 5792:     if (($uhome eq 'no_host') && 
 5793: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5794:         my $unhome='';
 5795:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5796:             $unhome = $desiredhome;
 5797: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5798: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5799:         } else { # load balancing routine for determining $unhome
 5800:             my $loadm=10000000;
 5801: 	    my %servers = &get_servers($udom,'library');
 5802: 	    foreach my $tryserver (keys(%servers)) {
 5803: 		my $answer=reply('load',$tryserver);
 5804: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5805: 		    $loadm=$answer;
 5806: 		    $unhome=$tryserver;
 5807: 		}
 5808: 	    }
 5809:         }
 5810:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5811: 	    return 'error: unable to find a home server for '.$uname.
 5812:                    ' in domain '.$udom;
 5813:         }
 5814:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5815:                          &escape($upass),$unhome);
 5816: 	unless ($reply eq 'ok') {
 5817:             return 'error: '.$reply;
 5818:         }   
 5819:         $uhome=&homeserver($uname,$udom,'true');
 5820:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5821: 	    return 'error: unable verify users home machine.';
 5822:         }
 5823:     }   # End of creation of new user
 5824: # ---------------------------------------------------------------------- Add ID
 5825:     if ($uid) {
 5826:        $uid=~tr/A-Z/a-z/;
 5827:        my %uidhash=&idrget($udom,$uname);
 5828:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5829:          && (!$forceid)) {
 5830: 	  unless ($uid eq $uidhash{$uname}) {
 5831: 	      return 'error: user id "'.$uid.'" does not match '.
 5832:                   'current user id "'.$uidhash{$uname}.'".';
 5833:           }
 5834:        } else {
 5835: 	  &idput($udom,($uname => $uid));
 5836:        }
 5837:     }
 5838: # -------------------------------------------------------------- Add names, etc
 5839:     my @tmp=&get('environment',
 5840: 		   ['firstname','middlename','lastname','generation','id',
 5841:                     'permanentemail','inststatus'],
 5842: 		   $udom,$uname);
 5843:     my %names;
 5844:     if ($tmp[0] =~ m/^error:.*/) { 
 5845:         %names=(); 
 5846:     } else {
 5847:         %names = @tmp;
 5848:     }
 5849: #
 5850: # Make sure to not trash student environment if instructor does not bother
 5851: # to supply name and email information
 5852: #
 5853:     if ($first)  { $names{'firstname'}  = $first; }
 5854:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5855:     if ($last)   { $names{'lastname'}   = $last; }
 5856:     if (defined($gene))   { $names{'generation'} = $gene; }
 5857:     if ($email) {
 5858:        $email=~s/[^\w\@\.\-\,]//gs;
 5859:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5860:     }
 5861:     if ($uid) { $names{'id'}  = $uid; }
 5862:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5863:     my $reply = &put('environment', \%names, $udom,$uname);
 5864:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5865:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5866:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5867:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5868:                  $umode.', '.$first.', '.$middle.', '.
 5869: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5870:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5871:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5872:     } else {
 5873:         $logmsg .= ' during self creation';
 5874:     }
 5875:     &logthis($logmsg);
 5876:     return 'ok';
 5877: }
 5878: 
 5879: # -------------------------------------------------------------- Modify student
 5880: 
 5881: sub modifystudent {
 5882:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5883:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5884:         $selfenroll,$context)=@_;
 5885:     if (!$cid) {
 5886: 	unless ($cid=$env{'request.course.id'}) {
 5887: 	    return 'not_in_class';
 5888: 	}
 5889:     }
 5890: # --------------------------------------------------------------- Make the user
 5891:     my $reply=&modifyuser
 5892: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5893:          $desiredhome,$email);
 5894:     unless ($reply eq 'ok') { return $reply; }
 5895:     # This will cause &modify_student_enrollment to get the uid from the
 5896:     # students environment
 5897:     $uid = undef if (!$forceid);
 5898:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5899: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5900:     return $reply;
 5901: }
 5902: 
 5903: sub modify_student_enrollment {
 5904:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5905:     my ($cdom,$cnum,$chome);
 5906:     if (!$cid) {
 5907: 	unless ($cid=$env{'request.course.id'}) {
 5908: 	    return 'not_in_class';
 5909: 	}
 5910: 	$cdom=$env{'course.'.$cid.'.domain'};
 5911: 	$cnum=$env{'course.'.$cid.'.num'};
 5912:     } else {
 5913: 	($cdom,$cnum)=split(/_/,$cid);
 5914:     }
 5915:     $chome=$env{'course.'.$cid.'.home'};
 5916:     if (!$chome) {
 5917: 	$chome=&homeserver($cnum,$cdom);
 5918:     }
 5919:     if (!$chome) { return 'unknown_course'; }
 5920:     # Make sure the user exists
 5921:     my $uhome=&homeserver($uname,$udom);
 5922:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5923: 	return 'error: no such user';
 5924:     }
 5925:     # Get student data if we were not given enough information
 5926:     if (!defined($first)  || $first  eq '' || 
 5927:         !defined($last)   || $last   eq '' || 
 5928:         !defined($uid)    || $uid    eq '' || 
 5929:         !defined($middle) || $middle eq '' || 
 5930:         !defined($gene)   || $gene   eq '') {
 5931:         # They did not supply us with enough data to enroll the student, so
 5932:         # we need to pick up more information.
 5933:         my %tmp = &get('environment',
 5934:                        ['firstname','middlename','lastname', 'generation','id']
 5935:                        ,$udom,$uname);
 5936: 
 5937:         #foreach my $key (keys(%tmp)) {
 5938:         #    &logthis("key $key = ".$tmp{$key});
 5939:         #}
 5940:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5941:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5942:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5943:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5944:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5945:     }
 5946:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5947:     my $reply=cput('classlist',
 5948: 		   {"$uname:$udom" => 
 5949: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5950: 		   $cdom,$cnum);
 5951:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5952: 	return 'error: '.$reply;
 5953:     } else {
 5954: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5955:     }
 5956:     # Add student role to user
 5957:     my $uurl='/'.$cid;
 5958:     $uurl=~s/\_/\//g;
 5959:     if ($usec) {
 5960: 	$uurl.='/'.$usec;
 5961:     }
 5962:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5963: }
 5964: 
 5965: sub format_name {
 5966:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5967:     my $name;
 5968:     if ($first ne 'lastname') {
 5969: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5970:     } else {
 5971: 	if ($lastname=~/\S/) {
 5972: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5973: 	    $name=~s/\s+,/,/;
 5974: 	} else {
 5975: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5976: 	}
 5977:     }
 5978:     $name=~s/^\s+//;
 5979:     $name=~s/\s+$//;
 5980:     $name=~s/\s+/ /g;
 5981:     return $name;
 5982: }
 5983: 
 5984: # ------------------------------------------------- Write to course preferences
 5985: 
 5986: sub writecoursepref {
 5987:     my ($courseid,%prefs)=@_;
 5988:     $courseid=~s/^\///;
 5989:     $courseid=~s/\_/\//g;
 5990:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5991:     my $chome=homeserver($cnum,$cdomain);
 5992:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5993: 	return 'error: no such course';
 5994:     }
 5995:     my $cstring='';
 5996:     foreach my $pref (keys(%prefs)) {
 5997: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5998:     }
 5999:     $cstring=~s/\&$//;
 6000:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6001: }
 6002: 
 6003: # ---------------------------------------------------------- Make/modify course
 6004: 
 6005: sub createcourse {
 6006:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6007:         $course_owner,$crstype)=@_;
 6008:     $url=&declutter($url);
 6009:     my $cid='';
 6010:     unless (&allowed('ccc',$udom)) {
 6011:         return 'refused';
 6012:     }
 6013: # ------------------------------------------------------------------- Create ID
 6014:    my $uname=int(1+rand(9)).
 6015:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6016:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6017:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6018: # ----------------------------------------------- Make sure that does not exist
 6019:    my $uhome=&homeserver($uname,$udom,'true');
 6020:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6021:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6022:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6023:        $uhome=&homeserver($uname,$udom,'true');       
 6024:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6025:            return 'error: unable to generate unique course-ID';
 6026:        } 
 6027:    }
 6028: # ------------------------------------------------ Check supplied server name
 6029:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6030:     if (! &is_library($course_server)) {
 6031:         return 'error:bad server name '.$course_server;
 6032:     }
 6033: # ------------------------------------------------------------- Make the course
 6034:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6035:                       $course_server);
 6036:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6037:     $uhome=&homeserver($uname,$udom,'true');
 6038:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6039: 	return 'error: no such course';
 6040:     }
 6041: # ----------------------------------------------------------------- Course made
 6042: # log existence
 6043:     my $newcourse = {
 6044:                     $udom.'_'.$uname => {
 6045:                                      description => $description,
 6046:                                      inst_code   => $inst_code,
 6047:                                      owner       => $course_owner,
 6048:                                      type        => $crstype,
 6049:                                                 },
 6050:                     };
 6051:     &courseidput($udom,$newcourse,$uhome,'notime');
 6052: # set toplevel url
 6053:     my $topurl=$url;
 6054:     unless ($nonstandard) {
 6055: # ------------------------------------------ For standard courses, make top url
 6056:         my $mapurl=&clutter($url);
 6057:         if ($mapurl eq '/res/') { $mapurl=''; }
 6058:         $env{'form.initmap'}=(<<ENDINITMAP);
 6059: <map>
 6060: <resource id="1" type="start"></resource>
 6061: <resource id="2" src="$mapurl"></resource>
 6062: <resource id="3" type="finish"></resource>
 6063: <link index="1" from="1" to="2"></link>
 6064: <link index="2" from="2" to="3"></link>
 6065: </map>
 6066: ENDINITMAP
 6067:         $topurl=&declutter(
 6068:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6069:                           );
 6070:     }
 6071: # ----------------------------------------------------------- Write preferences
 6072:     &writecoursepref($udom.'_'.$uname,
 6073:                      ('description' => $description,
 6074:                       'url'         => $topurl));
 6075:     return '/'.$udom.'/'.$uname;
 6076: }
 6077: 
 6078: sub is_course {
 6079:     my ($cdom,$cnum) = @_;
 6080:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6081: 				undef,'.');
 6082:     if (exists($courses{$cdom.'_'.$cnum})) {
 6083:         return 1;
 6084:     }
 6085:     return 0;
 6086: }
 6087: 
 6088: # ---------------------------------------------------------- Assign Custom Role
 6089: 
 6090: sub assigncustomrole {
 6091:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6092:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6093:                        $end,$start,$deleteflag,$selfenroll,$context);
 6094: }
 6095: 
 6096: # ----------------------------------------------------------------- Revoke Role
 6097: 
 6098: sub revokerole {
 6099:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6100:     my $now=time;
 6101:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6102: }
 6103: 
 6104: # ---------------------------------------------------------- Revoke Custom Role
 6105: 
 6106: sub revokecustomrole {
 6107:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6108:     my $now=time;
 6109:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6110:            $deleteflag,$selfenroll,$context);
 6111: }
 6112: 
 6113: # ------------------------------------------------------------ Disk usage
 6114: sub diskusage {
 6115:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6116:     $directorypath =~ s/\/$//;
 6117:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6118:                        .&escape($getpropath).':'.&escape($uname).':'
 6119:                        .&escape($udom),homeserver($uname,$udom));
 6120:     if ($listing eq 'unknown_cmd') {
 6121:         if ($getpropath) {
 6122:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6123:         }
 6124:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6125:     }
 6126:     return $listing;
 6127: }
 6128: 
 6129: sub is_locked {
 6130:     my ($file_name, $domain, $user) = @_;
 6131:     my @check;
 6132:     my $is_locked;
 6133:     push @check, $file_name;
 6134:     my %locked = &get('file_permissions',\@check,
 6135: 		      $env{'user.domain'},$env{'user.name'});
 6136:     my ($tmp)=keys(%locked);
 6137:     if ($tmp=~/^error:/) { undef(%locked); }
 6138:     
 6139:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6140:         $is_locked = 'false';
 6141:         foreach my $entry (@{$locked{$file_name}}) {
 6142:            if (ref($entry) eq 'ARRAY') { 
 6143:                $is_locked = 'true';
 6144:                last;
 6145:            }
 6146:        }
 6147:     } else {
 6148:         $is_locked = 'false';
 6149:     }
 6150: }
 6151: 
 6152: sub declutter_portfile {
 6153:     my ($file) = @_;
 6154:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6155:     return $file;
 6156: }
 6157: 
 6158: # ------------------------------------------------------------- Mark as Read Only
 6159: 
 6160: sub mark_as_readonly {
 6161:     my ($domain,$user,$files,$what) = @_;
 6162:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6163:     my ($tmp)=keys(%current_permissions);
 6164:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6165:     foreach my $file (@{$files}) {
 6166: 	$file = &declutter_portfile($file);
 6167:         push(@{$current_permissions{$file}},$what);
 6168:     }
 6169:     &put('file_permissions',\%current_permissions,$domain,$user);
 6170:     return;
 6171: }
 6172: 
 6173: # ------------------------------------------------------------Save Selected Files
 6174: 
 6175: sub save_selected_files {
 6176:     my ($user, $path, @files) = @_;
 6177:     my $filename = $user."savedfiles";
 6178:     my @other_files = &files_not_in_path($user, $path);
 6179:     open (OUT, '>'.$tmpdir.$filename);
 6180:     foreach my $file (@files) {
 6181:         print (OUT $env{'form.currentpath'}.$file."\n");
 6182:     }
 6183:     foreach my $file (@other_files) {
 6184:         print (OUT $file."\n");
 6185:     }
 6186:     close (OUT);
 6187:     return 'ok';
 6188: }
 6189: 
 6190: sub clear_selected_files {
 6191:     my ($user) = @_;
 6192:     my $filename = $user."savedfiles";
 6193:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6194:     print (OUT undef);
 6195:     close (OUT);
 6196:     return ("ok");    
 6197: }
 6198: 
 6199: sub files_in_path {
 6200:     my ($user, $path) = @_;
 6201:     my $filename = $user."savedfiles";
 6202:     my %return_files;
 6203:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6204:     while (my $line_in = <IN>) {
 6205:         chomp ($line_in);
 6206:         my @paths_and_file = split (m!/!, $line_in);
 6207:         my $file_part = pop (@paths_and_file);
 6208:         my $path_part = join ('/', @paths_and_file);
 6209:         $path_part.='/';
 6210:         my $path_and_file = $path_part.$file_part;
 6211:         if ($path_part eq $path) {
 6212:             $return_files{$file_part}= 'selected';
 6213:         }
 6214:     }
 6215:     close (IN);
 6216:     return (\%return_files);
 6217: }
 6218: 
 6219: # called in portfolio select mode, to show files selected NOT in current directory
 6220: sub files_not_in_path {
 6221:     my ($user, $path) = @_;
 6222:     my $filename = $user."savedfiles";
 6223:     my @return_files;
 6224:     my $path_part;
 6225:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6226:     while (my $line = <IN>) {
 6227:         #ok, I know it's clunky, but I want it to work
 6228:         my @paths_and_file = split(m|/|, $line);
 6229:         my $file_part = pop(@paths_and_file);
 6230:         chomp($file_part);
 6231:         my $path_part = join('/', @paths_and_file);
 6232:         $path_part .= '/';
 6233:         my $path_and_file = $path_part.$file_part;
 6234:         if ($path_part ne $path) {
 6235:             push(@return_files, ($path_and_file));
 6236:         }
 6237:     }
 6238:     close(OUT);
 6239:     return (@return_files);
 6240: }
 6241: 
 6242: #----------------------------------------------Get portfolio file permissions
 6243: 
 6244: sub get_portfile_permissions {
 6245:     my ($domain,$user) = @_;
 6246:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6247:     my ($tmp)=keys(%current_permissions);
 6248:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6249:     return \%current_permissions;
 6250: }
 6251: 
 6252: #---------------------------------------------Get portfolio file access controls
 6253: 
 6254: sub get_access_controls {
 6255:     my ($current_permissions,$group,$file) = @_;
 6256:     my %access;
 6257:     my $real_file = $file;
 6258:     $file =~ s/\.meta$//;
 6259:     if (defined($file)) {
 6260:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6261:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6262:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6263:             }
 6264:         }
 6265:     } else {
 6266:         foreach my $key (keys(%{$current_permissions})) {
 6267:             if ($key =~ /\0accesscontrol$/) {
 6268:                 if (defined($group)) {
 6269:                     if ($key !~ m-^\Q$group\E/-) {
 6270:                         next;
 6271:                     }
 6272:                 }
 6273:                 my ($fullpath) = split(/\0/,$key);
 6274:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6275:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6276:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6277:                     }
 6278:                 }
 6279:             }
 6280:         }
 6281:     }
 6282:     return %access;
 6283: }
 6284: 
 6285: sub modify_access_controls {
 6286:     my ($file_name,$changes,$domain,$user)=@_;
 6287:     my ($outcome,$deloutcome);
 6288:     my %store_permissions;
 6289:     my %new_values;
 6290:     my %new_control;
 6291:     my %translation;
 6292:     my @deletions = ();
 6293:     my $now = time;
 6294:     if (exists($$changes{'activate'})) {
 6295:         if (ref($$changes{'activate'}) eq 'HASH') {
 6296:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6297:             my $numnew = scalar(@newitems);
 6298:             for (my $i=0; $i<$numnew; $i++) {
 6299:                 my $newkey = $newitems[$i];
 6300:                 my $newid = &Apache::loncommon::get_cgi_id();
 6301:                 if ($newkey =~ /^\d+:/) { 
 6302:                     $newkey =~ s/^(\d+)/$newid/;
 6303:                     $translation{$1} = $newid;
 6304:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6305:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6306:                     $translation{$1} = $newid;
 6307:                 }
 6308:                 $new_values{$file_name."\0".$newkey} = 
 6309:                                           $$changes{'activate'}{$newitems[$i]};
 6310:                 $new_control{$newkey} = $now;
 6311:             }
 6312:         }
 6313:     }
 6314:     my %todelete;
 6315:     my %changed_items;
 6316:     foreach my $action ('delete','update') {
 6317:         if (exists($$changes{$action})) {
 6318:             if (ref($$changes{$action}) eq 'HASH') {
 6319:                 foreach my $key (keys(%{$$changes{$action}})) {
 6320:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6321:                     if ($action eq 'delete') { 
 6322:                         $todelete{$itemnum} = 1;
 6323:                     } else {
 6324:                         $changed_items{$itemnum} = $key;
 6325:                     }
 6326:                 }
 6327:             }
 6328:         }
 6329:     }
 6330:     # get lock on access controls for file.
 6331:     my $lockhash = {
 6332:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6333:                                                        ':'.$env{'user.domain'},
 6334:                    }; 
 6335:     my $tries = 0;
 6336:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6337:    
 6338:     while (($gotlock ne 'ok') && $tries <3) {
 6339:         $tries ++;
 6340:         sleep 1;
 6341:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6342:     }
 6343:     if ($gotlock eq 'ok') {
 6344:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6345:         my ($tmp)=keys(%curr_permissions);
 6346:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6347:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6348:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6349:             if (ref($curr_controls) eq 'HASH') {
 6350:                 foreach my $control_item (keys(%{$curr_controls})) {
 6351:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6352:                     if (defined($todelete{$itemnum})) {
 6353:                         push(@deletions,$file_name."\0".$control_item);
 6354:                     } else {
 6355:                         if (defined($changed_items{$itemnum})) {
 6356:                             $new_control{$changed_items{$itemnum}} = $now;
 6357:                             push(@deletions,$file_name."\0".$control_item);
 6358:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6359:                         } else {
 6360:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6361:                         }
 6362:                     }
 6363:                 }
 6364:             }
 6365:         }
 6366:         my ($group);
 6367:         if (&is_course($domain,$user)) {
 6368:             ($group,my $file) = split(/\//,$file_name,2);
 6369:         }
 6370:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6371:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6372:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6373:         #  remove lock
 6374:         my @del_lock = ($file_name."\0".'locked_access_records');
 6375:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6376:         my $sqlresult =
 6377:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6378:                                     $group);
 6379:     } else {
 6380:         $outcome = "error: could not obtain lockfile\n";  
 6381:     }
 6382:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6383: }
 6384: 
 6385: sub make_public_indefinitely {
 6386:     my ($requrl) = @_;
 6387:     my $now = time;
 6388:     my $action = 'activate';
 6389:     my $aclnum = 0;
 6390:     if (&is_portfolio_url($requrl)) {
 6391:         my (undef,$udom,$unum,$file_name,$group) =
 6392:             &parse_portfolio_url($requrl);
 6393:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6394:         my %access_controls = &get_access_controls($current_perms,
 6395:                                                    $group,$file_name);
 6396:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6397:             my ($num,$scope,$end,$start) = 
 6398:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6399:             if ($scope eq 'public') {
 6400:                 if ($start <= $now && $end == 0) {
 6401:                     $action = 'none';
 6402:                 } else {
 6403:                     $action = 'update';
 6404:                     $aclnum = $num;
 6405:                 }
 6406:                 last;
 6407:             }
 6408:         }
 6409:         if ($action eq 'none') {
 6410:              return 'ok';
 6411:         } else {
 6412:             my %changes;
 6413:             my $newend = 0;
 6414:             my $newstart = $now;
 6415:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6416:             $changes{$action}{$newkey} = {
 6417:                 type => 'public',
 6418:                 time => {
 6419:                     start => $newstart,
 6420:                     end   => $newend,
 6421:                 },
 6422:             };
 6423:             my ($outcome,$deloutcome,$new_values,$translation) =
 6424:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6425:             return $outcome;
 6426:         }
 6427:     } else {
 6428:         return 'invalid';
 6429:     }
 6430: }
 6431: 
 6432: #------------------------------------------------------Get Marked as Read Only
 6433: 
 6434: sub get_marked_as_readonly {
 6435:     my ($domain,$user,$what,$group) = @_;
 6436:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6437:     my @readonly_files;
 6438:     my $cmp1=$what;
 6439:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6440:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6441:         if (defined($group)) {
 6442:             if ($file_name !~ m-^\Q$group\E/-) {
 6443:                 next;
 6444:             }
 6445:         }
 6446:         if (ref($value) eq "ARRAY"){
 6447:             foreach my $stored_what (@{$value}) {
 6448:                 my $cmp2=$stored_what;
 6449:                 if (ref($stored_what) eq 'ARRAY') {
 6450:                     $cmp2=join('',@{$stored_what});
 6451:                 }
 6452:                 if ($cmp1 eq $cmp2) {
 6453:                     push(@readonly_files, $file_name);
 6454:                     last;
 6455:                 } elsif (!defined($what)) {
 6456:                     push(@readonly_files, $file_name);
 6457:                     last;
 6458:                 }
 6459:             }
 6460:         }
 6461:     }
 6462:     return @readonly_files;
 6463: }
 6464: #-----------------------------------------------------------Get Marked as Read Only Hash
 6465: 
 6466: sub get_marked_as_readonly_hash {
 6467:     my ($current_permissions,$group,$what) = @_;
 6468:     my %readonly_files;
 6469:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6470:         if (defined($group)) {
 6471:             if ($file_name !~ m-^\Q$group\E/-) {
 6472:                 next;
 6473:             }
 6474:         }
 6475:         if (ref($value) eq "ARRAY"){
 6476:             foreach my $stored_what (@{$value}) {
 6477:                 if (ref($stored_what) eq 'ARRAY') {
 6478:                     foreach my $lock_descriptor(@{$stored_what}) {
 6479:                         if ($lock_descriptor eq 'graded') {
 6480:                             $readonly_files{$file_name} = 'graded';
 6481:                         } elsif ($lock_descriptor eq 'handback') {
 6482:                             $readonly_files{$file_name} = 'handback';
 6483:                         } else {
 6484:                             if (!exists($readonly_files{$file_name})) {
 6485:                                 $readonly_files{$file_name} = 'locked';
 6486:                             }
 6487:                         }
 6488:                     }
 6489:                 } 
 6490:             }
 6491:         } 
 6492:     }
 6493:     return %readonly_files;
 6494: }
 6495: # ------------------------------------------------------------ Unmark as Read Only
 6496: 
 6497: sub unmark_as_readonly {
 6498:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6499:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6500:     my ($domain,$user,$what,$file_name,$group) = @_;
 6501:     $file_name = &declutter_portfile($file_name);
 6502:     my $symb_crs = $what;
 6503:     if (ref($what)) { $symb_crs=join('',@$what); }
 6504:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6505:     my ($tmp)=keys(%current_permissions);
 6506:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6507:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6508:     foreach my $file (@readonly_files) {
 6509: 	my $clean_file = &declutter_portfile($file);
 6510: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6511: 	my $current_locks = $current_permissions{$file};
 6512:         my @new_locks;
 6513:         my @del_keys;
 6514:         if (ref($current_locks) eq "ARRAY"){
 6515:             foreach my $locker (@{$current_locks}) {
 6516:                 my $compare=$locker;
 6517:                 if (ref($locker) eq 'ARRAY') {
 6518:                     $compare=join('',@{$locker});
 6519:                     if ($compare ne $symb_crs) {
 6520:                         push(@new_locks, $locker);
 6521:                     }
 6522:                 }
 6523:             }
 6524:             if (scalar(@new_locks) > 0) {
 6525:                 $current_permissions{$file} = \@new_locks;
 6526:             } else {
 6527:                 push(@del_keys, $file);
 6528:                 &del('file_permissions',\@del_keys, $domain, $user);
 6529:                 delete($current_permissions{$file});
 6530:             }
 6531:         }
 6532:     }
 6533:     &put('file_permissions',\%current_permissions,$domain,$user);
 6534:     return;
 6535: }
 6536: 
 6537: # ------------------------------------------------------------ Directory lister
 6538: 
 6539: sub dirlist {
 6540:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6541:     $uri=~s/^\///;
 6542:     $uri=~s/\/$//;
 6543:     my ($udom, $uname);
 6544:     if ($getuserdir) {
 6545:         $udom = $userdomain;
 6546:         $uname = $username;
 6547:     } else {
 6548:         (undef,$udom,$uname)=split(/\//,$uri);
 6549:         if(defined($userdomain)) {
 6550:             $udom = $userdomain;
 6551:         }
 6552:         if(defined($username)) {
 6553:             $uname = $username;
 6554:         }
 6555:     }
 6556:     my ($dirRoot,$listing,@listing_results);
 6557: 
 6558:     $dirRoot = $perlvar{'lonDocRoot'};
 6559:     if (defined($getpropath)) {
 6560:         $dirRoot = &propath($udom,$uname);
 6561:         $dirRoot =~ s/\/$//;
 6562:     } elsif (defined($getuserdir)) {
 6563:         my $subdir=$uname.'__';
 6564:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6565:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6566:                    ."/$udom/$subdir/$uname";
 6567:     } elsif (defined($alternateRoot)) {
 6568:         $dirRoot = $alternateRoot;
 6569:     }
 6570: 
 6571:     if($udom) {
 6572:         if($uname) {
 6573:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6574:                               .$getuserdir.':'.&escape($dirRoot)
 6575:                               .':'.&escape($uname).':'.&escape($udom),
 6576:                               &homeserver($uname,$udom));
 6577:             if ($listing eq 'unknown_cmd') {
 6578:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6579:                                   &homeserver($uname,$udom));
 6580:             } else {
 6581:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6582:             }
 6583:             if ($listing eq 'unknown_cmd') {
 6584:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6585: 				  &homeserver($uname,$udom));
 6586:                 @listing_results = split(/:/,$listing);
 6587:             } else {
 6588:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6589:             }
 6590:             return @listing_results;
 6591:         } elsif(!$alternateRoot) {
 6592:             my %allusers;
 6593: 	    my %servers = &get_servers($udom,'library');
 6594:  	    foreach my $tryserver (keys(%servers)) {
 6595:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6596:                                   &escape($udom),$tryserver);
 6597:                 if ($listing eq 'unknown_cmd') {
 6598: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6599: 				      $udom, $tryserver);
 6600:                 } else {
 6601:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6602:                 }
 6603: 		if ($listing eq 'unknown_cmd') {
 6604: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6605: 				      $udom, $tryserver);
 6606: 		    @listing_results = split(/:/,$listing);
 6607: 		} else {
 6608: 		    @listing_results =
 6609: 			map { &unescape($_); } split(/:/,$listing);
 6610: 		}
 6611: 		if ($listing_results[0] ne 'no_such_dir' && 
 6612: 		    $listing_results[0] ne 'empty'       &&
 6613: 		    $listing_results[0] ne 'con_lost') {
 6614: 		    foreach my $line (@listing_results) {
 6615: 			my ($entry) = split(/&/,$line,2);
 6616: 			$allusers{$entry} = 1;
 6617: 		    }
 6618: 		}
 6619:             }
 6620:             my $alluserstr='';
 6621:             foreach my $user (sort(keys(%allusers))) {
 6622:                 $alluserstr.=$user.'&user:';
 6623:             }
 6624:             $alluserstr=~s/:$//;
 6625:             return split(/:/,$alluserstr);
 6626:         } else {
 6627:             return ('missing user name');
 6628:         }
 6629:     } elsif(!defined($getpropath)) {
 6630:         my @all_domains = sort(&all_domains());
 6631:         foreach my $domain (@all_domains) {
 6632:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6633:         }
 6634:         return @all_domains;
 6635:     } else {
 6636:         return ('missing domain');
 6637:     }
 6638: }
 6639: 
 6640: # --------------------------------------------- GetFileTimestamp
 6641: # This function utilizes dirlist and returns the date stamp for
 6642: # when it was last modified.  It will also return an error of -1
 6643: # if an error occurs
 6644: 
 6645: sub GetFileTimestamp {
 6646:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6647:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6648:     $studentName   = &LONCAPA::clean_username($studentName);
 6649:     my ($fileStat) = 
 6650:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6651:                                  undef,$getuserdir);
 6652:     my @stats = split('&', $fileStat);
 6653:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6654:         # @stats contains first the filename, then the stat output
 6655:         return $stats[10]; # so this is 10 instead of 9.
 6656:     } else {
 6657:         return -1;
 6658:     }
 6659: }
 6660: 
 6661: sub stat_file {
 6662:     my ($uri) = @_;
 6663:     $uri = &clutter_with_no_wrapper($uri);
 6664: 
 6665:     my ($udom,$uname,$file);
 6666:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6667: 	($udom,$uname,$file) =
 6668: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6669: 	$file = 'userfiles/'.$file;
 6670:     }
 6671:     if ($uri =~ m-^/res/-) {
 6672: 	($udom,$uname) = 
 6673: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6674: 	$file = $uri;
 6675:     }
 6676: 
 6677:     if (!$udom || !$uname || !$file) {
 6678: 	# unable to handle the uri
 6679: 	return ();
 6680:     }
 6681:     my $getpropath;
 6682:     if ($file =~ /^userfiles\//) {
 6683:         $getpropath = 1;
 6684:     }
 6685:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6686:     my @stats = split('&', $result);
 6687:     
 6688:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6689: 	shift(@stats); #filename is first
 6690: 	return @stats;
 6691:     }
 6692:     return ();
 6693: }
 6694: 
 6695: # -------------------------------------------------------- Value of a Condition
 6696: 
 6697: # gets the value of a specific preevaluated condition
 6698: #    stored in the string  $env{user.state.<cid>}
 6699: # or looks up a condition reference in the bighash and if if hasn't
 6700: # already been evaluated recurses into docondval to get the value of
 6701: # the condition, then memoizing it to 
 6702: #   $env{user.state.<cid>.<condition>}
 6703: sub directcondval {
 6704:     my $number=shift;
 6705:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6706: 	&Apache::lonuserstate::evalstate();
 6707:     }
 6708:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6709: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6710:     } elsif ($number =~ /^_/) {
 6711: 	my $sub_condition;
 6712: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6713: 		&GDBM_READER(),0640)) {
 6714: 	    $sub_condition=$bighash{'conditions'.$number};
 6715: 	    untie(%bighash);
 6716: 	}
 6717: 	my $value = &docondval($sub_condition);
 6718: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6719: 	return $value;
 6720:     }
 6721:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6722:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6723:     } else {
 6724:        return 2;
 6725:     }
 6726: }
 6727: 
 6728: # get the collection of conditions for this resource
 6729: sub condval {
 6730:     my $condidx=shift;
 6731:     my $allpathcond='';
 6732:     foreach my $cond (split(/\|/,$condidx)) {
 6733: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6734: 	    $allpathcond.=
 6735: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6736: 	}
 6737:     }
 6738:     $allpathcond=~s/\|$//;
 6739:     return &docondval($allpathcond);
 6740: }
 6741: 
 6742: #evaluates an expression of conditions
 6743: sub docondval {
 6744:     my ($allpathcond) = @_;
 6745:     my $result=0;
 6746:     if ($env{'request.course.id'}
 6747: 	&& defined($allpathcond)) {
 6748: 	my $operand='|';
 6749: 	my @stack;
 6750: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6751: 	    if ($chunk eq '(') {
 6752: 		push @stack,($operand,$result);
 6753: 	    } elsif ($chunk eq ')') {
 6754: 		my $before=pop @stack;
 6755: 		if (pop @stack eq '&') {
 6756: 		    $result=$result>$before?$before:$result;
 6757: 		} else {
 6758: 		    $result=$result>$before?$result:$before;
 6759: 		}
 6760: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6761: 		$operand=$chunk;
 6762: 	    } else {
 6763: 		my $new=directcondval($chunk);
 6764: 		if ($operand eq '&') {
 6765: 		    $result=$result>$new?$new:$result;
 6766: 		} else {
 6767: 		    $result=$result>$new?$result:$new;
 6768: 		}
 6769: 	    }
 6770: 	}
 6771:     }
 6772:     return $result;
 6773: }
 6774: 
 6775: # ---------------------------------------------------- Devalidate courseresdata
 6776: 
 6777: sub devalidatecourseresdata {
 6778:     my ($coursenum,$coursedomain)=@_;
 6779:     my $hashid=$coursenum.':'.$coursedomain;
 6780:     &devalidate_cache_new('courseres',$hashid);
 6781: }
 6782: 
 6783: 
 6784: # --------------------------------------------------- Course Resourcedata Query
 6785: #
 6786: #  Parameters:
 6787: #      $coursenum    - Number of the course.
 6788: #      $coursedomain - Domain at which the course was created.
 6789: #  Returns:
 6790: #     A hash of the course parameters along (I think) with timestamps
 6791: #     and version info.
 6792: 
 6793: sub get_courseresdata {
 6794:     my ($coursenum,$coursedomain)=@_;
 6795:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6796:     my $hashid=$coursenum.':'.$coursedomain;
 6797:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6798:     my %dumpreply;
 6799:     unless (defined($cached)) {
 6800: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6801: 	$result=\%dumpreply;
 6802: 	my ($tmp) = keys(%dumpreply);
 6803: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6804: 	    &do_cache_new('courseres',$hashid,$result,600);
 6805: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6806: 	    return $tmp;
 6807: 	} elsif ($tmp =~ /^(error)/) {
 6808: 	    $result=undef;
 6809: 	    &do_cache_new('courseres',$hashid,$result,600);
 6810: 	}
 6811:     }
 6812:     return $result;
 6813: }
 6814: 
 6815: sub devalidateuserresdata {
 6816:     my ($uname,$udom)=@_;
 6817:     my $hashid="$udom:$uname";
 6818:     &devalidate_cache_new('userres',$hashid);
 6819: }
 6820: 
 6821: sub get_userresdata {
 6822:     my ($uname,$udom)=@_;
 6823:     #most student don\'t have any data set, check if there is some data
 6824:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6825: 
 6826:     my $hashid="$udom:$uname";
 6827:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6828:     if (!defined($cached)) {
 6829: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6830: 	$result=\%resourcedata;
 6831: 	&do_cache_new('userres',$hashid,$result,600);
 6832:     }
 6833:     my ($tmp)=keys(%$result);
 6834:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6835: 	return $result;
 6836:     }
 6837:     #error 2 occurs when the .db doesn't exist
 6838:     if ($tmp!~/error: 2 /) {
 6839: 	&logthis("<font color=\"blue\">WARNING:".
 6840: 		 " Trying to get resource data for ".
 6841: 		 $uname." at ".$udom.": ".
 6842: 		 $tmp."</font>");
 6843:     } elsif ($tmp=~/error: 2 /) {
 6844: 	#&EXT_cache_set($udom,$uname);
 6845: 	&do_cache_new('userres',$hashid,undef,600);
 6846: 	undef($tmp); # not really an error so don't send it back
 6847:     }
 6848:     return $tmp;
 6849: }
 6850: #----------------------------------------------- resdata - return resource data
 6851: #  Purpose:
 6852: #    Return resource data for either users or for a course.
 6853: #  Parameters:
 6854: #     $name      - Course/user name.
 6855: #     $domain    - Name of the domain the user/course is registered on.
 6856: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6857: #     @which     - Array of names of resources desired.
 6858: #  Returns:
 6859: #     The value of the first reasource in @which that is found in the
 6860: #     resource hash.
 6861: #  Exceptional Conditions:
 6862: #     If the $type passed in is not valid (not the string 'course' or 
 6863: #     'user', an undefined  reference is returned.
 6864: #     If none of the resources are found, an undef is returned
 6865: sub resdata {
 6866:     my ($name,$domain,$type,@which)=@_;
 6867:     my $result;
 6868:     if ($type eq 'course') {
 6869: 	$result=&get_courseresdata($name,$domain);
 6870:     } elsif ($type eq 'user') {
 6871: 	$result=&get_userresdata($name,$domain);
 6872:     }
 6873:     if (!ref($result)) { return $result; }    
 6874:     foreach my $item (@which) {
 6875: 	if (defined($result->{$item->[0]})) {
 6876: 	    return [$result->{$item->[0]},$item->[1]];
 6877: 	}
 6878:     }
 6879:     return undef;
 6880: }
 6881: 
 6882: #
 6883: # EXT resource caching routines
 6884: #
 6885: 
 6886: sub clear_EXT_cache_status {
 6887:     &delenv('cache.EXT.');
 6888: }
 6889: 
 6890: sub EXT_cache_status {
 6891:     my ($target_domain,$target_user) = @_;
 6892:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6893:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6894:         # We know already the user has no data
 6895:         return 1;
 6896:     } else {
 6897:         return 0;
 6898:     }
 6899: }
 6900: 
 6901: sub EXT_cache_set {
 6902:     my ($target_domain,$target_user) = @_;
 6903:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6904:     #&appenv({$cachename => time});
 6905: }
 6906: 
 6907: # --------------------------------------------------------- Value of a Variable
 6908: sub EXT {
 6909: 
 6910:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6911:     unless ($varname) { return ''; }
 6912:     #get real user name/domain, courseid and symb
 6913:     my $courseid;
 6914:     my $publicuser;
 6915:     if ($symbparm) {
 6916: 	$symbparm=&get_symb_from_alias($symbparm);
 6917:     }
 6918:     if (!($uname && $udom)) {
 6919:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6920:       if (!$symbparm) {	$symbparm=$cursymb; }
 6921:     } else {
 6922: 	$courseid=$env{'request.course.id'};
 6923:     }
 6924:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6925:     my $rest;
 6926:     if (defined($therest[0])) {
 6927:        $rest=join('.',@therest);
 6928:     } else {
 6929:        $rest='';
 6930:     }
 6931: 
 6932:     my $qualifierrest=$qualifier;
 6933:     if ($rest) { $qualifierrest.='.'.$rest; }
 6934:     my $spacequalifierrest=$space;
 6935:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6936:     if ($realm eq 'user') {
 6937: # --------------------------------------------------------------- user.resource
 6938: 	if ($space eq 'resource') {
 6939: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6940: 		  || defined($Apache::lonhomework::parsing_a_task))
 6941: 		 &&
 6942: 		 ($symbparm eq &symbread()) ) {	
 6943: 		# if we are in the middle of processing the resource the
 6944: 		# get the value we are planning on committing
 6945:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6946:                     return $Apache::lonhomework::results{$qualifierrest};
 6947:                 } else {
 6948:                     return $Apache::lonhomework::history{$qualifierrest};
 6949:                 }
 6950: 	    } else {
 6951: 		my %restored;
 6952: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6953: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6954: 		} else {
 6955: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6956: 		}
 6957: 		return $restored{$qualifierrest};
 6958: 	    }
 6959: # ----------------------------------------------------------------- user.access
 6960:         } elsif ($space eq 'access') {
 6961: 	    # FIXME - not supporting calls for a specific user
 6962:             return &allowed($qualifier,$rest);
 6963: # ------------------------------------------ user.preferences, user.environment
 6964:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6965: 	    if (($uname eq $env{'user.name'}) &&
 6966: 		($udom eq $env{'user.domain'})) {
 6967: 		return $env{join('.',('environment',$qualifierrest))};
 6968: 	    } else {
 6969: 		my %returnhash;
 6970: 		if (!$publicuser) {
 6971: 		    %returnhash=&userenvironment($udom,$uname,
 6972: 						 $qualifierrest);
 6973: 		}
 6974: 		return $returnhash{$qualifierrest};
 6975: 	    }
 6976: # ----------------------------------------------------------------- user.course
 6977:         } elsif ($space eq 'course') {
 6978: 	    # FIXME - not supporting calls for a specific user
 6979:             return $env{join('.',('request.course',$qualifier))};
 6980: # ------------------------------------------------------------------- user.role
 6981:         } elsif ($space eq 'role') {
 6982: 	    # FIXME - not supporting calls for a specific user
 6983:             my ($role,$where)=split(/\./,$env{'request.role'});
 6984:             if ($qualifier eq 'value') {
 6985: 		return $role;
 6986:             } elsif ($qualifier eq 'extent') {
 6987:                 return $where;
 6988:             }
 6989: # ----------------------------------------------------------------- user.domain
 6990:         } elsif ($space eq 'domain') {
 6991:             return $udom;
 6992: # ------------------------------------------------------------------- user.name
 6993:         } elsif ($space eq 'name') {
 6994:             return $uname;
 6995: # ---------------------------------------------------- Any other user namespace
 6996:         } else {
 6997: 	    my %reply;
 6998: 	    if (!$publicuser) {
 6999: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7000: 	    }
 7001: 	    return $reply{$qualifierrest};
 7002:         }
 7003:     } elsif ($realm eq 'query') {
 7004: # ---------------------------------------------- pull stuff out of query string
 7005:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7006: 						[$spacequalifierrest]);
 7007: 	return $env{'form.'.$spacequalifierrest}; 
 7008:    } elsif ($realm eq 'request') {
 7009: # ------------------------------------------------------------- request.browser
 7010:         if ($space eq 'browser') {
 7011: 	    if ($qualifier eq 'textremote') {
 7012: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7013: 		    return 1;
 7014: 		} else {
 7015: 		    return 0;
 7016: 		}
 7017: 	    } else {
 7018: 		return $env{'browser.'.$qualifier};
 7019: 	    }
 7020: # ------------------------------------------------------------ request.filename
 7021:         } else {
 7022:             return $env{'request.'.$spacequalifierrest};
 7023:         }
 7024:     } elsif ($realm eq 'course') {
 7025: # ---------------------------------------------------------- course.description
 7026:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7027:     } elsif ($realm eq 'resource') {
 7028: 
 7029: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7030: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7031: 	}
 7032: 
 7033: 	if ($space eq 'title') {
 7034: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7035: 	    return &gettitle($symbparm);
 7036: 	}
 7037: 	
 7038: 	if ($space eq 'map') {
 7039: 	    my ($map) = &decode_symb($symbparm);
 7040: 	    return &symbread($map);
 7041: 	}
 7042: 	if ($space eq 'filename') {
 7043: 	    if ($symbparm) {
 7044: 		return &clutter((&decode_symb($symbparm))[2]);
 7045: 	    }
 7046: 	    return &hreflocation('',$env{'request.filename'});
 7047: 	}
 7048: 
 7049: 	my ($section, $group, @groups);
 7050: 	my ($courselevelm,$courselevel);
 7051: 	if ($symbparm && defined($courseid) && 
 7052: 	    $courseid eq $env{'request.course.id'}) {
 7053: 
 7054: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7055: 
 7056: # ----------------------------------------------------- Cascading lookup scheme
 7057: 	    my $symbp=$symbparm;
 7058: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7059: 
 7060: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7061: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7062: 
 7063: 	    if (($env{'user.name'} eq $uname) &&
 7064: 		($env{'user.domain'} eq $udom)) {
 7065: 		$section=$env{'request.course.sec'};
 7066:                 @groups = split(/:/,$env{'request.course.groups'});  
 7067:                 @groups=&sort_course_groups($courseid,@groups); 
 7068: 	    } else {
 7069: 		if (! defined($usection)) {
 7070: 		    $section=&getsection($udom,$uname,$courseid);
 7071: 		} else {
 7072: 		    $section = $usection;
 7073: 		}
 7074:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7075: 	    }
 7076: 
 7077: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7078: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7079: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7080: 
 7081: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7082: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7083: 	    $courselevelm=$courseid.'.'.$mapparm;
 7084: 
 7085: # ----------------------------------------------------------- first, check user
 7086: 
 7087: 	    my $userreply=&resdata($uname,$udom,'user',
 7088: 				       ([$courselevelr,'resource'],
 7089: 					[$courselevelm,'map'     ],
 7090: 					[$courselevel, 'course'  ]));
 7091: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7092: 
 7093: # ------------------------------------------------ second, check some of course
 7094:             my $coursereply;
 7095:             if (@groups > 0) {
 7096:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7097:                                        $mapparm,$spacequalifierrest);
 7098:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7099:             }
 7100: 
 7101: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7102: 				  $env{'course.'.$courseid.'.domain'},
 7103: 				  'course',
 7104: 				  ([$seclevelr,   'resource'],
 7105: 				   [$seclevelm,   'map'     ],
 7106: 				   [$seclevel,    'course'  ],
 7107: 				   [$courselevelr,'resource']));
 7108: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7109: 
 7110: # ------------------------------------------------------ third, check map parms
 7111: 	    my %parmhash=();
 7112: 	    my $thisparm='';
 7113: 	    if (tie(%parmhash,'GDBM_File',
 7114: 		    $env{'request.course.fn'}.'_parms.db',
 7115: 		    &GDBM_READER(),0640)) {
 7116: 		$thisparm=$parmhash{$symbparm};
 7117: 		untie(%parmhash);
 7118: 	    }
 7119: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7120: 	}
 7121: # ------------------------------------------ fourth, look in resource metadata
 7122: 
 7123: 	$spacequalifierrest=~s/\./\_/;
 7124: 	my $filename;
 7125: 	if (!$symbparm) { $symbparm=&symbread(); }
 7126: 	if ($symbparm) {
 7127: 	    $filename=(&decode_symb($symbparm))[2];
 7128: 	} else {
 7129: 	    $filename=$env{'request.filename'};
 7130: 	}
 7131: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7132: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7133: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7134: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7135: 
 7136: # ---------------------------------------------- fourth, look in rest of course
 7137: 	if ($symbparm && defined($courseid) && 
 7138: 	    $courseid eq $env{'request.course.id'}) {
 7139: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7140: 				     $env{'course.'.$courseid.'.domain'},
 7141: 				     'course',
 7142: 				     ([$courselevelm,'map'   ],
 7143: 				      [$courselevel, 'course']));
 7144: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7145: 	}
 7146: # ------------------------------------------------------------------ Cascade up
 7147: 	unless ($space eq '0') {
 7148: 	    my @parts=split(/_/,$space);
 7149: 	    my $id=pop(@parts);
 7150: 	    my $part=join('_',@parts);
 7151: 	    if ($part eq '') { $part='0'; }
 7152: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7153: 				 $symbparm,$udom,$uname,$section,1);
 7154: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7155: 	}
 7156: 	if ($recurse) { return undef; }
 7157: 	my $pack_def=&packages_tab_default($filename,$varname);
 7158: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7159: # ---------------------------------------------------- Any other user namespace
 7160:     } elsif ($realm eq 'environment') {
 7161: # ----------------------------------------------------------------- environment
 7162: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7163: 	    return $env{'environment.'.$spacequalifierrest};
 7164: 	} else {
 7165: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7166: 		return '';
 7167: 	    }
 7168: 	    my %returnhash=&userenvironment($udom,$uname,
 7169: 					    $spacequalifierrest);
 7170: 	    return $returnhash{$spacequalifierrest};
 7171: 	}
 7172:     } elsif ($realm eq 'system') {
 7173: # ----------------------------------------------------------------- system.time
 7174: 	if ($space eq 'time') {
 7175: 	    return time;
 7176:         }
 7177:     } elsif ($realm eq 'server') {
 7178: # ----------------------------------------------------------------- system.time
 7179: 	if ($space eq 'name') {
 7180: 	    return $ENV{'SERVER_NAME'};
 7181:         }
 7182:     }
 7183:     return '';
 7184: }
 7185: 
 7186: sub get_reply {
 7187:     my ($reply_value) = @_;
 7188:     if (ref($reply_value) eq 'ARRAY') {
 7189:         if (wantarray) {
 7190: 	    return @$reply_value;
 7191:         }
 7192:         return $reply_value->[0];
 7193:     } else {
 7194:         return $reply_value;
 7195:     }
 7196: }
 7197: 
 7198: sub check_group_parms {
 7199:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7200:     my @groupitems = ();
 7201:     my $resultitem;
 7202:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7203:     foreach my $group (@{$groups}) {
 7204:         foreach my $level (@levels) {
 7205:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7206:              push(@groupitems,[$item,$level->[1]]);
 7207:         }
 7208:     }
 7209:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7210:                             $env{'course.'.$courseid.'.domain'},
 7211:                                      'course',@groupitems);
 7212:     return $coursereply;
 7213: }
 7214: 
 7215: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7216:     my ($courseid,@groups) = @_;
 7217:     @groups = sort(@groups);
 7218:     return @groups;
 7219: }
 7220: 
 7221: sub packages_tab_default {
 7222:     my ($uri,$varname)=@_;
 7223:     my (undef,$part,$name)=split(/\./,$varname);
 7224: 
 7225:     my (@extension,@specifics,$do_default);
 7226:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7227: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7228: 	if ($pack_type eq 'default') {
 7229: 	    $do_default=1;
 7230: 	} elsif ($pack_type eq 'extension') {
 7231: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7232: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7233: 	    # only look at packages defaults for packages that this id is
 7234: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7235: 	}
 7236:     }
 7237:     # first look for a package that matches the requested part id
 7238:     foreach my $package (@specifics) {
 7239: 	my (undef,$pack_type,$pack_part)=@{$package};
 7240: 	next if ($pack_part ne $part);
 7241: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7242: 	    return $packagetab{"$pack_type&$name&default"};
 7243: 	}
 7244:     }
 7245:     # look for any possible matching non extension_ package
 7246:     foreach my $package (@specifics) {
 7247: 	my (undef,$pack_type,$pack_part)=@{$package};
 7248: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7249: 	    return $packagetab{"$pack_type&$name&default"};
 7250: 	}
 7251: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7252: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7253: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7254: 	}
 7255:     }
 7256:     # look for any posible extension_ match
 7257:     foreach my $package (@extension) {
 7258: 	my ($package,$pack_type)=@{$package};
 7259: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7260: 	    return $packagetab{"$pack_type&$name&default"};
 7261: 	}
 7262: 	if (defined($packagetab{$package."&$name&default"})) {
 7263: 	    return $packagetab{$package."&$name&default"};
 7264: 	}
 7265:     }
 7266:     # look for a global default setting
 7267:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7268: 	return $packagetab{"default&$name&default"};
 7269:     }
 7270:     return undef;
 7271: }
 7272: 
 7273: sub add_prefix_and_part {
 7274:     my ($prefix,$part)=@_;
 7275:     my $keyroot;
 7276:     if (defined($prefix) && $prefix !~ /^__/) {
 7277: 	# prefix that has a part already
 7278: 	$keyroot=$prefix;
 7279:     } elsif (defined($prefix)) {
 7280: 	# prefix that is missing a part
 7281: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7282:     } else {
 7283: 	# no prefix at all
 7284: 	if (defined($part)) { $keyroot='_'.$part; }
 7285:     }
 7286:     return $keyroot;
 7287: }
 7288: 
 7289: # ---------------------------------------------------------------- Get metadata
 7290: 
 7291: my %metaentry;
 7292: sub metadata {
 7293:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7294:     $uri=&declutter($uri);
 7295:     # if it is a non metadata possible uri return quickly
 7296:     if (($uri eq '') || 
 7297: 	(($uri =~ m|^/*adm/|) && 
 7298: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7299:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7300: 	return undef;
 7301:     }
 7302:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7303: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7304: 	return undef;
 7305:     }
 7306:     my $filename=$uri;
 7307:     $uri=~s/\.meta$//;
 7308: #
 7309: # Is the metadata already cached?
 7310: # Look at timestamp of caching
 7311: # Everything is cached by the main uri, libraries are never directly cached
 7312: #
 7313:     if (!defined($liburi)) {
 7314: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7315: 	if (defined($cached)) { return $result->{':'.$what}; }
 7316:     }
 7317:     {
 7318: #
 7319: # Is this a recursive call for a library?
 7320: #
 7321: #	if (! exists($metacache{$uri})) {
 7322: #	    $metacache{$uri}={};
 7323: #	}
 7324: 	my $cachetime = 60*60;
 7325:         if ($liburi) {
 7326: 	    $liburi=&declutter($liburi);
 7327:             $filename=$liburi;
 7328:         } else {
 7329: 	    &devalidate_cache_new('meta',$uri);
 7330: 	    undef(%metaentry);
 7331: 	}
 7332:         my %metathesekeys=();
 7333:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7334: 	my $metastring;
 7335: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7336: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7337: 	    $metastring = 
 7338: 		&Apache::lonnet::ssi_body($which,
 7339: 					  ('grade_target' => 'meta'));
 7340: 	    $cachetime = 1; # only want this cached in the child not long term
 7341: 	} elsif ($uri !~ m -^(editupload)/-) {
 7342: 	    my $file=&filelocation('',&clutter($filename));
 7343: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7344: 	    $metastring=&getfile($file);
 7345: 	}
 7346:         my $parser=HTML::LCParser->new(\$metastring);
 7347:         my $token;
 7348:         undef %metathesekeys;
 7349:         while ($token=$parser->get_token) {
 7350: 	    if ($token->[0] eq 'S') {
 7351: 		if (defined($token->[2]->{'package'})) {
 7352: #
 7353: # This is a package - get package info
 7354: #
 7355: 		    my $package=$token->[2]->{'package'};
 7356: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7357: 		    if (defined($token->[2]->{'id'})) { 
 7358: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7359: 		    }
 7360: 		    if ($metaentry{':packages'}) {
 7361: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7362: 		    } else {
 7363: 			$metaentry{':packages'}=$package.$keyroot;
 7364: 		    }
 7365: 		    foreach my $pack_entry (keys(%packagetab)) {
 7366: 			my $part=$keyroot;
 7367: 			$part=~s/^\_//;
 7368: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7369: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7370: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7371: 			    # ignore package.tab specified default values
 7372:                             # here &package_tab_default() will fetch those
 7373: 			    if ($subp eq 'default') { next; }
 7374: 			    my $value=$packagetab{$pack_entry};
 7375: 			    my $unikey;
 7376: 			    if ($pack =~ /_0$/) {
 7377: 				$unikey='parameter_0_'.$name;
 7378: 				$part=0;
 7379: 			    } else {
 7380: 				$unikey='parameter'.$keyroot.'_'.$name;
 7381: 			    }
 7382: 			    if ($subp eq 'display') {
 7383: 				$value.=' [Part: '.$part.']';
 7384: 			    }
 7385: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7386: 			    $metathesekeys{$unikey}=1;
 7387: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7388: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7389: 			    }
 7390: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7391: 				$metaentry{':'.$unikey}=
 7392: 				    $metaentry{':'.$unikey.'.default'};
 7393: 			    }
 7394: 			}
 7395: 		    }
 7396: 		} else {
 7397: #
 7398: # This is not a package - some other kind of start tag
 7399: #
 7400: 		    my $entry=$token->[1];
 7401: 		    my $unikey;
 7402: 		    if ($entry eq 'import') {
 7403: 			$unikey='';
 7404: 		    } else {
 7405: 			$unikey=$entry;
 7406: 		    }
 7407: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7408: 
 7409: 		    if (defined($token->[2]->{'id'})) { 
 7410: 			$unikey.='_'.$token->[2]->{'id'}; 
 7411: 		    }
 7412: 
 7413: 		    if ($entry eq 'import') {
 7414: #
 7415: # Importing a library here
 7416: #
 7417: 			if ($depthcount<20) {
 7418: 			    my $location=$parser->get_text('/import');
 7419: 			    my $dir=$filename;
 7420: 			    $dir=~s|[^/]*$||;
 7421: 			    $location=&filelocation($dir,$location);
 7422: 			    my $metadata = 
 7423: 				&metadata($uri,'keys', $location,$unikey,
 7424: 					  $depthcount+1);
 7425: 			    foreach my $meta (split(',',$metadata)) {
 7426: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7427: 				$metathesekeys{$meta}=1;
 7428: 			    }
 7429: 			}
 7430: 		    } else { 
 7431: 			
 7432: 			if (defined($token->[2]->{'name'})) { 
 7433: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7434: 			}
 7435: 			$metathesekeys{$unikey}=1;
 7436: 			foreach my $param (@{$token->[3]}) {
 7437: 			    $metaentry{':'.$unikey.'.'.$param} =
 7438: 				$token->[2]->{$param};
 7439: 			}
 7440: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7441: 			my $default=$metaentry{':'.$unikey.'.default'};
 7442: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7443: 		 # only ws inside the tag, and not in default, so use default
 7444: 		 # as value
 7445: 			    $metaentry{':'.$unikey}=$default;
 7446: 			} elsif ( $internaltext =~ /\S/ ) {
 7447: 		  # something interesting inside the tag
 7448: 			    $metaentry{':'.$unikey}=$internaltext;
 7449: 			} else {
 7450: 		  # no interesting values, don't set a default
 7451: 			}
 7452: # end of not-a-package not-a-library import
 7453: 		    }
 7454: # end of not-a-package start tag
 7455: 		}
 7456: # the next is the end of "start tag"
 7457: 	    }
 7458: 	}
 7459: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7460: 	$extension = lc($extension);
 7461: 	if ($extension eq 'htm') { $extension='html'; }
 7462: 
 7463: 	foreach my $key (keys(%packagetab)) {
 7464: 	    #no specific packages #how's our extension
 7465: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7466: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7467: 					 \%metathesekeys);
 7468: 	}
 7469: 
 7470: 	if (!exists($metaentry{':packages'})
 7471: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7472: 	    foreach my $key (keys(%packagetab)) {
 7473: 		#no specific packages well let's get default then
 7474: 		if ($key!~/^default&/) { next; }
 7475: 		&metadata_create_package_def($uri,$key,'default',
 7476: 					     \%metathesekeys);
 7477: 	    }
 7478: 	}
 7479: # are there custom rights to evaluate
 7480: 	if ($metaentry{':copyright'} eq 'custom') {
 7481: 
 7482:     #
 7483:     # Importing a rights file here
 7484:     #
 7485: 	    unless ($depthcount) {
 7486: 		my $location=$metaentry{':customdistributionfile'};
 7487: 		my $dir=$filename;
 7488: 		$dir=~s|[^/]*$||;
 7489: 		$location=&filelocation($dir,$location);
 7490: 		my $rights_metadata =
 7491: 		    &metadata($uri,'keys',$location,'_rights',
 7492: 			      $depthcount+1);
 7493: 		foreach my $rights (split(',',$rights_metadata)) {
 7494: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7495: 		    $metathesekeys{$rights}=1;
 7496: 		}
 7497: 	    }
 7498: 	}
 7499: 	# uniqifiy package listing
 7500: 	my %seen;
 7501: 	my @uniq_packages =
 7502: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7503: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7504: 
 7505: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7506: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7507: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7508: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7509: # this is the end of "was not already recently cached
 7510:     }
 7511:     return $metaentry{':'.$what};
 7512: }
 7513: 
 7514: sub metadata_create_package_def {
 7515:     my ($uri,$key,$package,$metathesekeys)=@_;
 7516:     my ($pack,$name,$subp)=split(/\&/,$key);
 7517:     if ($subp eq 'default') { next; }
 7518:     
 7519:     if (defined($metaentry{':packages'})) {
 7520: 	$metaentry{':packages'}.=','.$package;
 7521:     } else {
 7522: 	$metaentry{':packages'}=$package;
 7523:     }
 7524:     my $value=$packagetab{$key};
 7525:     my $unikey;
 7526:     $unikey='parameter_0_'.$name;
 7527:     $metaentry{':'.$unikey.'.part'}=0;
 7528:     $$metathesekeys{$unikey}=1;
 7529:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7530: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7531:     }
 7532:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7533: 	$metaentry{':'.$unikey}=
 7534: 	    $metaentry{':'.$unikey.'.default'};
 7535:     }
 7536: }
 7537: 
 7538: sub metadata_generate_part0 {
 7539:     my ($metadata,$metacache,$uri) = @_;
 7540:     my %allnames;
 7541:     foreach my $metakey (keys(%$metadata)) {
 7542: 	if ($metakey=~/^parameter\_(.*)/) {
 7543: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7544: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7545: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7546: 	    $allnames{$name}=$part;
 7547: 	  }
 7548: 	}
 7549:     }
 7550:     foreach my $name (keys(%allnames)) {
 7551:       $$metadata{"parameter_0_$name"}=1;
 7552:       my $key=":parameter_0_$name";
 7553:       $$metacache{"$key.part"}='0';
 7554:       $$metacache{"$key.name"}=$name;
 7555:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7556: 					   $allnames{$name}.'_'.$name.
 7557: 					   '.type'};
 7558:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7559: 			     '.display'};
 7560:       my $expr='[Part: '.$allnames{$name}.']';
 7561:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7562:       $$metacache{"$key.display"}=$olddis;
 7563:     }
 7564: }
 7565: 
 7566: # ------------------------------------------------------ Devalidate title cache
 7567: 
 7568: sub devalidate_title_cache {
 7569:     my ($url)=@_;
 7570:     if (!$env{'request.course.id'}) { return; }
 7571:     my $symb=&symbread($url);
 7572:     if (!$symb) { return; }
 7573:     my $key=$env{'request.course.id'}."\0".$symb;
 7574:     &devalidate_cache_new('title',$key);
 7575: }
 7576: 
 7577: # ------------------------------------------------- Get the title of a resource
 7578: 
 7579: sub gettitle {
 7580:     my $urlsymb=shift;
 7581:     my $symb=&symbread($urlsymb);
 7582:     if ($symb) {
 7583: 	my $key=$env{'request.course.id'}."\0".$symb;
 7584: 	my ($result,$cached)=&is_cached_new('title',$key);
 7585: 	if (defined($cached)) { 
 7586: 	    return $result;
 7587: 	}
 7588: 	my ($map,$resid,$url)=&decode_symb($symb);
 7589: 	my $title='';
 7590: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7591: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7592: 	} else {
 7593: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7594: 		    &GDBM_READER(),0640)) {
 7595: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7596: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7597: 		untie(%bighash);
 7598: 	    }
 7599: 	}
 7600: 	$title=~s/\&colon\;/\:/gs;
 7601: 	if ($title) {
 7602: 	    return &do_cache_new('title',$key,$title,600);
 7603: 	}
 7604: 	$urlsymb=$url;
 7605:     }
 7606:     my $title=&metadata($urlsymb,'title');
 7607:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7608:     return $title;
 7609: }
 7610: 
 7611: sub get_slot {
 7612:     my ($which,$cnum,$cdom)=@_;
 7613:     if (!$cnum || !$cdom) {
 7614: 	(undef,my $courseid)=&whichuser();
 7615: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7616: 	$cnum=$env{'course.'.$courseid.'.num'};
 7617:     }
 7618:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7619:     my %slotinfo;
 7620:     if (exists($remembered{$key})) {
 7621: 	$slotinfo{$which} = $remembered{$key};
 7622:     } else {
 7623: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7624: 	&Apache::lonhomework::showhash(%slotinfo);
 7625: 	my ($tmp)=keys(%slotinfo);
 7626: 	if ($tmp=~/^error:/) { return (); }
 7627: 	$remembered{$key} = $slotinfo{$which};
 7628:     }
 7629:     if (ref($slotinfo{$which}) eq 'HASH') {
 7630: 	return %{$slotinfo{$which}};
 7631:     }
 7632:     return $slotinfo{$which};
 7633: }
 7634: # ------------------------------------------------- Update symbolic store links
 7635: 
 7636: sub symblist {
 7637:     my ($mapname,%newhash)=@_;
 7638:     $mapname=&deversion(&declutter($mapname));
 7639:     my %hash;
 7640:     if (($env{'request.course.fn'}) && (%newhash)) {
 7641:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7642:                       &GDBM_WRCREAT(),0640)) {
 7643: 	    foreach my $url (keys %newhash) {
 7644: 		next if ($url eq 'last_known'
 7645: 			 && $env{'form.no_update_last_known'});
 7646: 		$hash{declutter($url)}=&encode_symb($mapname,
 7647: 						    $newhash{$url}->[1],
 7648: 						    $newhash{$url}->[0]);
 7649:             }
 7650:             if (untie(%hash)) {
 7651: 		return 'ok';
 7652:             }
 7653:         }
 7654:     }
 7655:     return 'error';
 7656: }
 7657: 
 7658: # --------------------------------------------------------------- Verify a symb
 7659: 
 7660: sub symbverify {
 7661:     my ($symb,$thisurl)=@_;
 7662:     my $thisfn=$thisurl;
 7663:     $thisfn=&declutter($thisfn);
 7664: # direct jump to resource in page or to a sequence - will construct own symbs
 7665:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7666: # check URL part
 7667:     my ($map,$resid,$url)=&decode_symb($symb);
 7668: 
 7669:     unless ($url eq $thisfn) { return 0; }
 7670: 
 7671:     $symb=&symbclean($symb);
 7672:     $thisurl=&deversion($thisurl);
 7673:     $thisfn=&deversion($thisfn);
 7674: 
 7675:     my %bighash;
 7676:     my $okay=0;
 7677: 
 7678:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7679:                             &GDBM_READER(),0640)) {
 7680:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7681:         unless ($ids) { 
 7682:            $ids=$bighash{'ids_/'.$thisurl};
 7683:         }
 7684:         if ($ids) {
 7685: # ------------------------------------------------------------------- Has ID(s)
 7686: 	    foreach my $id (split(/\,/,$ids)) {
 7687: 	       my ($mapid,$resid)=split(/\./,$id);
 7688:                if (
 7689:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7690:    eq $symb) { 
 7691: 		   if (($env{'request.role.adv'}) ||
 7692: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7693: 		       $okay=1; 
 7694: 		   }
 7695: 	       }
 7696: 	   }
 7697:         }
 7698: 	untie(%bighash);
 7699:     }
 7700:     return $okay;
 7701: }
 7702: 
 7703: # --------------------------------------------------------------- Clean-up symb
 7704: 
 7705: sub symbclean {
 7706:     my $symb=shift;
 7707:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7708: # remove version from map
 7709:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7710: 
 7711: # remove version from URL
 7712:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7713: 
 7714: # remove wrapper
 7715: 
 7716:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7717:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7718:     return $symb;
 7719: }
 7720: 
 7721: # ---------------------------------------------- Split symb to find map and url
 7722: 
 7723: sub encode_symb {
 7724:     my ($map,$resid,$url)=@_;
 7725:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7726: }
 7727: 
 7728: sub decode_symb {
 7729:     my $symb=shift;
 7730:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7731:     my ($map,$resid,$url)=split(/___/,$symb);
 7732:     return (&fixversion($map),$resid,&fixversion($url));
 7733: }
 7734: 
 7735: sub fixversion {
 7736:     my $fn=shift;
 7737:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7738:     my %bighash;
 7739:     my $uri=&clutter($fn);
 7740:     my $key=$env{'request.course.id'}.'_'.$uri;
 7741: # is this cached?
 7742:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7743:     if (defined($cached)) { return $result; }
 7744: # unfortunately not cached, or expired
 7745:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7746: 	    &GDBM_READER(),0640)) {
 7747:  	if ($bighash{'version_'.$uri}) {
 7748:  	    my $version=$bighash{'version_'.$uri};
 7749:  	    unless (($version eq 'mostrecent') || 
 7750: 		    ($version==&getversion($uri))) {
 7751:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7752:  	    }
 7753:  	}
 7754:  	untie %bighash;
 7755:     }
 7756:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7757: }
 7758: 
 7759: sub deversion {
 7760:     my $url=shift;
 7761:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7762:     return $url;
 7763: }
 7764: 
 7765: # ------------------------------------------------------ Return symb list entry
 7766: 
 7767: sub symbread {
 7768:     my ($thisfn,$donotrecurse)=@_;
 7769:     my $cache_str='request.symbread.cached.'.$thisfn;
 7770:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7771: # no filename provided? try from environment
 7772:     unless ($thisfn) {
 7773:         if ($env{'request.symb'}) {
 7774: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7775: 	}
 7776: 	$thisfn=$env{'request.filename'};
 7777:     }
 7778:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7779: # is that filename actually a symb? Verify, clean, and return
 7780:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7781: 	if (&symbverify($thisfn,$1)) {
 7782: 	    return $env{$cache_str}=&symbclean($thisfn);
 7783: 	}
 7784:     }
 7785:     $thisfn=declutter($thisfn);
 7786:     my %hash;
 7787:     my %bighash;
 7788:     my $syval='';
 7789:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7790:         my $targetfn = $thisfn;
 7791:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7792:             $targetfn = 'adm/wrapper/'.$thisfn;
 7793:         }
 7794: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7795: 	    $targetfn=$1;
 7796: 	}
 7797:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7798:                       &GDBM_READER(),0640)) {
 7799: 	    $syval=$hash{$targetfn};
 7800:             untie(%hash);
 7801:         }
 7802: # ---------------------------------------------------------- There was an entry
 7803:         if ($syval) {
 7804: 	    #unless ($syval=~/\_\d+$/) {
 7805: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7806: 		    #&appenv({'request.ambiguous' => $thisfn});
 7807: 		    #return $env{$cache_str}='';
 7808: 		#}    
 7809: 		#$syval.=$1;
 7810: 	    #}
 7811:         } else {
 7812: # ------------------------------------------------------- Was not in symb table
 7813:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7814:                             &GDBM_READER(),0640)) {
 7815: # ---------------------------------------------- Get ID(s) for current resource
 7816:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7817:               unless ($ids) { 
 7818:                  $ids=$bighash{'ids_/'.$thisfn};
 7819:               }
 7820:               unless ($ids) {
 7821: # alias?
 7822: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7823:               }
 7824:               if ($ids) {
 7825: # ------------------------------------------------------------------- Has ID(s)
 7826:                  my @possibilities=split(/\,/,$ids);
 7827:                  if ($#possibilities==0) {
 7828: # ----------------------------------------------- There is only one possibility
 7829: 		     my ($mapid,$resid)=split(/\./,$ids);
 7830: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7831: 						    $resid,$thisfn);
 7832:                  } elsif (!$donotrecurse) {
 7833: # ------------------------------------------ There is more than one possibility
 7834:                      my $realpossible=0;
 7835:                      foreach my $id (@possibilities) {
 7836: 			 my $file=$bighash{'src_'.$id};
 7837:                          if (&allowed('bre',$file)) {
 7838:          		    my ($mapid,$resid)=split(/\./,$id);
 7839:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7840: 				$realpossible++;
 7841:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7842: 						    $resid,$thisfn);
 7843:                             }
 7844: 			 }
 7845:                      }
 7846: 		     if ($realpossible!=1) { $syval=''; }
 7847:                  } else {
 7848:                      $syval='';
 7849:                  }
 7850: 	      }
 7851:               untie(%bighash)
 7852:            }
 7853:         }
 7854:         if ($syval) {
 7855: 	    return $env{$cache_str}=$syval;
 7856:         }
 7857:     }
 7858:     &appenv({'request.ambiguous' => $thisfn});
 7859:     return $env{$cache_str}='';
 7860: }
 7861: 
 7862: # ---------------------------------------------------------- Return random seed
 7863: 
 7864: sub numval {
 7865:     my $txt=shift;
 7866:     $txt=~tr/A-J/0-9/;
 7867:     $txt=~tr/a-j/0-9/;
 7868:     $txt=~tr/K-T/0-9/;
 7869:     $txt=~tr/k-t/0-9/;
 7870:     $txt=~tr/U-Z/0-5/;
 7871:     $txt=~tr/u-z/0-5/;
 7872:     $txt=~s/\D//g;
 7873:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7874:     return int($txt);
 7875: }
 7876: 
 7877: sub numval2 {
 7878:     my $txt=shift;
 7879:     $txt=~tr/A-J/0-9/;
 7880:     $txt=~tr/a-j/0-9/;
 7881:     $txt=~tr/K-T/0-9/;
 7882:     $txt=~tr/k-t/0-9/;
 7883:     $txt=~tr/U-Z/0-5/;
 7884:     $txt=~tr/u-z/0-5/;
 7885:     $txt=~s/\D//g;
 7886:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7887:     my $total;
 7888:     foreach my $val (@txts) { $total+=$val; }
 7889:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7890:     return int($total);
 7891: }
 7892: 
 7893: sub numval3 {
 7894:     use integer;
 7895:     my $txt=shift;
 7896:     $txt=~tr/A-J/0-9/;
 7897:     $txt=~tr/a-j/0-9/;
 7898:     $txt=~tr/K-T/0-9/;
 7899:     $txt=~tr/k-t/0-9/;
 7900:     $txt=~tr/U-Z/0-5/;
 7901:     $txt=~tr/u-z/0-5/;
 7902:     $txt=~s/\D//g;
 7903:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7904:     my $total;
 7905:     foreach my $val (@txts) { $total+=$val; }
 7906:     if ($_64bit) { $total=(($total<<32)>>32); }
 7907:     return $total;
 7908: }
 7909: 
 7910: sub digest {
 7911:     my ($data)=@_;
 7912:     my $digest=&Digest::MD5::md5($data);
 7913:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7914:     my ($e,$f);
 7915:     {
 7916:         use integer;
 7917:         $e=($a+$b);
 7918:         $f=($c+$d);
 7919:         if ($_64bit) {
 7920:             $e=(($e<<32)>>32);
 7921:             $f=(($f<<32)>>32);
 7922:         }
 7923:     }
 7924:     if (wantarray) {
 7925: 	return ($e,$f);
 7926:     } else {
 7927: 	my $g;
 7928: 	{
 7929: 	    use integer;
 7930: 	    $g=($e+$f);
 7931: 	    if ($_64bit) {
 7932: 		$g=(($g<<32)>>32);
 7933: 	    }
 7934: 	}
 7935: 	return $g;
 7936:     }
 7937: }
 7938: 
 7939: sub latest_rnd_algorithm_id {
 7940:     return '64bit5';
 7941: }
 7942: 
 7943: sub get_rand_alg {
 7944:     my ($courseid)=@_;
 7945:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7946:     if ($courseid) {
 7947: 	return $env{"course.$courseid.rndseed"};
 7948:     }
 7949:     return &latest_rnd_algorithm_id();
 7950: }
 7951: 
 7952: sub validCODE {
 7953:     my ($CODE)=@_;
 7954:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7955:     return 0;
 7956: }
 7957: 
 7958: sub getCODE {
 7959:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7960:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7961: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7962: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7963: 	return $Apache::lonhomework::history{'resource.CODE'};
 7964:     }
 7965:     return undef;
 7966: }
 7967: 
 7968: sub rndseed {
 7969:     my ($symb,$courseid,$domain,$username)=@_;
 7970:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7971:     if (!defined($symb)) {
 7972: 	unless ($symb=$wsymb) { return time; }
 7973:     }
 7974:     if (!$courseid) { $courseid=$wcourseid; }
 7975:     if (!$domain) { $domain=$wdomain; }
 7976:     if (!$username) { $username=$wusername }
 7977:     my $which=&get_rand_alg();
 7978: 
 7979:     if (defined(&getCODE())) {
 7980: 	if ($which eq '64bit5') {
 7981: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7982: 	} elsif ($which eq '64bit4') {
 7983: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7984: 	} else {
 7985: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7986: 	}
 7987:     } elsif ($which eq '64bit5') {
 7988: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7989:     } elsif ($which eq '64bit4') {
 7990: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7991:     } elsif ($which eq '64bit3') {
 7992: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7993:     } elsif ($which eq '64bit2') {
 7994: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7995:     } elsif ($which eq '64bit') {
 7996: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7997:     }
 7998:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7999: }
 8000: 
 8001: sub rndseed_32bit {
 8002:     my ($symb,$courseid,$domain,$username)=@_;
 8003:     {
 8004: 	use integer;
 8005: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8006: 	my $symbseed=numval($symb) << 22;
 8007: 	my $namechck=unpack("%32C*",$username) << 17;
 8008: 	my $nameseed=numval($username) << 12;
 8009: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8010: 	my $courseseed=unpack("%32C*",$courseid);
 8011: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8012: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8013: 	#&logthis("rndseed :$num:$symb");
 8014: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8015: 	return $num;
 8016:     }
 8017: }
 8018: 
 8019: sub rndseed_64bit {
 8020:     my ($symb,$courseid,$domain,$username)=@_;
 8021:     {
 8022: 	use integer;
 8023: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8024: 	my $symbseed=numval($symb) << 10;
 8025: 	my $namechck=unpack("%32S*",$username);
 8026: 	
 8027: 	my $nameseed=numval($username) << 21;
 8028: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8029: 	my $courseseed=unpack("%32S*",$courseid);
 8030: 	
 8031: 	my $num1=$symbchck+$symbseed+$namechck;
 8032: 	my $num2=$nameseed+$domainseed+$courseseed;
 8033: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8034: 	#&logthis("rndseed :$num:$symb");
 8035: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8036: 	return "$num1,$num2";
 8037:     }
 8038: }
 8039: 
 8040: sub rndseed_64bit2 {
 8041:     my ($symb,$courseid,$domain,$username)=@_;
 8042:     {
 8043: 	use integer;
 8044: 	# strings need to be an even # of cahracters long, it it is odd the
 8045:         # last characters gets thrown away
 8046: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8047: 	my $symbseed=numval($symb) << 10;
 8048: 	my $namechck=unpack("%32S*",$username.' ');
 8049: 	
 8050: 	my $nameseed=numval($username) << 21;
 8051: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8052: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8053: 	
 8054: 	my $num1=$symbchck+$symbseed+$namechck;
 8055: 	my $num2=$nameseed+$domainseed+$courseseed;
 8056: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8057: 	#&logthis("rndseed :$num:$symb");
 8058: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8059: 	return "$num1,$num2";
 8060:     }
 8061: }
 8062: 
 8063: sub rndseed_64bit3 {
 8064:     my ($symb,$courseid,$domain,$username)=@_;
 8065:     {
 8066: 	use integer;
 8067: 	# strings need to be an even # of cahracters long, it it is odd the
 8068:         # last characters gets thrown away
 8069: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8070: 	my $symbseed=numval2($symb) << 10;
 8071: 	my $namechck=unpack("%32S*",$username.' ');
 8072: 	
 8073: 	my $nameseed=numval2($username) << 21;
 8074: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8075: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8076: 	
 8077: 	my $num1=$symbchck+$symbseed+$namechck;
 8078: 	my $num2=$nameseed+$domainseed+$courseseed;
 8079: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8080: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8081: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8082: 	
 8083: 	return "$num1:$num2";
 8084:     }
 8085: }
 8086: 
 8087: sub rndseed_64bit4 {
 8088:     my ($symb,$courseid,$domain,$username)=@_;
 8089:     {
 8090: 	use integer;
 8091: 	# strings need to be an even # of cahracters long, it it is odd the
 8092:         # last characters gets thrown away
 8093: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8094: 	my $symbseed=numval3($symb) << 10;
 8095: 	my $namechck=unpack("%32S*",$username.' ');
 8096: 	
 8097: 	my $nameseed=numval3($username) << 21;
 8098: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8099: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8100: 	
 8101: 	my $num1=$symbchck+$symbseed+$namechck;
 8102: 	my $num2=$nameseed+$domainseed+$courseseed;
 8103: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8104: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8105: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8106: 	
 8107: 	return "$num1:$num2";
 8108:     }
 8109: }
 8110: 
 8111: sub rndseed_64bit5 {
 8112:     my ($symb,$courseid,$domain,$username)=@_;
 8113:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8114:     return "$num1:$num2";
 8115: }
 8116: 
 8117: sub rndseed_CODE_64bit {
 8118:     my ($symb,$courseid,$domain,$username)=@_;
 8119:     {
 8120: 	use integer;
 8121: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8122: 	my $symbseed=numval2($symb);
 8123: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8124: 	my $CODEseed=numval(&getCODE());
 8125: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8126: 	my $num1=$symbseed+$CODEchck;
 8127: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8128: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8129: 	#&logthis("rndseed :$num1:$num2:$symb");
 8130: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8131: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8132: 	return "$num1:$num2";
 8133:     }
 8134: }
 8135: 
 8136: sub rndseed_CODE_64bit4 {
 8137:     my ($symb,$courseid,$domain,$username)=@_;
 8138:     {
 8139: 	use integer;
 8140: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8141: 	my $symbseed=numval3($symb);
 8142: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8143: 	my $CODEseed=numval3(&getCODE());
 8144: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8145: 	my $num1=$symbseed+$CODEchck;
 8146: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8147: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8148: 	#&logthis("rndseed :$num1:$num2:$symb");
 8149: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8150: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8151: 	return "$num1:$num2";
 8152:     }
 8153: }
 8154: 
 8155: sub rndseed_CODE_64bit5 {
 8156:     my ($symb,$courseid,$domain,$username)=@_;
 8157:     my $code = &getCODE();
 8158:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8159:     return "$num1:$num2";
 8160: }
 8161: 
 8162: sub setup_random_from_rndseed {
 8163:     my ($rndseed)=@_;
 8164:     if ($rndseed =~/([,:])/) {
 8165: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8166: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8167:     } else {
 8168: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8169:     }
 8170: }
 8171: 
 8172: sub latest_receipt_algorithm_id {
 8173:     return 'receipt3';
 8174: }
 8175: 
 8176: sub recunique {
 8177:     my $fucourseid=shift;
 8178:     my $unique;
 8179:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8180: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8181: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8182:     } else {
 8183: 	$unique=$perlvar{'lonReceipt'};
 8184:     }
 8185:     return unpack("%32C*",$unique);
 8186: }
 8187: 
 8188: sub recprefix {
 8189:     my $fucourseid=shift;
 8190:     my $prefix;
 8191:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8192: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8193: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8194:     } else {
 8195: 	$prefix=$perlvar{'lonHostID'};
 8196:     }
 8197:     return unpack("%32C*",$prefix);
 8198: }
 8199: 
 8200: sub ireceipt {
 8201:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8202: 
 8203:     my $return =&recprefix($fucourseid).'-';
 8204: 
 8205:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8206: 	$env{'request.state'} eq 'construct') {
 8207: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8208: 	return $return;
 8209:     }
 8210: 
 8211:     my $cuname=unpack("%32C*",$funame);
 8212:     my $cudom=unpack("%32C*",$fudom);
 8213:     my $cucourseid=unpack("%32C*",$fucourseid);
 8214:     my $cusymb=unpack("%32C*",$fusymb);
 8215:     my $cunique=&recunique($fucourseid);
 8216:     my $cpart=unpack("%32S*",$part);
 8217:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8218: 
 8219: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8220: 			       
 8221: 	$return.= ($cunique%$cuname+
 8222: 		   $cunique%$cudom+
 8223: 		   $cusymb%$cuname+
 8224: 		   $cusymb%$cudom+
 8225: 		   $cucourseid%$cuname+
 8226: 		   $cucourseid%$cudom+
 8227: 		   $cpart%$cuname+
 8228: 		   $cpart%$cudom);
 8229:     } else {
 8230: 	$return.= ($cunique%$cuname+
 8231: 		   $cunique%$cudom+
 8232: 		   $cusymb%$cuname+
 8233: 		   $cusymb%$cudom+
 8234: 		   $cucourseid%$cuname+
 8235: 		   $cucourseid%$cudom);
 8236:     }
 8237:     return $return;
 8238: }
 8239: 
 8240: sub receipt {
 8241:     my ($part)=@_;
 8242:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8243:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8244: }
 8245: 
 8246: sub whichuser {
 8247:     my ($passedsymb)=@_;
 8248:     my ($symb,$courseid,$domain,$name,$publicuser);
 8249:     if (defined($env{'form.grade_symb'})) {
 8250: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8251: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8252: 	if (!$allowed &&
 8253: 	    exists($env{'request.course.sec'}) &&
 8254: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8255: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8256: 			      '/'.$env{'request.course.sec'});
 8257: 	}
 8258: 	if ($allowed) {
 8259: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8260: 	    $courseid=$tmp_courseid;
 8261: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8262: 	    ($name)=&get_env_multiple('form.grade_username');
 8263: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8264: 	}
 8265:     }
 8266:     if (!$passedsymb) {
 8267: 	$symb=&symbread();
 8268:     } else {
 8269: 	$symb=$passedsymb;
 8270:     }
 8271:     $courseid=$env{'request.course.id'};
 8272:     $domain=$env{'user.domain'};
 8273:     $name=$env{'user.name'};
 8274:     if ($name eq 'public' && $domain eq 'public') {
 8275: 	if (!defined($env{'form.username'})) {
 8276: 	    $env{'form.username'}.=time.rand(10000000);
 8277: 	}
 8278: 	$name.=$env{'form.username'};
 8279:     }
 8280:     return ($symb,$courseid,$domain,$name,$publicuser);
 8281: 
 8282: }
 8283: 
 8284: # ------------------------------------------------------------ Serves up a file
 8285: # returns either the contents of the file or 
 8286: # -1 if the file doesn't exist
 8287: #
 8288: # if the target is a file that was uploaded via DOCS, 
 8289: # a check will be made to see if a current copy exists on the local server,
 8290: # if it does this will be served, otherwise a copy will be retrieved from
 8291: # the home server for the course and stored in /home/httpd/html/userfiles on
 8292: # the local server.   
 8293: 
 8294: sub getfile {
 8295:     my ($file) = @_;
 8296:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8297:     &repcopy($file);
 8298:     return &readfile($file);
 8299: }
 8300: 
 8301: sub repcopy_userfile {
 8302:     my ($file)=@_;
 8303:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8304:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8305:     my ($cdom,$cnum,$filename) = 
 8306: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8307:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8308:     if (-e "$file") {
 8309: # we already have a local copy, check it out
 8310: 	my @fileinfo = stat($file);
 8311: 	my $rtncode;
 8312: 	my $info;
 8313: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8314: 	if ($lwpresp ne 'ok') {
 8315: # there is no such file anymore, even though we had a local copy
 8316: 	    if ($rtncode eq '404') {
 8317: 		unlink($file);
 8318: 	    }
 8319: 	    return -1;
 8320: 	}
 8321: 	if ($info < $fileinfo[9]) {
 8322: # nice, the file we have is up-to-date, just say okay
 8323: 	    return 'ok';
 8324: 	} else {
 8325: # the file is outdated, get rid of it
 8326: 	    unlink($file);
 8327: 	}
 8328:     }
 8329: # one way or the other, at this point, we don't have the file
 8330: # construct the correct path for the file
 8331:     my @parts = ($cdom,$cnum); 
 8332:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8333: 	push @parts, split(/\//,$1);
 8334:     }
 8335:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8336:     foreach my $part (@parts) {
 8337: 	$path .= '/'.$part;
 8338: 	if (!-e $path) {
 8339: 	    mkdir($path,0770);
 8340: 	}
 8341:     }
 8342: # now the path exists for sure
 8343: # get a user agent
 8344:     my $ua=new LWP::UserAgent;
 8345:     my $transferfile=$file.'.in.transfer';
 8346: # FIXME: this should flock
 8347:     if (-e $transferfile) { return 'ok'; }
 8348:     my $request;
 8349:     $uri=~s/^\///;
 8350:     my $homeserver = &homeserver($cnum,$cdom);
 8351:     my $protocol = $protocol{$homeserver};
 8352:     $protocol = 'http' if ($protocol ne 'https');
 8353:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8354:     my $response=$ua->request($request,$transferfile);
 8355: # did it work?
 8356:     if ($response->is_error()) {
 8357: 	unlink($transferfile);
 8358: 	&logthis("Userfile repcopy failed for $uri");
 8359: 	return -1;
 8360:     }
 8361: # worked, rename the transfer file
 8362:     rename($transferfile,$file);
 8363:     return 'ok';
 8364: }
 8365: 
 8366: sub tokenwrapper {
 8367:     my $uri=shift;
 8368:     $uri=~s|^https?\://([^/]+)||;
 8369:     $uri=~s|^/||;
 8370:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8371:     my $token=$1;
 8372:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8373:     if ($udom && $uname && $file) {
 8374: 	$file=~s|(\?\.*)*$||;
 8375:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8376:         my $homeserver = &homeserver($uname,$udom);
 8377:         my $protocol = $protocol{$homeserver};
 8378:         $protocol = 'http' if ($protocol ne 'https');
 8379:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8380:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8381:                                '&tokenissued='.$perlvar{'lonHostID'};
 8382:     } else {
 8383:         return '/adm/notfound.html';
 8384:     }
 8385: }
 8386: 
 8387: # call with reqtype HEAD: get last modification time
 8388: # call with reqtype GET: get the file contents
 8389: # Do not call this with reqtype GET for large files! It loads everything into memory
 8390: #
 8391: sub getuploaded {
 8392:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8393:     $uri=~s/^\///;
 8394:     my $homeserver = &homeserver($cnum,$cdom);
 8395:     my $protocol = $protocol{$homeserver};
 8396:     $protocol = 'http' if ($protocol ne 'https');
 8397:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8398:     my $ua=new LWP::UserAgent;
 8399:     my $request=new HTTP::Request($reqtype,$uri);
 8400:     my $response=$ua->request($request);
 8401:     $$rtncode = $response->code;
 8402:     if (! $response->is_success()) {
 8403: 	return 'failed';
 8404:     }      
 8405:     if ($reqtype eq 'HEAD') {
 8406: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8407:     } elsif ($reqtype eq 'GET') {
 8408: 	$$info = $response->content;
 8409:     }
 8410:     return 'ok';
 8411: }
 8412: 
 8413: sub readfile {
 8414:     my $file = shift;
 8415:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8416:     my $fh;
 8417:     open($fh,"<$file");
 8418:     my $a='';
 8419:     while (my $line = <$fh>) { $a .= $line; }
 8420:     return $a;
 8421: }
 8422: 
 8423: sub filelocation {
 8424:     my ($dir,$file) = @_;
 8425:     my $location;
 8426:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8427: 
 8428:     if ($file =~ m-^/adm/-) {
 8429: 	$file=~s-^/adm/wrapper/-/-;
 8430: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8431:     }
 8432: 
 8433:     if ($file=~m:^/~:) { # is a contruction space reference
 8434:         $location = $file;
 8435:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8436:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8437: 	# is a correct contruction space reference
 8438:         $location = $file;
 8439:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8440:         $location = $file;
 8441:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8442:         my ($udom,$uname,$filename)=
 8443:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8444:         my $home=&homeserver($uname,$udom);
 8445:         my $is_me=0;
 8446:         my @ids=&current_machine_ids();
 8447:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8448:         if ($is_me) {
 8449:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8450:         } else {
 8451:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8452:   	      $udom.'/'.$uname.'/'.$filename;
 8453:         }
 8454:     } elsif ($file =~ m-^/adm/-) {
 8455: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8456:     } else {
 8457:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8458:         $file=~s:^/res/:/:;
 8459:         if ( !( $file =~ m:^/:) ) {
 8460:             $location = $dir. '/'.$file;
 8461:         } else {
 8462:             $location = '/home/httpd/html/res'.$file;
 8463:         }
 8464:     }
 8465:     $location=~s://+:/:g; # remove duplicate /
 8466:     while ($location=~m{/\.\./}) {
 8467: 	if ($location =~ m{/[^/]+/\.\./}) {
 8468: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8469: 	} else {
 8470: 	    $location=~ s{/\.\./}{/}g;
 8471: 	}
 8472:     } #remove dir/..
 8473:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8474:     return $location;
 8475: }
 8476: 
 8477: sub hreflocation {
 8478:     my ($dir,$file)=@_;
 8479:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8480: 	$file=filelocation($dir,$file);
 8481:     } elsif ($file=~m-^/adm/-) {
 8482: 	$file=~s-^/adm/wrapper/-/-;
 8483: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8484:     }
 8485:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8486: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8487:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8488: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8489:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8490: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8491: 	    -/uploaded/$1/$2/-x;
 8492:     }
 8493:     if ($file=~ m{^/userfiles/}) {
 8494: 	$file =~ s{^/userfiles/}{/uploaded/};
 8495:     }
 8496:     return $file;
 8497: }
 8498: 
 8499: sub current_machine_domains {
 8500:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8501: }
 8502: 
 8503: sub machine_domains {
 8504:     my ($hostname) = @_;
 8505:     my @domains;
 8506:     my %hostname = &all_hostnames();
 8507:     while( my($id, $name) = each(%hostname)) {
 8508: #	&logthis("-$id-$name-$hostname-");
 8509: 	if ($hostname eq $name) {
 8510: 	    push(@domains,&host_domain($id));
 8511: 	}
 8512:     }
 8513:     return @domains;
 8514: }
 8515: 
 8516: sub current_machine_ids {
 8517:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8518: }
 8519: 
 8520: sub machine_ids {
 8521:     my ($hostname) = @_;
 8522:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8523:     my @ids;
 8524:     my %name_to_host = &all_names();
 8525:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8526: 	return @{ $name_to_host{$hostname} };
 8527:     }
 8528:     return;
 8529: }
 8530: 
 8531: sub additional_machine_domains {
 8532:     my @domains;
 8533:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8534:     while( my $line = <$fh>) {
 8535:         $line =~ s/\s//g;
 8536:         push(@domains,$line);
 8537:     }
 8538:     return @domains;
 8539: }
 8540: 
 8541: sub default_login_domain {
 8542:     my $domain = $perlvar{'lonDefDomain'};
 8543:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8544:     foreach my $posdom (&current_machine_domains(),
 8545:                         &additional_machine_domains()) {
 8546:         if (lc($posdom) eq lc($testdomain)) {
 8547:             $domain=$posdom;
 8548:             last;
 8549:         }
 8550:     }
 8551:     return $domain;
 8552: }
 8553: 
 8554: # ------------------------------------------------------------- Declutters URLs
 8555: 
 8556: sub declutter {
 8557:     my $thisfn=shift;
 8558:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8559:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8560:     $thisfn=~s/^\///;
 8561:     $thisfn=~s|^adm/wrapper/||;
 8562:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8563:     $thisfn=~s/^res\///;
 8564:     $thisfn=~s/\?.+$//;
 8565:     return $thisfn;
 8566: }
 8567: 
 8568: # ------------------------------------------------------------- Clutter up URLs
 8569: 
 8570: sub clutter {
 8571:     my $thisfn='/'.&declutter(shift);
 8572:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8573: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8574:        $thisfn='/res'.$thisfn; 
 8575:     }
 8576:     if ($thisfn !~m|/adm|) {
 8577: 	if ($thisfn =~ m|/ext/|) {
 8578: 	    $thisfn='/adm/wrapper'.$thisfn;
 8579: 	} else {
 8580: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8581: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8582: 	    if ($embstyle eq 'ssi'
 8583: 		|| ($embstyle eq 'hdn')
 8584: 		|| ($embstyle eq 'rat')
 8585: 		|| ($embstyle eq 'prv')
 8586: 		|| ($embstyle eq 'ign')) {
 8587: 		#do nothing with these
 8588: 	    } elsif (($embstyle eq 'img') 
 8589: 		|| ($embstyle eq 'emb')
 8590: 		|| ($embstyle eq 'wrp')) {
 8591: 		$thisfn='/adm/wrapper'.$thisfn;
 8592: 	    } elsif ($embstyle eq 'unk'
 8593: 		     && $thisfn!~/\.(sequence|page)$/) {
 8594: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8595: 	    } else {
 8596: #		&logthis("Got a blank emb style");
 8597: 	    }
 8598: 	}
 8599:     }
 8600:     return $thisfn;
 8601: }
 8602: 
 8603: sub clutter_with_no_wrapper {
 8604:     my $uri = &clutter(shift);
 8605:     if ($uri =~ m-^/adm/-) {
 8606: 	$uri =~ s-^/adm/wrapper/-/-;
 8607: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8608:     }
 8609:     return $uri;
 8610: }
 8611: 
 8612: sub freeze_escape {
 8613:     my ($value)=@_;
 8614:     if (ref($value)) {
 8615: 	$value=&nfreeze($value);
 8616: 	return '__FROZEN__'.&escape($value);
 8617:     }
 8618:     return &escape($value);
 8619: }
 8620: 
 8621: 
 8622: sub thaw_unescape {
 8623:     my ($value)=@_;
 8624:     if ($value =~ /^__FROZEN__/) {
 8625: 	substr($value,0,10,undef);
 8626: 	$value=&unescape($value);
 8627: 	return &thaw($value);
 8628:     }
 8629:     return &unescape($value);
 8630: }
 8631: 
 8632: sub correct_line_ends {
 8633:     my ($result)=@_;
 8634:     $$result =~s/\r\n/\n/mg;
 8635:     $$result =~s/\r/\n/mg;
 8636: }
 8637: # ================================================================ Main Program
 8638: 
 8639: sub goodbye {
 8640:    &logthis("Starting Shut down");
 8641: #not converted to using infrastruture and probably shouldn't be
 8642:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8643: #converted
 8644: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8645:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8646: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8647: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8648: #1.1 only
 8649: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8650: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8651: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8652: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8653:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8654:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8655:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8656:    &flushcourselogs();
 8657:    &logthis("Shutting down");
 8658: }
 8659: 
 8660: sub get_dns {
 8661:     my ($url,$func,$ignore_cache) = @_;
 8662:     if (!$ignore_cache) {
 8663: 	my ($content,$cached)=
 8664: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8665: 	if ($cached) {
 8666: 	    &$func($content);
 8667: 	    return;
 8668: 	}
 8669:     }
 8670: 
 8671:     my %alldns;
 8672:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8673:     foreach my $dns (<$config>) {
 8674: 	next if ($dns !~ /^\^(\S*)/x);
 8675:         my $line = $1;
 8676:         my ($host,$protocol) = split(/:/,$line);
 8677:         if ($protocol ne 'https') {
 8678:             $protocol = 'http';
 8679:         }
 8680: 	$alldns{$host} = $protocol;
 8681:     }
 8682:     while (%alldns) {
 8683: 	my ($dns) = keys(%alldns);
 8684: 	my $ua=new LWP::UserAgent;
 8685: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8686: 	my $response=$ua->request($request);
 8687:         delete($alldns{$dns});
 8688: 	next if ($response->is_error());
 8689: 	my @content = split("\n",$response->content);
 8690: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8691: 	&$func(\@content);
 8692: 	return;
 8693:     }
 8694:     close($config);
 8695:     my $which = (split('/',$url))[3];
 8696:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8697:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8698:     my @content = <$config>;
 8699:     &$func(\@content);
 8700:     return;
 8701: }
 8702: # ------------------------------------------------------------ Read domain file
 8703: {
 8704:     my $loaded;
 8705:     my %domain;
 8706: 
 8707:     sub parse_domain_tab {
 8708: 	my ($lines) = @_;
 8709: 	foreach my $line (@$lines) {
 8710: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8711: 
 8712: 	    chomp($line);
 8713: 	    my ($name,@elements) = split(/:/,$line,9);
 8714: 	    my %this_domain;
 8715: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8716: 			       'lang_def', 'city', 'longi', 'lati',
 8717: 			       'primary') {
 8718: 		$this_domain{$field} = shift(@elements);
 8719: 	    }
 8720: 	    $domain{$name} = \%this_domain;
 8721: 	}
 8722:     }
 8723: 
 8724:     sub reset_domain_info {
 8725: 	undef($loaded);
 8726: 	undef(%domain);
 8727:     }
 8728: 
 8729:     sub load_domain_tab {
 8730: 	my ($ignore_cache) = @_;
 8731: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8732: 	my $fh;
 8733: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8734: 	    my @lines = <$fh>;
 8735: 	    &parse_domain_tab(\@lines);
 8736: 	}
 8737: 	close($fh);
 8738: 	$loaded = 1;
 8739:     }
 8740: 
 8741:     sub domain {
 8742: 	&load_domain_tab() if (!$loaded);
 8743: 
 8744: 	my ($name,$what) = @_;
 8745: 	return if ( !exists($domain{$name}) );
 8746: 
 8747: 	if (!$what) {
 8748: 	    return $domain{$name}{'description'};
 8749: 	}
 8750: 	return $domain{$name}{$what};
 8751:     }
 8752: 
 8753:     sub domain_info {
 8754:         &load_domain_tab() if (!$loaded);
 8755:         return %domain;
 8756:     }
 8757: 
 8758: }
 8759: 
 8760: 
 8761: # ------------------------------------------------------------- Read hosts file
 8762: {
 8763:     my %hostname;
 8764:     my %hostdom;
 8765:     my %libserv;
 8766:     my $loaded;
 8767:     my %name_to_host;
 8768: 
 8769:     sub parse_hosts_tab {
 8770: 	my ($file) = @_;
 8771: 	foreach my $configline (@$file) {
 8772: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8773: 	    next if ($configline =~ /^\^/);
 8774: 	    chomp($configline);
 8775: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8776: 	    $name=~s/\s//g;
 8777: 	    if ($id && $domain && $role && $name) {
 8778: 		$hostname{$id}=$name;
 8779: 		push(@{$name_to_host{$name}}, $id);
 8780: 		$hostdom{$id}=$domain;
 8781: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8782:                 if (defined($protocol)) {
 8783:                     if ($protocol eq 'https') {
 8784:                         $protocol{$id} = $protocol;
 8785:                     } else {
 8786:                         $protocol{$id} = 'http'; 
 8787:                     }
 8788:                 } else {
 8789:                     $protocol{$id} = 'http';
 8790:                 }
 8791: 	    }
 8792: 	}
 8793:     }
 8794:     
 8795:     sub reset_hosts_info {
 8796: 	&purge_remembered();
 8797: 	&reset_domain_info();
 8798: 	&reset_hosts_ip_info();
 8799: 	undef(%name_to_host);
 8800: 	undef(%hostname);
 8801: 	undef(%hostdom);
 8802: 	undef(%libserv);
 8803: 	undef($loaded);
 8804:     }
 8805: 
 8806:     sub load_hosts_tab {
 8807: 	my ($ignore_cache) = @_;
 8808: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8809: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8810: 	my @config = <$config>;
 8811: 	&parse_hosts_tab(\@config);
 8812: 	close($config);
 8813: 	$loaded=1;
 8814:     }
 8815: 
 8816:     sub hostname {
 8817: 	&load_hosts_tab() if (!$loaded);
 8818: 
 8819: 	my ($lonid) = @_;
 8820: 	return $hostname{$lonid};
 8821:     }
 8822: 
 8823:     sub all_hostnames {
 8824: 	&load_hosts_tab() if (!$loaded);
 8825: 
 8826: 	return %hostname;
 8827:     }
 8828: 
 8829:     sub all_names {
 8830: 	&load_hosts_tab() if (!$loaded);
 8831: 
 8832: 	return %name_to_host;
 8833:     }
 8834: 
 8835:     sub all_host_domain {
 8836:         &load_hosts_tab() if (!$loaded);
 8837:         return %hostdom;
 8838:     }
 8839: 
 8840:     sub is_library {
 8841: 	&load_hosts_tab() if (!$loaded);
 8842: 
 8843: 	return exists($libserv{$_[0]});
 8844:     }
 8845: 
 8846:     sub all_library {
 8847: 	&load_hosts_tab() if (!$loaded);
 8848: 
 8849: 	return %libserv;
 8850:     }
 8851: 
 8852:     sub get_servers {
 8853: 	&load_hosts_tab() if (!$loaded);
 8854: 
 8855: 	my ($domain,$type) = @_;
 8856: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8857: 	                                          : %hostname;
 8858: 	my %result;
 8859: 	if (ref($domain) eq 'ARRAY') {
 8860: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8861: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8862: 		    $result{$host} = $hostname;
 8863: 		}
 8864: 	    }
 8865: 	} else {
 8866: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8867: 		if ($hostdom{$host} eq $domain) {
 8868: 		    $result{$host} = $hostname;
 8869: 		}
 8870: 	    }
 8871: 	}
 8872: 	return %result;
 8873:     }
 8874: 
 8875:     sub host_domain {
 8876: 	&load_hosts_tab() if (!$loaded);
 8877: 
 8878: 	my ($lonid) = @_;
 8879: 	return $hostdom{$lonid};
 8880:     }
 8881: 
 8882:     sub all_domains {
 8883: 	&load_hosts_tab() if (!$loaded);
 8884: 
 8885: 	my %seen;
 8886: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8887: 	return @uniq;
 8888:     }
 8889: }
 8890: 
 8891: { 
 8892:     my %iphost;
 8893:     my %name_to_ip;
 8894:     my %lonid_to_ip;
 8895: 
 8896:     sub get_hosts_from_ip {
 8897: 	my ($ip) = @_;
 8898: 	my %iphosts = &get_iphost();
 8899: 	if (ref($iphosts{$ip})) {
 8900: 	    return @{$iphosts{$ip}};
 8901: 	}
 8902: 	return;
 8903:     }
 8904:     
 8905:     sub reset_hosts_ip_info {
 8906: 	undef(%iphost);
 8907: 	undef(%name_to_ip);
 8908: 	undef(%lonid_to_ip);
 8909:     }
 8910: 
 8911:     sub get_host_ip {
 8912: 	my ($lonid) = @_;
 8913: 	if (exists($lonid_to_ip{$lonid})) {
 8914: 	    return $lonid_to_ip{$lonid};
 8915: 	}
 8916: 	my $name=&hostname($lonid);
 8917:    	my $ip = gethostbyname($name);
 8918: 	return if (!$ip || length($ip) ne 4);
 8919: 	$ip=inet_ntoa($ip);
 8920: 	$name_to_ip{$name}   = $ip;
 8921: 	$lonid_to_ip{$lonid} = $ip;
 8922: 	return $ip;
 8923:     }
 8924:     
 8925:     sub get_iphost {
 8926: 	my ($ignore_cache) = @_;
 8927: 
 8928: 	if (!$ignore_cache) {
 8929: 	    if (%iphost) {
 8930: 		return %iphost;
 8931: 	    }
 8932: 	    my ($ip_info,$cached)=
 8933: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8934: 	    if ($cached) {
 8935: 		%iphost      = %{$ip_info->[0]};
 8936: 		%name_to_ip  = %{$ip_info->[1]};
 8937: 		%lonid_to_ip = %{$ip_info->[2]};
 8938: 		return %iphost;
 8939: 	    }
 8940: 	}
 8941: 
 8942: 	# get yesterday's info for fallback
 8943: 	my %old_name_to_ip;
 8944: 	my ($ip_info,$cached)=
 8945: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8946: 	if ($cached) {
 8947: 	    %old_name_to_ip = %{$ip_info->[1]};
 8948: 	}
 8949: 
 8950: 	my %name_to_host = &all_names();
 8951: 	foreach my $name (keys(%name_to_host)) {
 8952: 	    my $ip;
 8953: 	    if (!exists($name_to_ip{$name})) {
 8954: 		$ip = gethostbyname($name);
 8955: 		if (!$ip || length($ip) ne 4) {
 8956: 		    if (defined($old_name_to_ip{$name})) {
 8957: 			$ip = $old_name_to_ip{$name};
 8958: 			&logthis("Can't find $name defaulting to old $ip");
 8959: 		    } else {
 8960: 			&logthis("Name $name no IP found");
 8961: 			next;
 8962: 		    }
 8963: 		} else {
 8964: 		    $ip=inet_ntoa($ip);
 8965: 		}
 8966: 		$name_to_ip{$name} = $ip;
 8967: 	    } else {
 8968: 		$ip = $name_to_ip{$name};
 8969: 	    }
 8970: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8971: 		$lonid_to_ip{$id} = $ip;
 8972: 	    }
 8973: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8974: 	}
 8975: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8976: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8977: 				      48*60*60);
 8978: 
 8979: 	return %iphost;
 8980:     }
 8981: }
 8982: 
 8983: BEGIN {
 8984: 
 8985: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8986:     unless ($readit) {
 8987: {
 8988:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8989:     %perlvar = (%perlvar,%{$configvars});
 8990: }
 8991: 
 8992: 
 8993: # ------------------------------------------------------ Read spare server file
 8994: {
 8995:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8996: 
 8997:     while (my $configline=<$config>) {
 8998:        chomp($configline);
 8999:        if ($configline) {
 9000: 	   my ($host,$type) = split(':',$configline,2);
 9001: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9002: 	   push(@{ $spareid{$type} }, $host);
 9003:        }
 9004:     }
 9005:     close($config);
 9006: }
 9007: # ------------------------------------------------------------ Read permissions
 9008: {
 9009:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9010: 
 9011:     while (my $configline=<$config>) {
 9012: 	chomp($configline);
 9013: 	if ($configline) {
 9014: 	    my ($role,$perm)=split(/ /,$configline);
 9015: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9016: 	}
 9017:     }
 9018:     close($config);
 9019: }
 9020: 
 9021: # -------------------------------------------- Read plain texts for permissions
 9022: {
 9023:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9024: 
 9025:     while (my $configline=<$config>) {
 9026: 	chomp($configline);
 9027: 	if ($configline) {
 9028: 	    my ($short,@plain)=split(/:/,$configline);
 9029:             %{$prp{$short}} = ();
 9030: 	    if (@plain > 0) {
 9031:                 $prp{$short}{'std'} = $plain[0];
 9032:                 for (my $i=1; $i<@plain; $i++) {
 9033:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9034:                 }
 9035:             }
 9036: 	}
 9037:     }
 9038:     close($config);
 9039: }
 9040: 
 9041: # ---------------------------------------------------------- Read package table
 9042: {
 9043:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9044: 
 9045:     while (my $configline=<$config>) {
 9046: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9047: 	chomp($configline);
 9048: 	my ($short,$plain)=split(/:/,$configline);
 9049: 	my ($pack,$name)=split(/\&/,$short);
 9050: 	if ($plain ne '') {
 9051: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9052: 	    $packagetab{$short}=$plain; 
 9053: 	}
 9054:     }
 9055:     close($config);
 9056: }
 9057: 
 9058: # ------------- set up temporary directory
 9059: {
 9060:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9061: 
 9062: }
 9063: 
 9064: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9065: 				'compress_threshold'=> 20_000,
 9066:  			        });
 9067: 
 9068: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9069: $dumpcount=0;
 9070: $locknum=0;
 9071: 
 9072: &logtouch();
 9073: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9074: $readit=1;
 9075:     {
 9076: 	use integer;
 9077: 	my $test=(2**32)+1;
 9078: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9079: 	&logthis(" Detected 64bit platform ($_64bit)");
 9080:     }
 9081: }
 9082: }
 9083: 
 9084: 1;
 9085: __END__
 9086: 
 9087: =pod
 9088: 
 9089: =head1 NAME
 9090: 
 9091: Apache::lonnet - Subroutines to ask questions about things in the network.
 9092: 
 9093: =head1 SYNOPSIS
 9094: 
 9095: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9096: 
 9097:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9098: 
 9099: Common parameters:
 9100: 
 9101: =over 4
 9102: 
 9103: =item *
 9104: 
 9105: $uname : an internal username (if $cname expecting a course Id specifically)
 9106: 
 9107: =item *
 9108: 
 9109: $udom : a domain (if $cdom expecting a course's domain specifically)
 9110: 
 9111: =item *
 9112: 
 9113: $symb : a resource instance identifier
 9114: 
 9115: =item *
 9116: 
 9117: $namespace : the name of a .db file that contains the data needed or
 9118: being set.
 9119: 
 9120: =back
 9121: 
 9122: =head1 OVERVIEW
 9123: 
 9124: lonnet provides subroutines which interact with the
 9125: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9126: about classes, users, and resources.
 9127: 
 9128: For many of these objects you can also use this to store data about
 9129: them or modify them in various ways.
 9130: 
 9131: =head2 Symbs
 9132: 
 9133: To identify a specific instance of a resource, LON-CAPA uses symbols
 9134: or "symbs"X<symb>. These identifiers are built from the URL of the
 9135: map, the resource number of the resource in the map, and the URL of
 9136: the resource itself. The latter is somewhat redundant, but might help
 9137: if maps change.
 9138: 
 9139: An example is
 9140: 
 9141:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9142: 
 9143: The respective map entry is
 9144: 
 9145:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9146:   title="Problem 2">
 9147:  </resource>
 9148: 
 9149: Symbs are used by the random number generator, as well as to store and
 9150: restore data specific to a certain instance of for example a problem.
 9151: 
 9152: =head2 Storing And Retrieving Data
 9153: 
 9154: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9155: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9156: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9157: is is the non-critical message twin of cstore. These functions are for
 9158: handlers to store a perl hash to a user's permanent data space in an
 9159: easy manner, and to retrieve it again on another call. It is expected
 9160: that a handler would use this once at the beginning to retrieve data,
 9161: and then again once at the end to send only the new data back.
 9162: 
 9163: The data is stored in the user's data directory on the user's
 9164: homeserver under the ID of the course.
 9165: 
 9166: The hash that is returned by restore will have all of the previous
 9167: value for all of the elements of the hash.
 9168: 
 9169: Example:
 9170: 
 9171:  #creating a hash
 9172:  my %hash;
 9173:  $hash{'foo'}='bar';
 9174: 
 9175:  #storing it
 9176:  &Apache::lonnet::cstore(\%hash);
 9177: 
 9178:  #changing a value
 9179:  $hash{'foo'}='notbar';
 9180: 
 9181:  #adding a new value
 9182:  $hash{'bar'}='foo';
 9183:  &Apache::lonnet::cstore(\%hash);
 9184: 
 9185:  #retrieving the hash
 9186:  my %history=&Apache::lonnet::restore();
 9187: 
 9188:  #print the hash
 9189:  foreach my $key (sort(keys(%history))) {
 9190:    print("\%history{$key} = $history{$key}");
 9191:  }
 9192: 
 9193: Will print out:
 9194: 
 9195:  %history{1:foo} = bar
 9196:  %history{1:keys} = foo:timestamp
 9197:  %history{1:timestamp} = 990455579
 9198:  %history{2:bar} = foo
 9199:  %history{2:foo} = notbar
 9200:  %history{2:keys} = foo:bar:timestamp
 9201:  %history{2:timestamp} = 990455580
 9202:  %history{bar} = foo
 9203:  %history{foo} = notbar
 9204:  %history{timestamp} = 990455580
 9205:  %history{version} = 2
 9206: 
 9207: Note that the special hash entries C<keys>, C<version> and
 9208: C<timestamp> were added to the hash. C<version> will be equal to the
 9209: total number of versions of the data that have been stored. The
 9210: C<timestamp> attribute will be the UNIX time the hash was
 9211: stored. C<keys> is available in every historical section to list which
 9212: keys were added or changed at a specific historical revision of a
 9213: hash.
 9214: 
 9215: B<Warning>: do not store the hash that restore returns directly. This
 9216: will cause a mess since it will restore the historical keys as if the
 9217: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9218: 
 9219: Calling convention:
 9220: 
 9221:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9222:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9223: 
 9224: For more detailed information, see lonnet specific documentation.
 9225: 
 9226: =head1 RETURN MESSAGES
 9227: 
 9228: =over 4
 9229: 
 9230: =item * B<con_lost>: unable to contact remote host
 9231: 
 9232: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9233: when the connection is brought back up
 9234: 
 9235: =item * B<con_failed>: unable to contact remote host and unable to save message
 9236: for later delivery
 9237: 
 9238: =item * B<error:>: an error a occurred, a description of the error follows the :
 9239: 
 9240: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9241: that was requested
 9242: 
 9243: =back
 9244: 
 9245: =head1 PUBLIC SUBROUTINES
 9246: 
 9247: =head2 Session Environment Functions
 9248: 
 9249: =over 4
 9250: 
 9251: =item * 
 9252: X<appenv()>
 9253: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9254: the user envirnoment file, and will be restored for each access this
 9255: user makes during this session, also modifies the %env for the current
 9256: process. Optional rolesarrayref - if defined contains a reference to an array
 9257: of roles which are exempt from the restriction on modifying user.role entries 
 9258: in the user's environment.db and in %env.    
 9259: 
 9260: =item *
 9261: X<delenv()>
 9262: B<delenv($regexp)>: removes all items from the session
 9263: environment file that matches the regular expression in $regexp. The
 9264: values are also delted from the current processes %env.
 9265: 
 9266: =item * get_env_multiple($name) 
 9267: 
 9268: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9269: values may be defined and end up as an array ref.
 9270: 
 9271: returns an array of values
 9272: 
 9273: =back
 9274: 
 9275: =head2 User Information
 9276: 
 9277: =over 4
 9278: 
 9279: =item *
 9280: X<queryauthenticate()>
 9281: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9282: authentication scheme
 9283: 
 9284: =item *
 9285: X<authenticate()>
 9286: B<authenticate($uname,$upass,$udom)>: try to
 9287: authenticate user from domain's lib servers (first use the current
 9288: one). C<$upass> should be the users password.
 9289: 
 9290: =item *
 9291: X<homeserver()>
 9292: B<homeserver($uname,$udom)>: find the server which has
 9293: the user's directory and files (there must be only one), this caches
 9294: the answer, and also caches if there is a borken connection.
 9295: 
 9296: =item *
 9297: X<idget()>
 9298: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9299: (IDs are a unique resource in a domain, there must be only 1 ID per
 9300: username, and only 1 username per ID in a specific domain) (returns
 9301: hash: id=>name,id=>name)
 9302: 
 9303: =item *
 9304: X<idrget()>
 9305: B<idrget($udom,@unames)>: find the IDs behind a list of
 9306: usernames (returns hash: name=>id,name=>id)
 9307: 
 9308: =item *
 9309: X<idput()>
 9310: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9311: 
 9312: =item *
 9313: X<rolesinit()>
 9314: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9315: 
 9316: =item *
 9317: X<getsection()>
 9318: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9319: course $cname, return section name/number or '' for "not in course"
 9320: and '-1' for "no section"
 9321: 
 9322: =item *
 9323: X<userenvironment()>
 9324: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9325: passed in @what from the requested user's environment, returns a hash
 9326: 
 9327: =item * 
 9328: X<userlog_query()>
 9329: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9330: activity.log file. %filters defines filters applied when parsing the
 9331: log file. These can be start or end timestamps, or the type of action
 9332: - log to look for Login or Logout events, check for Checkin or
 9333: Checkout, role for role selection. The response is in the form
 9334: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9335: escaped strings of the action recorded in the activity.log file.
 9336: 
 9337: =back
 9338: 
 9339: =head2 User Roles
 9340: 
 9341: =over 4
 9342: 
 9343: =item *
 9344: 
 9345: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9346:  F: full access
 9347:  U,I,K: authentication modes (cxx only)
 9348:  '': forbidden
 9349:  1: user needs to choose course
 9350:  2: browse allowed
 9351:  A: passphrase authentication needed
 9352: 
 9353: =item *
 9354: 
 9355: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9356: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9357: and course level
 9358: 
 9359: =item *
 9360: 
 9361: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9362: explanation of a user role term
 9363: 
 9364: =item *
 9365: 
 9366: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9367: All arguments are optional. Returns a hash of a roles, either for
 9368: co-author/assistant author roles for a user's Construction Space
 9369: (default), or if $context is 'userroles', roles for the user himself,
 9370: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9371: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9372: For each key, value is set to colon-separated start and end times for
 9373: the role.  If no username and domain are specified, will default to
 9374: current user/domain. Types, roles, and roledoms are references to arrays
 9375: of role statuses (active, future or previous), roles 
 9376: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9377: to restrict the list of roles reported. If no array ref is 
 9378: provided for types, will default to return only active roles.
 9379: 
 9380: =back
 9381: 
 9382: =head2 User Modification
 9383: 
 9384: =over 4
 9385: 
 9386: =item *
 9387: 
 9388: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9389: user for the level given by URL.  Optional start and end dates (leave empty
 9390: string or zero for "no date")
 9391: 
 9392: =item *
 9393: 
 9394: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9395: change a users, password, possible return values are: ok,
 9396: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9397: refused
 9398: 
 9399: =item *
 9400: 
 9401: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9402: 
 9403: =item *
 9404: 
 9405: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9406:            $forceid,$desiredhome,$email,$inststatus) : 
 9407: modify user
 9408: 
 9409: =item *
 9410: 
 9411: modifystudent
 9412: 
 9413: modify a student's enrollment and identification information.
 9414: The course id is resolved based on the current users environment.  
 9415: This means the envoking user must be a course coordinator or otherwise
 9416: associated with a course.
 9417: 
 9418: This call is essentially a wrapper for lonnet::modifyuser and
 9419: lonnet::modify_student_enrollment
 9420: 
 9421: Inputs: 
 9422: 
 9423: =over 4
 9424: 
 9425: =item B<$udom> Student's loncapa domain
 9426: 
 9427: =item B<$uname> Student's loncapa login name
 9428: 
 9429: =item B<$uid> Student/Employee ID
 9430: 
 9431: =item B<$umode> Student's authentication mode
 9432: 
 9433: =item B<$upass> Student's password
 9434: 
 9435: =item B<$first> Student's first name
 9436: 
 9437: =item B<$middle> Student's middle name
 9438: 
 9439: =item B<$last> Student's last name
 9440: 
 9441: =item B<$gene> Student's generation
 9442: 
 9443: =item B<$usec> Student's section in course
 9444: 
 9445: =item B<$end> Unix time of the roles expiration
 9446: 
 9447: =item B<$start> Unix time of the roles start date
 9448: 
 9449: =item B<$forceid> If defined, allow $uid to be changed
 9450: 
 9451: =item B<$desiredhome> server to use as home server for student
 9452: 
 9453: =item B<$email> Student's permanent e-mail address
 9454: 
 9455: =item B<$type> Type of enrollment (auto or manual)
 9456: 
 9457: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9458: 
 9459: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9460: 
 9461: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9462: 
 9463: =item B<$context> role change context (shown in User Management Logs display in a course)
 9464: 
 9465: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9466: 
 9467: =back
 9468: 
 9469: =item *
 9470: 
 9471: modify_student_enrollment
 9472: 
 9473: Change a students enrollment status in a class.  The environment variable
 9474: 'role.request.course' must be defined for this function to proceed.
 9475: 
 9476: Inputs:
 9477: 
 9478: =over 4
 9479: 
 9480: =item $udom, students domain
 9481: 
 9482: =item $uname, students name
 9483: 
 9484: =item $uid, students user id
 9485: 
 9486: =item $first, students first name
 9487: 
 9488: =item $middle
 9489: 
 9490: =item $last
 9491: 
 9492: =item $gene
 9493: 
 9494: =item $usec
 9495: 
 9496: =item $end
 9497: 
 9498: =item $start
 9499: 
 9500: =item $type
 9501: 
 9502: =item $locktype
 9503: 
 9504: =item $cid
 9505: 
 9506: =item $selfenroll
 9507: 
 9508: =item $context
 9509: 
 9510: =back
 9511: 
 9512: 
 9513: =item *
 9514: 
 9515: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9516: custom role; give a custom role to a user for the level given by URL.  Specify
 9517: name and domain of role author, and role name
 9518: 
 9519: =item *
 9520: 
 9521: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9522: 
 9523: =item *
 9524: 
 9525: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9526: 
 9527: =back
 9528: 
 9529: =head2 Course Infomation
 9530: 
 9531: =over 4
 9532: 
 9533: =item *
 9534: 
 9535: coursedescription($courseid) : returns a hash of information about the
 9536: specified course id, including all environment settings for the
 9537: course, the description of the course will be in the hash under the
 9538: key 'description'
 9539: 
 9540: =item *
 9541: 
 9542: resdata($name,$domain,$type,@which) : request for current parameter
 9543: setting for a specific $type, where $type is either 'course' or 'user',
 9544: @what should be a list of parameters to ask about. This routine caches
 9545: answers for 5 minutes.
 9546: 
 9547: =item *
 9548: 
 9549: get_courseresdata($courseid, $domain) : dump the entire course resource
 9550: data base, returning a hash that is keyed by the resource name and has
 9551: values that are the resource value.  I believe that the timestamps and
 9552: versions are also returned.
 9553: 
 9554: 
 9555: =back
 9556: 
 9557: =head2 Course Modification
 9558: 
 9559: =over 4
 9560: 
 9561: =item *
 9562: 
 9563: writecoursepref($courseid,%prefs) : write preferences (environment
 9564: database) for a course
 9565: 
 9566: =item *
 9567: 
 9568: createcourse($udom,$description,$url) : make/modify course
 9569: 
 9570: =back
 9571: 
 9572: =head2 Resource Subroutines
 9573: 
 9574: =over 4
 9575: 
 9576: =item *
 9577: 
 9578: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9579: 
 9580: =item *
 9581: 
 9582: repcopy($filename) : subscribes to the requested file, and attempts to
 9583: replicate from the owning library server, Might return
 9584: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9585: 'bad_request', also attempts to grab the metadata for the
 9586: resource. Expects the local filesystem pathname
 9587: (/home/httpd/html/res/....)
 9588: 
 9589: =back
 9590: 
 9591: =head2 Resource Information
 9592: 
 9593: =over 4
 9594: 
 9595: =item *
 9596: 
 9597: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9598: a vairety of different possible values, $varname should be a request
 9599: string, and the other parameters can be used to specify who and what
 9600: one is asking about.
 9601: 
 9602: Possible values for $varname are environment.lastname (or other item
 9603: from the envirnment hash), user.name (or someother aspect about the
 9604: user), resource.0.maxtries (or some other part and parameter of a
 9605: resource)
 9606: 
 9607: =item *
 9608: 
 9609: directcondval($number) : get current value of a condition; reads from a state
 9610: string
 9611: 
 9612: =item *
 9613: 
 9614: condval($condidx) : value of condition index based on state
 9615: 
 9616: =item *
 9617: 
 9618: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9619: resource's metadata, $what should be either a specific key, or either
 9620: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9621: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9622: 
 9623: this function automatically caches all requests
 9624: 
 9625: =item *
 9626: 
 9627: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9628: network of library servers; returns file handle of where SQL and regex results
 9629: will be stored for query
 9630: 
 9631: =item *
 9632: 
 9633: symbread($filename) : return symbolic list entry (filename argument optional);
 9634: returns the data handle
 9635: 
 9636: =item *
 9637: 
 9638: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9639: a possible symb for the URL in $thisfn, and if is an encryypted
 9640: resource that the user accessed using /enc/ returns a 1 on success, 0
 9641: on failure, user must be in a course, as it assumes the existance of
 9642: the course initial hash, and uses $env('request.course.id'}
 9643: 
 9644: 
 9645: =item *
 9646: 
 9647: symbclean($symb) : removes versions numbers from a symb, returns the
 9648: cleaned symb
 9649: 
 9650: =item *
 9651: 
 9652: is_on_map($uri) : checks if the $uri is somewhere on the current
 9653: course map, user must be in a course for it to work.
 9654: 
 9655: =item *
 9656: 
 9657: numval($salt) : return random seed value (addend for rndseed)
 9658: 
 9659: =item *
 9660: 
 9661: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9662: a random seed, all arguments are optional, if they aren't sent it uses the
 9663: environment to derive them. Note: if symb isn't sent and it can't get one
 9664: from &symbread it will use the current time as its return value
 9665: 
 9666: =item *
 9667: 
 9668: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9669: unfakeable, receipt
 9670: 
 9671: =item *
 9672: 
 9673: receipt() : API to ireceipt working off of env values; given out to users
 9674: 
 9675: =item *
 9676: 
 9677: countacc($url) : count the number of accesses to a given URL
 9678: 
 9679: =item *
 9680: 
 9681: 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
 9682: 
 9683: =item *
 9684: 
 9685: 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)
 9686: 
 9687: =item *
 9688: 
 9689: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9690: 
 9691: =item *
 9692: 
 9693: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9694: forcing spreadsheet to reevaluate the resource scores next time.
 9695: 
 9696: =back
 9697: 
 9698: =head2 Storing/Retreiving Data
 9699: 
 9700: =over 4
 9701: 
 9702: =item *
 9703: 
 9704: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9705: for this url; hashref needs to be given and should be a \%hashname; the
 9706: remaining args aren't required and if they aren't passed or are '' they will
 9707: be derived from the env
 9708: 
 9709: =item *
 9710: 
 9711: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9712: uses critical subroutine
 9713: 
 9714: =item *
 9715: 
 9716: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9717: all args are optional
 9718: 
 9719: =item *
 9720: 
 9721: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9722: dumps the complete (or key matching regexp) namespace into a hash
 9723: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9724: normally &store()ed into
 9725: 
 9726: $range should be either an integer '100' (give me the first 100
 9727:                                            matching records)
 9728:               or be  two integers sperated by a - with no spaces
 9729:                  '30-50' (give me the 30th through the 50th matching
 9730:                           records)
 9731: 
 9732: 
 9733: =item *
 9734: 
 9735: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9736: replaces a &store() version of data with a replacement set of data
 9737: for a particular resource in a namespace passed in the $storehash hash 
 9738: reference
 9739: 
 9740: =item *
 9741: 
 9742: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9743: works very similar to store/cstore, but all data is stored in a
 9744: temporary location and can be reset using tmpreset, $storehash should
 9745: be a hash reference, returns nothing on success
 9746: 
 9747: =item *
 9748: 
 9749: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9750: similar to restore, but all data is stored in a temporary location and
 9751: can be reset using tmpreset. Returns a hash of values on success,
 9752: error string otherwise.
 9753: 
 9754: =item *
 9755: 
 9756: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9757: deltes all keys for $symb form the temporary storage hash.
 9758: 
 9759: =item *
 9760: 
 9761: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9762: reference filled in from namesp ($udom and $uname are optional)
 9763: 
 9764: =item *
 9765: 
 9766: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9767: namesp ($udom and $uname are optional)
 9768: 
 9769: =item *
 9770: 
 9771: dump($namespace,$udom,$uname,$regexp,$range) : 
 9772: dumps the complete (or key matching regexp) namespace into a hash
 9773: ($udom, $uname, $regexp, $range are optional)
 9774: 
 9775: $range should be either an integer '100' (give me the first 100
 9776:                                            matching records)
 9777:               or be  two integers sperated by a - with no spaces
 9778:                  '30-50' (give me the 30th through the 50th matching
 9779:                           records)
 9780: =item *
 9781: 
 9782: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9783: $store can be a scalar, an array reference, or if the amount to be 
 9784: incremented is > 1, a hash reference.
 9785: 
 9786: ($udom and $uname are optional)
 9787: 
 9788: =item *
 9789: 
 9790: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9791: ($udom and $uname are optional)
 9792: 
 9793: =item *
 9794: 
 9795: cput($namespace,$storehash,$udom,$uname) : critical put
 9796: ($udom and $uname are optional)
 9797: 
 9798: =item *
 9799: 
 9800: newput($namespace,$storehash,$udom,$uname) :
 9801: 
 9802: Attempts to store the items in the $storehash, but only if they don't
 9803: currently exist, if this succeeds you can be certain that you have 
 9804: successfully created a new key value pair in the $namespace db.
 9805: 
 9806: 
 9807: Args:
 9808:  $namespace: name of database to store values to
 9809:  $storehash: hashref to store to the db
 9810:  $udom: (optional) domain of user containing the db
 9811:  $uname: (optional) name of user caontaining the db
 9812: 
 9813: Returns:
 9814:  'ok' -> succeeded in storing all keys of $storehash
 9815:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9816:                         least <key> already existed in the db (other
 9817:                         requested keys may also already exist)
 9818:  'error: <msg>' -> unable to tie the DB or other error occurred
 9819:  'con_lost' -> unable to contact request server
 9820:  'refused' -> action was not allowed by remote machine
 9821: 
 9822: 
 9823: =item *
 9824: 
 9825: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9826: reference filled in from namesp (encrypts the return communication)
 9827: ($udom and $uname are optional)
 9828: 
 9829: =item *
 9830: 
 9831: log($udom,$name,$home,$message) : write to permanent log for user; use
 9832: critical subroutine
 9833: 
 9834: =item *
 9835: 
 9836: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9837: array reference filled in from namespace found in domain level on either
 9838: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9839: 
 9840: =item *
 9841: 
 9842: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9843: domain level either on specified domain server ($uhome) or primary domain 
 9844: server ($udom and $uhome are optional)
 9845: 
 9846: =item * 
 9847: 
 9848: get_domain_defaults($target_domain) : returns hash with defaults for
 9849: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9850: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9851: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9852: Values are retrieved from cache (if current), or from domain's configuration.db
 9853: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9854: or lonTabs/domain.tab. 
 9855: 
 9856: %domdefaults = &get_auth_defaults($target_domain);
 9857: 
 9858: =back
 9859: 
 9860: =head2 Network Status Functions
 9861: 
 9862: =over 4
 9863: 
 9864: =item *
 9865: 
 9866: dirlist($uri) : return directory list based on URI
 9867: 
 9868: =item *
 9869: 
 9870: spareserver() : find server with least workload from spare.tab
 9871: 
 9872: =back
 9873: 
 9874: =head2 Apache Request
 9875: 
 9876: =over 4
 9877: 
 9878: =item *
 9879: 
 9880: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9881: localhost, posts hash
 9882: 
 9883: =back
 9884: 
 9885: =head2 Data to String to Data
 9886: 
 9887: =over 4
 9888: 
 9889: =item *
 9890: 
 9891: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9892: and '&' separators, supports elements that are arrayrefs and hashrefs
 9893: 
 9894: =item *
 9895: 
 9896: hashref2str($hashref) : convert a hashref into a string complete with
 9897: escaping and '=' and '&' separators, supports elements that are
 9898: arrayrefs and hashrefs
 9899: 
 9900: =item *
 9901: 
 9902: arrayref2str($arrayref) : convert an arrayref into a string complete
 9903: with escaping and '&' separators, supports elements that are arrayrefs
 9904: and hashrefs
 9905: 
 9906: =item *
 9907: 
 9908: str2hash($string) : convert string to hash using unescaping and
 9909: splitting on '=' and '&', supports elements that are arrayrefs and
 9910: hashrefs
 9911: 
 9912: =item *
 9913: 
 9914: str2array($string) : convert string to hash using unescaping and
 9915: splitting on '&', supports elements that are arrayrefs and hashrefs
 9916: 
 9917: =back
 9918: 
 9919: =head2 Logging Routines
 9920: 
 9921: =over 4
 9922: 
 9923: These routines allow one to make log messages in the lonnet.log and
 9924: lonnet.perm logfiles.
 9925: 
 9926: =item *
 9927: 
 9928: logtouch() : make sure the logfile, lonnet.log, exists
 9929: 
 9930: =item *
 9931: 
 9932: logthis() : append message to the normal lonnet.log file, it gets
 9933: preiodically rolled over and deleted.
 9934: 
 9935: =item *
 9936: 
 9937: logperm() : append a permanent message to lonnet.perm.log, this log
 9938: file never gets deleted by any automated portion of the system, only
 9939: messages of critical importance should go in here.
 9940: 
 9941: =back
 9942: 
 9943: =head2 General File Helper Routines
 9944: 
 9945: =over 4
 9946: 
 9947: =item *
 9948: 
 9949: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9950: (a) files in /uploaded
 9951:   (i) If a local copy of the file exists - 
 9952:       compares modification date of local copy with last-modified date for 
 9953:       definitive version stored on home server for course. If local copy is 
 9954:       stale, requests a new version from the home server and stores it. 
 9955:       If the original has been removed from the home server, then local copy 
 9956:       is unlinked.
 9957:   (ii) If local copy does not exist -
 9958:       requests the file from the home server and stores it. 
 9959:   
 9960:   If $caller is 'uploadrep':  
 9961:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9962:     for request for files originally uploaded via DOCS. 
 9963:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9964:   
 9965:   Otherwise:
 9966:      This indicates a call from the content generation phase of the request.
 9967:      -  returns the entire contents of the file or -1.
 9968:      
 9969: (b) files in /res
 9970:    - returns the entire contents of a file or -1; 
 9971:    it properly subscribes to and replicates the file if neccessary.
 9972: 
 9973: 
 9974: =item *
 9975: 
 9976: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9977:                   reference
 9978: 
 9979: returns either a stat() list of data about the file or an empty list
 9980: if the file doesn't exist or couldn't find out about it (connection
 9981: problems or user unknown)
 9982: 
 9983: =item *
 9984: 
 9985: filelocation($dir,$file) : returns file system location of a file
 9986: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9987: directory that relative $file lookups are to looked in ($dir of /a/dir
 9988: and a file of ../bob will become /a/bob)
 9989: 
 9990: =item *
 9991: 
 9992: hreflocation($dir,$file) : returns file system location or a URL; same as
 9993: filelocation except for hrefs
 9994: 
 9995: =item *
 9996: 
 9997: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9998: 
 9999: =back
10000: 
10001: =head2 Usererfile file routines (/uploaded*)
10002: 
10003: =over 4
10004: 
10005: =item *
10006: 
10007: userfileupload(): main rotine for putting a file in a user or course's
10008:                   filespace, arguments are,
10009: 
10010:  formname - required - this is the name of the element in $env where the
10011:            filename, and the contents of the file to create/modifed exist
10012:            the filename is in $env{'form.'.$formname.'.filename'} and the
10013:            contents of the file is located in $env{'form.'.$formname}
10014:  coursedoc - if true, store the file in the course of the active role
10015:              of the current user
10016:  subdir - required - subdirectory to put the file in under ../userfiles/
10017:          if undefined, it will be placed in "unknown"
10018: 
10019:  (This routine calls clean_filename() to remove any dangerous
10020:  characters from the filename, and then calls finuserfileupload() to
10021:  complete the transaction)
10022: 
10023:  returns either the url of the uploaded file (/uploaded/....) if successful
10024:  and /adm/notfound.html if unsuccessful
10025: 
10026: =item *
10027: 
10028: clean_filename(): routine for cleaing a filename up for storage in
10029:                  userfile space, argument is:
10030: 
10031:  filename - proposed filename
10032: 
10033: returns: the new clean filename
10034: 
10035: =item *
10036: 
10037: finishuserfileupload(): routine that creaes and sends the file to
10038: userspace, probably shouldn't be called directly
10039: 
10040:   docuname: username or courseid of destination for the file
10041:   docudom: domain of user/course of destination for the file
10042:   formname: same as for userfileupload()
10043:   fname: filename (inculding subdirectories) for the file
10044: 
10045:  returns either the url of the uploaded file (/uploaded/....) if successful
10046:  and /adm/notfound.html if unsuccessful
10047: 
10048: =item *
10049: 
10050: renameuserfile(): renames an existing userfile to a new name
10051: 
10052:   Args:
10053:    docuname: username or courseid of destination for the file
10054:    docudom: domain of user/course of destination for the file
10055:    old: current file name (including any subdirs under userfiles)
10056:    new: desired file name (including any subdirs under userfiles)
10057: 
10058: =item *
10059: 
10060: mkdiruserfile(): creates a directory is a userfiles dir
10061: 
10062:   Args:
10063:    docuname: username or courseid of destination for the file
10064:    docudom: domain of user/course of destination for the file
10065:    dir: dir to create (including any subdirs under userfiles)
10066: 
10067: =item *
10068: 
10069: removeuserfile(): removes a file that exists in userfiles
10070: 
10071:   Args:
10072:    docuname: username or courseid of destination for the file
10073:    docudom: domain of user/course of destination for the file
10074:    fname: filname to delete (including any subdirs under userfiles)
10075: 
10076: =item *
10077: 
10078: removeuploadedurl(): convience function for removeuserfile()
10079: 
10080:   Args:
10081:    url:  a full /uploaded/... url to delete
10082: 
10083: =item * 
10084: 
10085: get_portfile_permissions():
10086:   Args:
10087:     domain: domain of user or course contain the portfolio files
10088:     user: name of user or num of course contain the portfolio files
10089:   Returns:
10090:     hashref of a dump of the proper file_permissions.db
10091:    
10092: 
10093: =item * 
10094: 
10095: get_access_controls():
10096: 
10097: Args:
10098:   current_permissions: the hash ref returned from get_portfile_permissions()
10099:   group: (optional) the group you want the files associated with
10100:   file: (optional) the file you want access info on
10101: 
10102: Returns:
10103:     a hash (keys are file names) of hashes containing
10104:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10105:         values are XML containing access control settings (see below) 
10106: 
10107: Internal notes:
10108: 
10109:  access controls are stored in file_permissions.db as key=value pairs.
10110:     key -> path to file/file_name\0uniqueID:scope_end_start
10111:         where scope -> public,guest,course,group,domains or users.
10112:               end -> UNIX time for end of access (0 -> no end date)
10113:               start -> UNIX time for start of access
10114: 
10115:     value -> XML description of access control
10116:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10117:             <start></start>
10118:             <end></end>
10119: 
10120:             <password></password>  for scope type = guest
10121: 
10122:             <domain></domain>     for scope type = course or group
10123:             <number></number>
10124:             <roles id="">
10125:              <role></role>
10126:              <access></access>
10127:              <section></section>
10128:              <group></group>
10129:             </roles>
10130: 
10131:             <dom></dom>         for scope type = domains
10132: 
10133:             <users>             for scope type = users
10134:              <user>
10135:               <uname></uname>
10136:               <udom></udom>
10137:              </user>
10138:             </users>
10139:            </scope> 
10140:               
10141:  Access data is also aggregated for each file in an additional key=value pair:
10142:  key -> path to file/file_name\0accesscontrol 
10143:  value -> reference to hash
10144:           hash contains key = value pairs
10145:           where key = uniqueID:scope_end_start
10146:                 value = UNIX time record was last updated
10147: 
10148:           Used to improve speed of look-ups of access controls for each file.  
10149:  
10150:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10151: 
10152: modify_access_controls():
10153: 
10154: Modifies access controls for a portfolio file
10155: Args
10156: 1. file name
10157: 2. reference to hash of required changes,
10158: 3. domain
10159: 4. username
10160:   where domain,username are the domain of the portfolio owner 
10161:   (either a user or a course) 
10162: 
10163: Returns:
10164: 1. result of additions or updates ('ok' or 'error', with error message). 
10165: 2. result of deletions ('ok' or 'error', with error message).
10166: 3. reference to hash of any new or updated access controls.
10167: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10168:    key = integer (inbound ID)
10169:    value = uniqueID  
10170: 
10171: =back
10172: 
10173: =head2 HTTP Helper Routines
10174: 
10175: =over 4
10176: 
10177: =item *
10178: 
10179: escape() : unpack non-word characters into CGI-compatible hex codes
10180: 
10181: =item *
10182: 
10183: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10184: 
10185: =back
10186: 
10187: =head1 PRIVATE SUBROUTINES
10188: 
10189: =head2 Underlying communication routines (Shouldn't call)
10190: 
10191: =over 4
10192: 
10193: =item *
10194: 
10195: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10196: 
10197: =item *
10198: 
10199: reply() : uses subreply to send a message to remote machine, logs all failures
10200: 
10201: =item *
10202: 
10203: critical() : passes a critical message to another server; if cannot
10204: get through then place message in connection buffer directory and
10205: returns con_delayed, if incapable of saving message, returns
10206: con_failed
10207: 
10208: =item *
10209: 
10210: reconlonc() : tries to reconnect lonc client processes.
10211: 
10212: =back
10213: 
10214: =head2 Resource Access Logging
10215: 
10216: =over 4
10217: 
10218: =item *
10219: 
10220: flushcourselogs() : flush (save) buffer logs and access logs
10221: 
10222: =item *
10223: 
10224: courselog($what) : save message for course in hash
10225: 
10226: =item *
10227: 
10228: courseacclog($what) : save message for course using &courselog().  Perform
10229: special processing for specific resource types (problems, exams, quizzes, etc).
10230: 
10231: =item *
10232: 
10233: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10234: as a PerlChildExitHandler
10235: 
10236: =back
10237: 
10238: =head2 Other
10239: 
10240: =over 4
10241: 
10242: =item *
10243: 
10244: symblist($mapname,%newhash) : update symbolic storage links
10245: 
10246: =back
10247: 
10248: =cut
10249: 

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