File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.986: download - view: text, annotated - select for diffs
Tue Feb 10 11:15:16 2009 UTC (15 years, 5 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Added host_from_dns to translate dns hostnames -> loncapa hostnames.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.986 2009/02/10 11:15:16 foxr 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: use IO::Socket;
   78: 
   79: # use Date::Parse;
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol);
   82: 
   83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   86:     %courseownerbuf, %coursetypebuf,$locknum);
   87: 
   88: use IO::Socket;
   89: use GDBM_File;
   90: use HTML::LCParser;
   91: use Fcntl qw(:flock);
   92: use Storable qw(thaw nfreeze);
   93: use Time::HiRes qw( gettimeofday tv_interval );
   94: use Cache::Memcached;
   95: use Digest::MD5;
   96: use Math::Random;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: 
  100: my $readit;
  101: my $max_connection_retries = 10;     # Or some such value.
  102: 
  103: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  104: 
  105: require Exporter;
  106: 
  107: our @ISA = qw (Exporter);
  108: our @EXPORT = qw(%env);
  109: 
  110: 
  111: # --------------------------------------------------------------------- Logging
  112: {
  113:     my $logid;
  114:     sub instructor_log {
  115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  116:         if (($cnum eq '') || ($cdom eq '')) {
  117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  119:         }
  120: 	$logid++;
  121:         my $now = time();
  122: 	my $id=$now.'00000'.$$.'00000'.$logid;
  123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  124: 				    { $id => {
  125: 					'exe_uname' => $env{'user.name'},
  126: 					'exe_udom'  => $env{'user.domain'},
  127: 					'exe_time'  => $now,
  128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  129: 					'delflag'   => $delflag,
  130: 					'logentry'  => $storehash,
  131: 					'uname'     => $uname,
  132: 					'udom'      => $udom,
  133: 				    }
  134: 				  },$cdom,$cnum);
  135:     }
  136: }
  137: 
  138: sub logtouch {
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     unless (-e "$execdir/logs/lonnet.log") {	
  141: 	open(my $fh,">>$execdir/logs/lonnet.log");
  142: 	close $fh;
  143:     }
  144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  146: }
  147: 
  148: sub logthis {
  149:     my $message=shift;
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     my $now=time;
  152:     my $local=localtime($now);
  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  155: 	print $fh $logstring;
  156: 	close($fh);
  157:     }
  158:     return 1;
  159: }
  160: 
  161: sub logperm {
  162:     my $message=shift;
  163:     my $execdir=$perlvar{'lonDaemons'};
  164:     my $now=time;
  165:     my $local=localtime($now);
  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  167: 	print $fh "$now:$message:$local\n";
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub create_connection {
  174:     my ($hostname,$lonid) = @_;
  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  176: 				     Type    => SOCK_STREAM,
  177: 				     Timeout => 10);
  178:     return 0 if (!$client);
  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  180:     my $result = <$client>;
  181:     chomp($result);
  182:     return 1 if ($result eq 'done');
  183:     return 0;
  184: }
  185: 
  186: sub get_server_timezone {
  187:     my ($cnum,$cdom) = @_;
  188:     my $home=&homeserver($cnum,$cdom);
  189:     if ($home ne 'no_host') {
  190:         my $cachetime = 24*3600;
  191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  192:         if (defined($cached)) {
  193:             return $timezone;
  194:         } else {
  195:             my $timezone = &reply('servertimezone',$home);
  196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  197:         }
  198:     }
  199: }
  200: 
  201: # -------------------------------------------------- Non-critical communication
  202: sub subreply {
  203:     my ($cmd,$server)=@_;
  204:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  205:     #
  206:     #  With loncnew process trimming, there's a timing hole between lonc server
  207:     #  process exit and the master server picking up the listen on the AF_UNIX
  208:     #  socket.  In that time interval, a lock file will exist:
  209: 
  210:     my $lockfile=$peerfile.".lock";
  211:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  212: 	sleep(1);
  213:     }
  214:     # At this point, either a loncnew parent is listening or an old lonc
  215:     # or loncnew child is listening so we can connect or everything's dead.
  216:     #
  217:     #   We'll give the connection a few tries before abandoning it.  If
  218:     #   connection is not possible, we'll con_lost back to the client.
  219:     #   
  220:     my $client;
  221:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  222: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  223: 				      Type    => SOCK_STREAM,
  224: 				      Timeout => 10);
  225: 	if ($client) {
  226: 	    last;		# Connected!
  227: 	} else {
  228: 	    &create_connection(&hostname($server),$server);
  229: 	}
  230:         sleep(1);		# Try again later if failed connection.
  231:     }
  232:     my $answer;
  233:     if ($client) {
  234: 	print $client "sethost:$server:$cmd\n";
  235: 	$answer=<$client>;
  236: 	if (!$answer) { $answer="con_lost"; }
  237: 	chomp($answer);
  238:     } else {
  239: 	$answer = 'con_lost';	# Failed connection.
  240:     }
  241:     return $answer;
  242: }
  243: 
  244: sub reply {
  245:     my ($cmd,$server)=@_;
  246:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  247:     my $answer=subreply($cmd,$server);
  248:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  249:        &logthis("<font color=\"blue\">WARNING:".
  250:                 " $cmd to $server returned $answer</font>");
  251:     }
  252:     return $answer;
  253: }
  254: 
  255: # ----------------------------------------------------------- Send USR1 to lonc
  256: 
  257: sub reconlonc {
  258:     my ($lonid) = @_;
  259:     my $hostname = &hostname($lonid);
  260:     if ($lonid) {
  261: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  262: 	if ($hostname && -e $peerfile) {
  263: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  264: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  265: 					     Type    => SOCK_STREAM,
  266: 					     Timeout => 10);
  267: 	    if ($client) {
  268: 		print $client ("reset_retries\n");
  269: 		my $answer=<$client>;
  270: 		#reset just this one.
  271: 	    }
  272: 	}
  273: 	return;
  274:     }
  275: 
  276:     &logthis("Trying to reconnect lonc");
  277:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  278:     if (open(my $fh,"<$loncfile")) {
  279: 	my $loncpid=<$fh>;
  280:         chomp($loncpid);
  281:         if (kill 0 => $loncpid) {
  282: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  283:             kill USR1 => $loncpid;
  284:             sleep 1;
  285:          } else {
  286: 	    &logthis(
  287:                "<font color=\"blue\">WARNING:".
  288:                " lonc at pid $loncpid not responding, giving up</font>");
  289:         }
  290:     } else {
  291: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  292:     }
  293: }
  294: 
  295: # ------------------------------------------------------ Critical communication
  296: 
  297: sub critical {
  298:     my ($cmd,$server)=@_;
  299:     unless (&hostname($server)) {
  300:         &logthis("<font color=\"blue\">WARNING:".
  301:                " Critical message to unknown server ($server)</font>");
  302:         return 'no_such_host';
  303:     }
  304:     my $answer=reply($cmd,$server);
  305:     if ($answer eq 'con_lost') {
  306: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  307: 	my $answer=reply($cmd,$server);
  308:         if ($answer eq 'con_lost') {
  309:             my $now=time;
  310:             my $middlename=$cmd;
  311:             $middlename=substr($middlename,0,16);
  312:             $middlename=~s/\W//g;
  313:             my $dfilename=
  314:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  315:             $dumpcount++;
  316:             {
  317: 		my $dfh;
  318: 		if (open($dfh,">$dfilename")) {
  319: 		    print $dfh "$cmd\n"; 
  320: 		    close($dfh);
  321: 		}
  322:             }
  323:             sleep 2;
  324:             my $wcmd='';
  325:             {
  326: 		my $dfh;
  327: 		if (open($dfh,"<$dfilename")) {
  328: 		    $wcmd=<$dfh>; 
  329: 		    close($dfh);
  330: 		}
  331:             }
  332:             chomp($wcmd);
  333:             if ($wcmd eq $cmd) {
  334: 		&logthis("<font color=\"blue\">WARNING: ".
  335:                          "Connection buffer $dfilename: $cmd</font>");
  336:                 &logperm("D:$server:$cmd");
  337: 	        return 'con_delayed';
  338:             } else {
  339:                 &logthis("<font color=\"red\">CRITICAL:"
  340:                         ." Critical connection failed: $server $cmd</font>");
  341:                 &logperm("F:$server:$cmd");
  342:                 return 'con_failed';
  343:             }
  344:         }
  345:     }
  346:     return $answer;
  347: }
  348: 
  349: # ------------------------------------------- check if return value is an error
  350: 
  351: sub error {
  352:     my ($result) = @_;
  353:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  354: 	if ($2 == 2) { return undef; }
  355: 	return $1;
  356:     }
  357:     return undef;
  358: }
  359: 
  360: sub convert_and_load_session_env {
  361:     my ($lonidsdir,$handle)=@_;
  362:     my @profile;
  363:     {
  364: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  365: 	if (!$opened) {
  366: 	    return 0;
  367: 	}
  368: 	flock($idf,LOCK_SH);
  369: 	@profile=<$idf>;
  370: 	close($idf);
  371:     }
  372:     my %temp_env;
  373:     foreach my $line (@profile) {
  374: 	if ($line !~ m/=/) {
  375: 	    return 0;
  376: 	}
  377: 	chomp($line);
  378: 	my ($envname,$envvalue)=split(/=/,$line,2);
  379: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  380:     }
  381:     unlink("$lonidsdir/$handle.id");
  382:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  383: 	    0640)) {
  384: 	%disk_env = %temp_env;
  385: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  386: 	untie(%disk_env);
  387:     }
  388:     return 1;
  389: }
  390: 
  391: # ------------------------------------------- Transfer profile into environment
  392: my $env_loaded;
  393: sub transfer_profile_to_env {
  394:     my ($lonidsdir,$handle,$force_transfer) = @_;
  395:     if (!$force_transfer && $env_loaded) { return; } 
  396: 
  397:     if (!defined($lonidsdir)) {
  398: 	$lonidsdir = $perlvar{'lonIDsDir'};
  399:     }
  400:     if (!defined($handle)) {
  401:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  402:     }
  403: 
  404:     my $convert;
  405:     {
  406:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  407: 	if (!$opened) {
  408: 	    return;
  409: 	}
  410: 	flock($idf,LOCK_SH);
  411: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  412: 		&GDBM_READER(),0640)) {
  413: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  414: 	    untie(%disk_env);
  415: 	} else {
  416: 	    $convert = 1;
  417: 	}
  418:     }
  419:     if ($convert) {
  420: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  421: 	    &logthis("Failed to load session, or convert session.");
  422: 	}
  423:     }
  424: 
  425:     my %remove;
  426:     while ( my $envname = each(%env) ) {
  427:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  428:             if ($time < time-300) {
  429:                 $remove{$key}++;
  430:             }
  431:         }
  432:     }
  433: 
  434:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  435:     $env_loaded=1;
  436:     foreach my $expired_key (keys(%remove)) {
  437:         &delenv($expired_key);
  438:     }
  439: }
  440: 
  441: # ---------------------------------------------------- Check for valid session 
  442: sub check_for_valid_session {
  443:     my ($r) = @_;
  444:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  445:     my $lonid=$cookies{'lonID'};
  446:     return undef if (!$lonid);
  447: 
  448:     my $handle=&LONCAPA::clean_handle($lonid->value);
  449:     my $lonidsdir=$r->dir_config('lonIDsDir');
  450:     return undef if (!-e "$lonidsdir/$handle.id");
  451: 
  452:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  453:     return undef if (!$opened);
  454: 
  455:     flock($idf,LOCK_SH);
  456:     my %disk_env;
  457:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  458: 	    &GDBM_READER(),0640)) {
  459: 	return undef;	
  460:     }
  461: 
  462:     if (!defined($disk_env{'user.name'})
  463: 	|| !defined($disk_env{'user.domain'})) {
  464: 	return undef;
  465:     }
  466:     return $handle;
  467: }
  468: 
  469: sub timed_flock {
  470:     my ($file,$lock_type) = @_;
  471:     my $failed=0;
  472:     eval {
  473: 	local $SIG{__DIE__}='DEFAULT';
  474: 	local $SIG{ALRM}=sub {
  475: 	    $failed=1;
  476: 	    die("failed lock");
  477: 	};
  478: 	alarm(13);
  479: 	flock($file,$lock_type);
  480: 	alarm(0);
  481:     };
  482:     if ($failed) {
  483: 	return undef;
  484:     } else {
  485: 	return 1;
  486:     }
  487: }
  488: 
  489: # ---------------------------------------------------------- Append Environment
  490: 
  491: sub appenv {
  492:     my ($newenv,$roles) = @_;
  493:     if (ref($newenv) eq 'HASH') {
  494:         foreach my $key (keys(%{$newenv})) {
  495:             my $refused = 0;
  496: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  497:                 $refused = 1;
  498:                 if (ref($roles) eq 'ARRAY') {
  499:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  500:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  501:                         $refused = 0;
  502:                     }
  503:                 }
  504:             }
  505:             if ($refused) {
  506:                 &logthis("<font color=\"blue\">WARNING: ".
  507:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  508:                          .'</font>');
  509: 	        delete($newenv->{$key});
  510:             } else {
  511:                 $env{$key}=$newenv->{$key};
  512:             }
  513:         }
  514:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  515:         if ($opened
  516: 	    && &timed_flock($env_file,LOCK_EX)
  517: 	    &&
  518: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  519: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  520: 	    while (my ($key,$value) = each(%{$newenv})) {
  521: 	        $disk_env{$key} = $value;
  522: 	    }
  523: 	    untie(%disk_env);
  524:         }
  525:     }
  526:     return 'ok';
  527: }
  528: # ----------------------------------------------------- Delete from Environment
  529: 
  530: sub delenv {
  531:     my $delthis=shift;
  532:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  533:         &logthis("<font color=\"blue\">WARNING: ".
  534:                 "Attempt to delete from environment ".$delthis);
  535:         return 'error';
  536:     }
  537:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  538:     if ($opened
  539: 	&& &timed_flock($env_file,LOCK_EX)
  540: 	&&
  541: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  542: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  543: 	foreach my $key (keys(%disk_env)) {
  544: 	    if ($key=~/^\Q$delthis\E/) { 
  545: 		delete($env{$key});
  546: 		delete($disk_env{$key});
  547: 	    }
  548: 	}
  549: 	untie(%disk_env);
  550:     }
  551:     return 'ok';
  552: }
  553: 
  554: sub get_env_multiple {
  555:     my ($name) = @_;
  556:     my @values;
  557:     if (defined($env{$name})) {
  558:         # exists is it an array
  559:         if (ref($env{$name})) {
  560:             @values=@{ $env{$name} };
  561:         } else {
  562:             $values[0]=$env{$name};
  563:         }
  564:     }
  565:     return(@values);
  566: }
  567: 
  568: # ------------------------------------------------------------------- Locking
  569: 
  570: sub set_lock {
  571:     my ($text)=@_;
  572:     $locknum++;
  573:     my $id=$$.'-'.$locknum;
  574:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  575:              'session.lock.'.$id => $text});
  576:     return $id;
  577: }
  578: 
  579: sub get_locks {
  580:     my $num=0;
  581:     my %texts=();
  582:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  583:        if ($lock=~/\w/) {
  584:           $num++;
  585:           $texts{$lock}=$env{'session.lock.'.$lock};
  586:        }
  587:    }
  588:    return ($num,%texts);
  589: }
  590: 
  591: sub remove_lock {
  592:     my ($id)=@_;
  593:     my $newlocks='';
  594:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  595:        if (($lock=~/\w/) && ($lock ne $id)) {
  596:           $newlocks.=','.$lock;
  597:        }
  598:     }
  599:     &appenv({'session.locks' => $newlocks});
  600:     &delenv('session.lock.'.$id);
  601: }
  602: 
  603: sub remove_all_locks {
  604:     my $activelocks=$env{'session.locks'};
  605:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  606:        if ($lock=~/\w/) {
  607:           &remove_lock($lock);
  608:        }
  609:     }
  610: }
  611: 
  612: 
  613: # ------------------------------------------ Find out current server userload
  614: sub userload {
  615:     my $numusers=0;
  616:     {
  617: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  618: 	my $filename;
  619: 	my $curtime=time;
  620: 	while ($filename=readdir(LONIDS)) {
  621: 	    next if ($filename eq '.' || $filename eq '..');
  622: 	    next if ($filename =~ /publicuser_\d+\.id/);
  623: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  624: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  625: 	}
  626: 	closedir(LONIDS);
  627:     }
  628:     my $userloadpercent=0;
  629:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  630:     if ($maxuserload) {
  631: 	$userloadpercent=100*$numusers/$maxuserload;
  632:     }
  633:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  634:     return $userloadpercent;
  635: }
  636: 
  637: # ------------------------------------------ Fight off request when overloaded
  638: 
  639: sub overloaderror {
  640:     my ($r,$checkserver)=@_;
  641:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  642:     my $loadavg;
  643:     if ($checkserver eq $perlvar{'lonHostID'}) {
  644:        open(my $loadfile,'/proc/loadavg');
  645:        $loadavg=<$loadfile>;
  646:        $loadavg =~ s/\s.*//g;
  647:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  648:        close($loadfile);
  649:     } else {
  650:        $loadavg=&reply('load',$checkserver);
  651:     }
  652:     my $overload=$loadavg-100;
  653:     if ($overload>0) {
  654: 	$r->err_headers_out->{'Retry-After'}=$overload;
  655:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  656:         return 413;
  657:     }    
  658:     return '';
  659: }
  660: 
  661: # ------------------------------ Find server with least workload from spare.tab
  662: 
  663: sub spareserver {
  664:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  665:     my $spare_server;
  666:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  667:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  668:                                                      :  $userloadpercent;
  669:     
  670:     foreach my $try_server (@{ $spareid{'primary'} }) {
  671: 	($spare_server, $lowest_load) =
  672: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  673:     }
  674: 
  675:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  676: 
  677:     if (!$found_server) {
  678: 	foreach my $try_server (@{ $spareid{'default'} }) {
  679: 	    ($spare_server, $lowest_load) =
  680: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  681: 	}
  682:     }
  683: 
  684:     if (!$want_server_name) {
  685:         my $protocol = 'http';
  686:         if ($protocol{$spare_server} eq 'https') {
  687:             $protocol = $protocol{$spare_server};
  688:         }
  689: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  690:     }
  691:     return $spare_server;
  692: }
  693: 
  694: sub compare_server_load {
  695:     my ($try_server, $spare_server, $lowest_load) = @_;
  696: 
  697:     my $loadans     = &reply('load',    $try_server);
  698:     my $userloadans = &reply('userload',$try_server);
  699: 
  700:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  701: 	next; #didn't get a number from the server
  702:     }
  703: 
  704:     my $load;
  705:     if ($loadans =~ /\d/) {
  706: 	if ($userloadans =~ /\d/) {
  707: 	    #both are numbers, pick the bigger one
  708: 	    $load = ($loadans > $userloadans) ? $loadans 
  709: 		                              : $userloadans;
  710: 	} else {
  711: 	    $load = $loadans;
  712: 	}
  713:     } else {
  714: 	$load = $userloadans;
  715:     }
  716: 
  717:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  718: 	$spare_server = $try_server;
  719: 	$lowest_load  = $load;
  720:     }
  721:     return ($spare_server,$lowest_load);
  722: }
  723: 
  724: # --------------------------- ask offload servers if user already has a session
  725: sub find_existing_session {
  726:     my ($udom,$uname) = @_;
  727:     foreach my $try_server (@{ $spareid{'primary'} },
  728: 			    @{ $spareid{'default'} }) {
  729: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  730:     }
  731:     return;
  732: }
  733: 
  734: # -------------------------------- ask if server already has a session for user
  735: sub has_user_session {
  736:     my ($lonid,$udom,$uname) = @_;
  737:     my $result = &reply(join(':','userhassession',
  738: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  739:     return 1 if ($result eq 'ok');
  740: 
  741:     return 0;
  742: }
  743: 
  744: # --------------------------------------------- Try to change a user's password
  745: 
  746: sub changepass {
  747:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  748:     $currentpass = &escape($currentpass);
  749:     $newpass     = &escape($newpass);
  750:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  751: 		       $server);
  752:     if (! $answer) {
  753: 	&logthis("No reply on password change request to $server ".
  754: 		 "by $uname in domain $udom.");
  755:     } elsif ($answer =~ "^ok") {
  756:         &logthis("$uname in $udom successfully changed their password ".
  757: 		 "on $server.");
  758:     } elsif ($answer =~ "^pwchange_failure") {
  759: 	&logthis("$uname in $udom was unable to change their password ".
  760: 		 "on $server.  The action was blocked by either lcpasswd ".
  761: 		 "or pwchange");
  762:     } elsif ($answer =~ "^non_authorized") {
  763:         &logthis("$uname in $udom did not get their password correct when ".
  764: 		 "attempting to change it on $server.");
  765:     } elsif ($answer =~ "^auth_mode_error") {
  766:         &logthis("$uname in $udom attempted to change their password despite ".
  767: 		 "not being locally or internally authenticated on $server.");
  768:     } elsif ($answer =~ "^unknown_user") {
  769:         &logthis("$uname in $udom attempted to change their password ".
  770: 		 "on $server but were unable to because $server is not ".
  771: 		 "their home server.");
  772:     } elsif ($answer =~ "^refused") {
  773: 	&logthis("$server refused to change $uname in $udom password because ".
  774: 		 "it was sent an unencrypted request to change the password.");
  775:     }
  776:     return $answer;
  777: }
  778: 
  779: # ----------------------- Try to determine user's current authentication scheme
  780: 
  781: sub queryauthenticate {
  782:     my ($uname,$udom)=@_;
  783:     my $uhome=&homeserver($uname,$udom);
  784:     if (!$uhome) {
  785: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  786: 	return 'no_host';
  787:     }
  788:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  789:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  790: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  791:     }
  792:     return $answer;
  793: }
  794: 
  795: # --------- Try to authenticate user from domain's lib servers (first this one)
  796: 
  797: sub authenticate {
  798:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  799:     $upass=&escape($upass);
  800:     $uname= &LONCAPA::clean_username($uname);
  801:     my $uhome=&homeserver($uname,$udom,1);
  802:     my $newhome;
  803:     if ((!$uhome) || ($uhome eq 'no_host')) {
  804: # Maybe the machine was offline and only re-appeared again recently?
  805:         &reconlonc();
  806: # One more
  807: 	$uhome=&homeserver($uname,$udom,1);
  808:         if (($uhome eq 'no_host') && $checkdefauth) {
  809:             if (defined(&domain($udom,'primary'))) {
  810:                 $newhome=&domain($udom,'primary');
  811:             }
  812:             if ($newhome ne '') {
  813:                 $uhome = $newhome;
  814:             }
  815:         }
  816: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  817: 	    &logthis("User $uname at $udom is unknown in authenticate");
  818: 	    return 'no_host';
  819:         }
  820:     }
  821:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  822:     if ($answer eq 'authorized') {
  823:         if ($newhome) {
  824:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  825:             return 'no_account_on_host'; 
  826:         } else {
  827:             &logthis("User $uname at $udom authorized by $uhome");
  828:             return $uhome;
  829:         }
  830:     }
  831:     if ($answer eq 'non_authorized') {
  832: 	&logthis("User $uname at $udom rejected by $uhome");
  833: 	return 'no_host'; 
  834:     }
  835:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  836:     return 'no_host';
  837: }
  838: 
  839: # ---------------------- Find the homebase for a user from domain's lib servers
  840: 
  841: my %homecache;
  842: sub homeserver {
  843:     my ($uname,$udom,$ignoreBadCache)=@_;
  844:     my $index="$uname:$udom";
  845: 
  846:     if (exists($homecache{$index})) { return $homecache{$index}; }
  847: 
  848:     my %servers = &get_servers($udom,'library');
  849:     foreach my $tryserver (keys(%servers)) {
  850:         next if ($ignoreBadCache ne 'true' && 
  851: 		 exists($badServerCache{$tryserver}));
  852: 
  853: 	my $answer=reply("home:$udom:$uname",$tryserver);
  854: 	if ($answer eq 'found') {
  855: 	    delete($badServerCache{$tryserver}); 
  856: 	    return $homecache{$index}=$tryserver;
  857: 	} elsif ($answer eq 'no_host') {
  858: 	    $badServerCache{$tryserver}=1;
  859: 	}
  860:     }    
  861:     return 'no_host';
  862: }
  863: 
  864: # ------------------------------------- Find the usernames behind a list of IDs
  865: 
  866: sub idget {
  867:     my ($udom,@ids)=@_;
  868:     my %returnhash=();
  869:     
  870:     my %servers = &get_servers($udom,'library');
  871:     foreach my $tryserver (keys(%servers)) {
  872: 	my $idlist=join('&',@ids);
  873: 	$idlist=~tr/A-Z/a-z/; 
  874: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  875: 	my @answer=();
  876: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  877: 	    @answer=split(/\&/,$reply);
  878: 	}                    ;
  879: 	my $i;
  880: 	for ($i=0;$i<=$#ids;$i++) {
  881: 	    if ($answer[$i]) {
  882: 		$returnhash{$ids[$i]}=$answer[$i];
  883: 	    } 
  884: 	}
  885:     } 
  886:     return %returnhash;
  887: }
  888: 
  889: # ------------------------------------- Find the IDs behind a list of usernames
  890: 
  891: sub idrget {
  892:     my ($udom,@unames)=@_;
  893:     my %returnhash=();
  894:     foreach my $uname (@unames) {
  895:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  896:     }
  897:     return %returnhash;
  898: }
  899: 
  900: # ------------------------------- Store away a list of names and associated IDs
  901: 
  902: sub idput {
  903:     my ($udom,%ids)=@_;
  904:     my %servers=();
  905:     foreach my $uname (keys(%ids)) {
  906: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  907:         my $uhom=&homeserver($uname,$udom);
  908:         if ($uhom ne 'no_host') {
  909:             my $id=&escape($ids{$uname});
  910:             $id=~tr/A-Z/a-z/;
  911:             my $esc_unam=&escape($uname);
  912: 	    if ($servers{$uhom}) {
  913: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  914:             } else {
  915:                 $servers{$uhom}=$id.'='.$esc_unam;
  916:             }
  917:         }
  918:     }
  919:     foreach my $server (keys(%servers)) {
  920:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  921:     }
  922: }
  923: 
  924: # ------------------------------------------- get items from domain db files   
  925: 
  926: sub get_dom {
  927:     my ($namespace,$storearr,$udom,$uhome)=@_;
  928:     my $items='';
  929:     foreach my $item (@$storearr) {
  930:         $items.=&escape($item).'&';
  931:     }
  932:     $items=~s/\&$//;
  933:     if (!$udom) {
  934:         $udom=$env{'user.domain'};
  935:         if (defined(&domain($udom,'primary'))) {
  936:             $uhome=&domain($udom,'primary');
  937:         } else {
  938:             undef($uhome);
  939:         }
  940:     } else {
  941:         if (!$uhome) {
  942:             if (defined(&domain($udom,'primary'))) {
  943:                 $uhome=&domain($udom,'primary');
  944:             }
  945:         }
  946:     }
  947:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  948:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  949:         my %returnhash;
  950:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  951:             return %returnhash;
  952:         }
  953:         my @pairs=split(/\&/,$rep);
  954:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  955:             return @pairs;
  956:         }
  957:         my $i=0;
  958:         foreach my $item (@$storearr) {
  959:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  960:             $i++;
  961:         }
  962:         return %returnhash;
  963:     } else {
  964:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  965:     }
  966: }
  967: 
  968: # -------------------------------------------- put items in domain db files 
  969: 
  970: sub put_dom {
  971:     my ($namespace,$storehash,$udom,$uhome)=@_;
  972:     if (!$udom) {
  973:         $udom=$env{'user.domain'};
  974:         if (defined(&domain($udom,'primary'))) {
  975:             $uhome=&domain($udom,'primary');
  976:         } else {
  977:             undef($uhome);
  978:         }
  979:     } else {
  980:         if (!$uhome) {
  981:             if (defined(&domain($udom,'primary'))) {
  982:                 $uhome=&domain($udom,'primary');
  983:             }
  984:         }
  985:     } 
  986:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  987:         my $items='';
  988:         foreach my $item (keys(%$storehash)) {
  989:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  990:         }
  991:         $items=~s/\&$//;
  992:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  993:     } else {
  994:         &logthis("put_dom failed - no homeserver and/or domain");
  995:     }
  996: }
  997: 
  998: sub retrieve_inst_usertypes {
  999:     my ($udom) = @_;
 1000:     my (%returnhash,@order);
 1001:     if (defined(&domain($udom,'primary'))) {
 1002:         my $uhome=&domain($udom,'primary');
 1003:         my $rep=&reply("inst_usertypes:$udom",$uhome);
 1004:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1005:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1006:             return (\%returnhash,\@order);
 1007:         }
 1008:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1009:         my @pairs=split(/\&/,$hashitems);
 1010:         foreach my $item (@pairs) {
 1011:             my ($key,$value)=split(/=/,$item,2);
 1012:             $key = &unescape($key);
 1013:             next if ($key =~ /^error: 2 /);
 1014:             $returnhash{$key}=&thaw_unescape($value);
 1015:         }
 1016:         my @esc_order = split(/\&/,$orderitems);
 1017:         foreach my $item (@esc_order) {
 1018:             push(@order,&unescape($item));
 1019:         }
 1020:     } else {
 1021:         &logthis("get_dom failed - no primary domain server for $udom");
 1022:     }
 1023:     return (\%returnhash,\@order);
 1024: }
 1025: 
 1026: sub is_domainimage {
 1027:     my ($url) = @_;
 1028:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1029:         if (&domain($1) ne '') {
 1030:             return '1';
 1031:         }
 1032:     }
 1033:     return;
 1034: }
 1035: 
 1036: sub inst_directory_query {
 1037:     my ($srch) = @_;
 1038:     my $udom = $srch->{'srchdomain'};
 1039:     my %results;
 1040:     my $homeserver = &domain($udom,'primary');
 1041:     my $outcome;
 1042:     if ($homeserver ne '') {
 1043: 	my $queryid=&reply("querysend:instdirsearch:".
 1044: 			   &escape($srch->{'srchby'}).':'.
 1045: 			   &escape($srch->{'srchterm'}).':'.
 1046: 			   &escape($srch->{'srchtype'}),$homeserver);
 1047: 	my $host=&hostname($homeserver);
 1048: 	if ($queryid !~/^\Q$host\E\_/) {
 1049: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1050: 	    return;
 1051: 	}
 1052: 	my $response = &get_query_reply($queryid);
 1053: 	my $maxtries = 5;
 1054: 	my $tries = 1;
 1055: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1056: 	    $response = &get_query_reply($queryid);
 1057: 	    $tries ++;
 1058: 	}
 1059: 
 1060:         if (!&error($response) && $response ne 'refused') {
 1061:             if ($response eq 'unavailable') {
 1062:                 $outcome = $response;
 1063:             } else {
 1064:                 $outcome = 'ok';
 1065:                 my @matches = split(/\n/,$response);
 1066:                 foreach my $match (@matches) {
 1067:                     my ($key,$value) = split(/=/,$match);
 1068:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1069:                 }
 1070:             }
 1071:         }
 1072:     }
 1073:     return ($outcome,%results);
 1074: }
 1075: 
 1076: sub usersearch {
 1077:     my ($srch) = @_;
 1078:     my $dom = $srch->{'srchdomain'};
 1079:     my %results;
 1080:     my %libserv = &all_library();
 1081:     my $query = 'usersearch';
 1082:     foreach my $tryserver (keys(%libserv)) {
 1083:         if (&host_domain($tryserver) eq $dom) {
 1084:             my $host=&hostname($tryserver);
 1085:             my $queryid=
 1086:                 &reply("querysend:".&escape($query).':'.
 1087:                        &escape($srch->{'srchby'}).':'.
 1088:                        &escape($srch->{'srchtype'}).':'.
 1089:                        &escape($srch->{'srchterm'}),$tryserver);
 1090:             if ($queryid !~/^\Q$host\E\_/) {
 1091:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1092:                 next;
 1093:             }
 1094:             my $reply = &get_query_reply($queryid);
 1095:             my $maxtries = 1;
 1096:             my $tries = 1;
 1097:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1098:                 $reply = &get_query_reply($queryid);
 1099:                 $tries ++;
 1100:             }
 1101:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1102:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1103:             } else {
 1104:                 my @matches;
 1105:                 if ($reply =~ /\n/) {
 1106:                     @matches = split(/\n/,$reply);
 1107:                 } else {
 1108:                     @matches = split(/\&/,$reply);
 1109:                 }
 1110:                 foreach my $match (@matches) {
 1111:                     my ($uname,$udom,%userhash);
 1112:                     foreach my $entry (split(/:/,$match)) {
 1113:                         my ($key,$value) =
 1114:                             map {&unescape($_);} split(/=/,$entry);
 1115:                         $userhash{$key} = $value;
 1116:                         if ($key eq 'username') {
 1117:                             $uname = $value;
 1118:                         } elsif ($key eq 'domain') {
 1119:                             $udom = $value;
 1120:                         }
 1121:                     }
 1122:                     $results{$uname.':'.$udom} = \%userhash;
 1123:                 }
 1124:             }
 1125:         }
 1126:     }
 1127:     return %results;
 1128: }
 1129: 
 1130: sub get_instuser {
 1131:     my ($udom,$uname,$id) = @_;
 1132:     my $homeserver = &domain($udom,'primary');
 1133:     my ($outcome,%results);
 1134:     if ($homeserver ne '') {
 1135:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1136:                            &escape($id).':'.&escape($udom),$homeserver);
 1137:         my $host=&hostname($homeserver);
 1138:         if ($queryid !~/^\Q$host\E\_/) {
 1139:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1140:             return;
 1141:         }
 1142:         my $response = &get_query_reply($queryid);
 1143:         my $maxtries = 5;
 1144:         my $tries = 1;
 1145:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1146:             $response = &get_query_reply($queryid);
 1147:             $tries ++;
 1148:         }
 1149:         if (!&error($response) && $response ne 'refused') {
 1150:             if ($response eq 'unavailable') {
 1151:                 $outcome = $response;
 1152:             } else {
 1153:                 $outcome = 'ok';
 1154:                 my @matches = split(/\n/,$response);
 1155:                 foreach my $match (@matches) {
 1156:                     my ($key,$value) = split(/=/,$match);
 1157:                     $results{&unescape($key)} = &thaw_unescape($value);
 1158:                 }
 1159:             }
 1160:         }
 1161:     }
 1162:     my %userinfo;
 1163:     if (ref($results{$uname}) eq 'HASH') {
 1164:         %userinfo = %{$results{$uname}};
 1165:     } 
 1166:     return ($outcome,%userinfo);
 1167: }
 1168: 
 1169: sub inst_rulecheck {
 1170:     my ($udom,$uname,$id,$item,$rules) = @_;
 1171:     my %returnhash;
 1172:     if ($udom ne '') {
 1173:         if (ref($rules) eq 'ARRAY') {
 1174:             @{$rules} = map {&escape($_);} (@{$rules});
 1175:             my $rulestr = join(':',@{$rules});
 1176:             my $homeserver=&domain($udom,'primary');
 1177:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1178:                 my $response;
 1179:                 if ($item eq 'username') {                
 1180:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1181:                                               ':'.&escape($uname).':'.$rulestr,
 1182:                                               $homeserver));
 1183:                 } elsif ($item eq 'id') {
 1184:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1185:                                               ':'.&escape($id).':'.$rulestr,
 1186:                                               $homeserver));
 1187:                 } elsif ($item eq 'selfcreate') {
 1188:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1189:                                                &escape($udom).':'.&escape($uname).
 1190:                                               ':'.$rulestr,$homeserver));
 1191:                 }
 1192:                 if ($response ne 'refused') {
 1193:                     my @pairs=split(/\&/,$response);
 1194:                     foreach my $item (@pairs) {
 1195:                         my ($key,$value)=split(/=/,$item,2);
 1196:                         $key = &unescape($key);
 1197:                         next if ($key =~ /^error: 2 /);
 1198:                         $returnhash{$key}=&thaw_unescape($value);
 1199:                     }
 1200:                 }
 1201:             }
 1202:         }
 1203:     }
 1204:     return %returnhash;
 1205: }
 1206: 
 1207: sub inst_userrules {
 1208:     my ($udom,$check) = @_;
 1209:     my (%ruleshash,@ruleorder);
 1210:     if ($udom ne '') {
 1211:         my $homeserver=&domain($udom,'primary');
 1212:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1213:             my $response;
 1214:             if ($check eq 'id') {
 1215:                 $response=&reply('instidrules:'.&escape($udom),
 1216:                                  $homeserver);
 1217:             } elsif ($check eq 'email') {
 1218:                 $response=&reply('instemailrules:'.&escape($udom),
 1219:                                  $homeserver);
 1220:             } else {
 1221:                 $response=&reply('instuserrules:'.&escape($udom),
 1222:                                  $homeserver);
 1223:             }
 1224:             if (($response ne 'refused') && ($response ne 'error') && 
 1225:                 ($response ne 'unknown_cmd') && 
 1226:                 ($response ne 'no_such_host')) {
 1227:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1228:                 my @pairs=split(/\&/,$hashitems);
 1229:                 foreach my $item (@pairs) {
 1230:                     my ($key,$value)=split(/=/,$item,2);
 1231:                     $key = &unescape($key);
 1232:                     next if ($key =~ /^error: 2 /);
 1233:                     $ruleshash{$key}=&thaw_unescape($value);
 1234:                 }
 1235:                 my @esc_order = split(/\&/,$orderitems);
 1236:                 foreach my $item (@esc_order) {
 1237:                     push(@ruleorder,&unescape($item));
 1238:                 }
 1239:             }
 1240:         }
 1241:     }
 1242:     return (\%ruleshash,\@ruleorder);
 1243: }
 1244: 
 1245: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1246: 
 1247: sub get_domain_defaults {
 1248:     my ($domain) = @_;
 1249:     my $cachetime = 60*60*24;
 1250:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1251:     if (defined($cached)) {
 1252:         if (ref($result) eq 'HASH') {
 1253:             return %{$result};
 1254:         }
 1255:     }
 1256:     my %domdefaults;
 1257:     my %domconfig =
 1258:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1259:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1260:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1261:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1262:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1263:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1264:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1265:     } else {
 1266:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1267:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1268:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1269:     }
 1270:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1271:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1272:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1273:         } else {
 1274:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1275:         } 
 1276:         my @usertools = ('aboutme','blog','portfolio');
 1277:         foreach my $item (@usertools) {
 1278:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1279:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1280:             }
 1281:         }
 1282:     }
 1283:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1284:         foreach my $item ('official','unofficial') {
 1285:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1286:         }
 1287:     }
 1288:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1289:                                   $cachetime);
 1290:     return %domdefaults;
 1291: }
 1292: 
 1293: # --------------------------------------------------- Assign a key to a student
 1294: 
 1295: sub assign_access_key {
 1296: #
 1297: # a valid key looks like uname:udom#comments
 1298: # comments are being appended
 1299: #
 1300:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1301:     $kdom=
 1302:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1303:     $knum=
 1304:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1305:     $cdom=
 1306:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1307:     $cnum=
 1308:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1309:     $udom=$env{'user.name'} unless (defined($udom));
 1310:     $uname=$env{'user.domain'} unless (defined($uname));
 1311:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1312:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1313:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1314:                                                   # assigned to this person
 1315:                                                   # - this should not happen,
 1316:                                                   # unless something went wrong
 1317:                                                   # the first time around
 1318: # ready to assign
 1319:         $logentry=$1.'; '.$logentry;
 1320:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1321:                                                  $kdom,$knum) eq 'ok') {
 1322: # key now belongs to user
 1323: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1324:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1325:                 &appenv({'environment.'.$envkey => $ckey});
 1326:                 return 'ok';
 1327:             } else {
 1328:                 return 
 1329:   'error: Count not permanently assign key, will need to be re-entered later.';
 1330: 	    }
 1331:         } else {
 1332:             return 'error: Could not assign key, try again later.';
 1333:         }
 1334:     } elsif (!$existing{$ckey}) {
 1335: # the key does not exist
 1336: 	return 'error: The key does not exist';
 1337:     } else {
 1338: # the key is somebody else's
 1339: 	return 'error: The key is already in use';
 1340:     }
 1341: }
 1342: 
 1343: # ------------------------------------------ put an additional comment on a key
 1344: 
 1345: sub comment_access_key {
 1346: #
 1347: # a valid key looks like uname:udom#comments
 1348: # comments are being appended
 1349: #
 1350:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1351:     $cdom=
 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1353:     $cnum=
 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1355:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1356:     if ($existing{$ckey}) {
 1357:         $existing{$ckey}.='; '.$logentry;
 1358: # ready to assign
 1359:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1360:                                                  $cdom,$cnum) eq 'ok') {
 1361: 	    return 'ok';
 1362:         } else {
 1363: 	    return 'error: Count not store comment.';
 1364:         }
 1365:     } else {
 1366: # the key does not exist
 1367: 	return 'error: The key does not exist';
 1368:     }
 1369: }
 1370: 
 1371: # ------------------------------------------------------ Generate a set of keys
 1372: 
 1373: sub generate_access_keys {
 1374:     my ($number,$cdom,$cnum,$logentry)=@_;
 1375:     $cdom=
 1376:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1377:     $cnum=
 1378:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1379:     unless (&allowed('mky',$cdom)) { return 0; }
 1380:     unless (($cdom) && ($cnum)) { return 0; }
 1381:     if ($number>10000) { return 0; }
 1382:     sleep(2); # make sure don't get same seed twice
 1383:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1384:     my $total=0;
 1385:     for (my $i=1;$i<=$number;$i++) {
 1386:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1387:                   sprintf("%lx",int(100000*rand)).'-'.
 1388:                   sprintf("%lx",int(100000*rand));
 1389:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1390:        $newkey=~s/0/h/g; # and also 0 and O
 1391:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1392:        if ($existing{$newkey}) {
 1393:            $i--;
 1394:        } else {
 1395: 	  if (&put('accesskeys',
 1396:               { $newkey => '# generated '.localtime().
 1397:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1398:                            '; '.$logentry },
 1399: 		   $cdom,$cnum) eq 'ok') {
 1400:               $total++;
 1401: 	  }
 1402:        }
 1403:     }
 1404:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1405:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1406:     return $total;
 1407: }
 1408: 
 1409: # ------------------------------------------------------- Validate an accesskey
 1410: 
 1411: sub validate_access_key {
 1412:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1413:     $cdom=
 1414:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1415:     $cnum=
 1416:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1417:     $udom=$env{'user.domain'} unless (defined($udom));
 1418:     $uname=$env{'user.name'} unless (defined($uname));
 1419:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1420:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1421: }
 1422: 
 1423: # ------------------------------------- Find the section of student in a course
 1424: sub devalidate_getsection_cache {
 1425:     my ($udom,$unam,$courseid)=@_;
 1426:     my $hashid="$udom:$unam:$courseid";
 1427:     &devalidate_cache_new('getsection',$hashid);
 1428: }
 1429: 
 1430: sub courseid_to_courseurl {
 1431:     my ($courseid) = @_;
 1432:     #already url style courseid
 1433:     return $courseid if ($courseid =~ m{^/});
 1434: 
 1435:     if (exists($env{'course.'.$courseid.'.num'})) {
 1436: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1437: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1438: 	return "/$cdom/$cnum";
 1439:     }
 1440: 
 1441:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1442:     if (exists($courseinfo{'num'})) {
 1443: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1444:     }
 1445: 
 1446:     return undef;
 1447: }
 1448: 
 1449: sub getsection {
 1450:     my ($udom,$unam,$courseid)=@_;
 1451:     my $cachetime=1800;
 1452: 
 1453:     my $hashid="$udom:$unam:$courseid";
 1454:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1455:     if (defined($cached)) { return $result; }
 1456: 
 1457:     my %Pending; 
 1458:     my %Expired;
 1459:     #
 1460:     # Each role can either have not started yet (pending), be active, 
 1461:     #    or have expired.
 1462:     #
 1463:     # If there is an active role, we are done.
 1464:     #
 1465:     # If there is more than one role which has not started yet, 
 1466:     #     choose the one which will start sooner
 1467:     # If there is one role which has not started yet, return it.
 1468:     #
 1469:     # If there is more than one expired role, choose the one which ended last.
 1470:     # If there is a role which has expired, return it.
 1471:     #
 1472:     $courseid = &courseid_to_courseurl($courseid);
 1473:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1474:     foreach my $key (keys(%roleshash)) {
 1475:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1476:         my $section=$1;
 1477:         if ($key eq $courseid.'_st') { $section=''; }
 1478:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1479:         my $now=time;
 1480:         if (defined($end) && $end && ($now > $end)) {
 1481:             $Expired{$end}=$section;
 1482:             next;
 1483:         }
 1484:         if (defined($start) && $start && ($now < $start)) {
 1485:             $Pending{$start}=$section;
 1486:             next;
 1487:         }
 1488:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1489:     }
 1490:     #
 1491:     # Presumedly there will be few matching roles from the above
 1492:     # loop and the sorting time will be negligible.
 1493:     if (scalar(keys(%Pending))) {
 1494:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1495:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1496:     } 
 1497:     if (scalar(keys(%Expired))) {
 1498:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1499:         my $time = pop(@sorted);
 1500:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1501:     }
 1502:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1503: }
 1504: 
 1505: sub save_cache {
 1506:     &purge_remembered();
 1507:     #&Apache::loncommon::validate_page();
 1508:     undef(%env);
 1509:     undef($env_loaded);
 1510: }
 1511: 
 1512: my $to_remember=-1;
 1513: my %remembered;
 1514: my %accessed;
 1515: my $kicks=0;
 1516: my $hits=0;
 1517: sub make_key {
 1518:     my ($name,$id) = @_;
 1519:     if (length($id) > 65 
 1520: 	&& length(&escape($id)) > 200) {
 1521: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1522:     }
 1523:     return &escape($name.':'.$id);
 1524: }
 1525: 
 1526: sub devalidate_cache_new {
 1527:     my ($name,$id,$debug) = @_;
 1528:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1529:     $id=&make_key($name,$id);
 1530:     $memcache->delete($id);
 1531:     delete($remembered{$id});
 1532:     delete($accessed{$id});
 1533: }
 1534: 
 1535: sub is_cached_new {
 1536:     my ($name,$id,$debug) = @_;
 1537:     $id=&make_key($name,$id);
 1538:     if (exists($remembered{$id})) {
 1539: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1540: 	$accessed{$id}=[&gettimeofday()];
 1541: 	$hits++;
 1542: 	return ($remembered{$id},1);
 1543:     }
 1544:     my $value = $memcache->get($id);
 1545:     if (!(defined($value))) {
 1546: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1547: 	return (undef,undef);
 1548:     }
 1549:     if ($value eq '__undef__') {
 1550: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1551: 	$value=undef;
 1552:     }
 1553:     &make_room($id,$value,$debug);
 1554:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1555:     return ($value,1);
 1556: }
 1557: 
 1558: sub do_cache_new {
 1559:     my ($name,$id,$value,$time,$debug) = @_;
 1560:     $id=&make_key($name,$id);
 1561:     my $setvalue=$value;
 1562:     if (!defined($setvalue)) {
 1563: 	$setvalue='__undef__';
 1564:     }
 1565:     if (!defined($time) ) {
 1566: 	$time=600;
 1567:     }
 1568:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1569:     my $result = $memcache->set($id,$setvalue,$time);
 1570:     if (! $result) {
 1571: 	&logthis("caching of id -> $id  failed");
 1572: 	$memcache->disconnect_all();
 1573:     }
 1574:     # need to make a copy of $value
 1575:     &make_room($id,$value,$debug);
 1576:     return $value;
 1577: }
 1578: 
 1579: sub make_room {
 1580:     my ($id,$value,$debug)=@_;
 1581: 
 1582:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1583:                                     : $value;
 1584:     if ($to_remember<0) { return; }
 1585:     $accessed{$id}=[&gettimeofday()];
 1586:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1587:     my $to_kick;
 1588:     my $max_time=0;
 1589:     foreach my $other (keys(%accessed)) {
 1590: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1591: 	    $to_kick=$other;
 1592: 	    $max_time=&tv_interval($accessed{$other});
 1593: 	}
 1594:     }
 1595:     delete($remembered{$to_kick});
 1596:     delete($accessed{$to_kick});
 1597:     $kicks++;
 1598:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1599:     return;
 1600: }
 1601: 
 1602: sub purge_remembered {
 1603:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1604:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1605:     undef(%remembered);
 1606:     undef(%accessed);
 1607: }
 1608: # ------------------------------------- Read an entry from a user's environment
 1609: 
 1610: sub userenvironment {
 1611:     my ($udom,$unam,@what)=@_;
 1612:     my $items;
 1613:     foreach my $item (@what) {
 1614:         $items.=&escape($item).'&';
 1615:     }
 1616:     $items=~s/\&$//;
 1617:     my %returnhash=();
 1618:     my @answer=split(/\&/,
 1619:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1620:                       &homeserver($unam,$udom)));
 1621:     my $i;
 1622:     for ($i=0;$i<=$#what;$i++) {
 1623: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1624:     }
 1625:     return %returnhash;
 1626: }
 1627: 
 1628: # ---------------------------------------------------------- Get a studentphoto
 1629: sub studentphoto {
 1630:     my ($udom,$unam,$ext) = @_;
 1631:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1632:     if (defined($env{'request.course.id'})) {
 1633:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1634:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1635:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1636:             } else {
 1637:                 my ($result,$perm_reqd)=
 1638: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1639:                 if ($result eq 'ok') {
 1640:                     if (!($perm_reqd eq 'yes')) {
 1641:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1642:                     }
 1643:                 }
 1644:             }
 1645:         }
 1646:     } else {
 1647:         my ($result,$perm_reqd) = 
 1648: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1649:         if ($result eq 'ok') {
 1650:             if (!($perm_reqd eq 'yes')) {
 1651:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1652:             }
 1653:         }
 1654:     }
 1655:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1656: }
 1657: 
 1658: sub retrievestudentphoto {
 1659:     my ($udom,$unam,$ext,$type) = @_;
 1660:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1661:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1662:     if ($ret eq 'ok') {
 1663:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1664:         if ($type eq 'thumbnail') {
 1665:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1666:         }
 1667:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1668:         return $tokenurl;
 1669:     } else {
 1670:         if ($type eq 'thumbnail') {
 1671:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1672:         } else { 
 1673:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1674:         }
 1675:     }
 1676: }
 1677: 
 1678: # -------------------------------------------------------------------- New chat
 1679: 
 1680: sub chatsend {
 1681:     my ($newentry,$anon,$group)=@_;
 1682:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1683:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1684:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1685:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1686: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1687: 		   &escape($newentry)).':'.$group,$chome);
 1688: }
 1689: 
 1690: # ------------------------------------------ Find current version of a resource
 1691: 
 1692: sub getversion {
 1693:     my $fname=&clutter(shift);
 1694:     unless ($fname=~/^\/res\//) { return -1; }
 1695:     return &currentversion(&filelocation('',$fname));
 1696: }
 1697: 
 1698: sub currentversion {
 1699:     my $fname=shift;
 1700:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1701:     if (defined($cached)) { return $result; }
 1702:     my $author=$fname;
 1703:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1704:     my ($udom,$uname)=split(/\//,$author);
 1705:     my $home=homeserver($uname,$udom);
 1706:     if ($home eq 'no_host') { 
 1707:         return -1; 
 1708:     }
 1709:     my $answer=reply("currentversion:$fname",$home);
 1710:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1711: 	return -1;
 1712:     }
 1713:     return &do_cache_new('resversion',$fname,$answer,600);
 1714: }
 1715: 
 1716: # ----------------------------- Subscribe to a resource, return URL if possible
 1717: 
 1718: sub subscribe {
 1719:     my $fname=shift;
 1720:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1721:     $fname=~s/[\n\r]//g;
 1722:     my $author=$fname;
 1723:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1724:     my ($udom,$uname)=split(/\//,$author);
 1725:     my $home=homeserver($uname,$udom);
 1726:     if ($home eq 'no_host') {
 1727:         return 'not_found';
 1728:     }
 1729:     my $answer=reply("sub:$fname",$home);
 1730:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1731: 	$answer.=' by '.$home;
 1732:     }
 1733:     return $answer;
 1734: }
 1735:     
 1736: # -------------------------------------------------------------- Replicate file
 1737: 
 1738: sub repcopy {
 1739:     my $filename=shift;
 1740:     $filename=~s/\/+/\//g;
 1741:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1742:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1743:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1744: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1745: 	return &repcopy_userfile($filename);
 1746:     }
 1747:     $filename=~s/[\n\r]//g;
 1748:     my $transname="$filename.in.transfer";
 1749: # FIXME: this should flock
 1750:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1751:     my $remoteurl=subscribe($filename);
 1752:     if ($remoteurl =~ /^con_lost by/) {
 1753: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1754:            return 'unavailable';
 1755:     } elsif ($remoteurl eq 'not_found') {
 1756: 	   #&logthis("Subscribe returned not_found: $filename");
 1757: 	   return 'not_found';
 1758:     } elsif ($remoteurl =~ /^rejected by/) {
 1759: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1760:            return 'forbidden';
 1761:     } elsif ($remoteurl eq 'directory') {
 1762:            return 'ok';
 1763:     } else {
 1764:         my $author=$filename;
 1765:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1766:         my ($udom,$uname)=split(/\//,$author);
 1767:         my $home=homeserver($uname,$udom);
 1768:         unless ($home eq $perlvar{'lonHostID'}) {
 1769:            my @parts=split(/\//,$filename);
 1770:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1771:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1772:                &logthis("Malconfiguration for replication: $filename");
 1773: 	       return 'bad_request';
 1774:            }
 1775:            my $count;
 1776:            for ($count=5;$count<$#parts;$count++) {
 1777:                $path.="/$parts[$count]";
 1778:                if ((-e $path)!=1) {
 1779: 		   mkdir($path,0777);
 1780:                }
 1781:            }
 1782:            my $ua=new LWP::UserAgent;
 1783:            my $request=new HTTP::Request('GET',"$remoteurl");
 1784:            my $response=$ua->request($request,$transname);
 1785:            if ($response->is_error()) {
 1786: 	       unlink($transname);
 1787:                my $message=$response->status_line;
 1788:                &logthis("<font color=\"blue\">WARNING:"
 1789:                        ." LWP get: $message: $filename</font>");
 1790:                return 'unavailable';
 1791:            } else {
 1792: 	       if ($remoteurl!~/\.meta$/) {
 1793:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1794:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1795:                   if ($mresponse->is_error()) {
 1796: 		      unlink($filename.'.meta');
 1797:                       &logthis(
 1798:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1799:                   }
 1800: 	       }
 1801:                rename($transname,$filename);
 1802:                return 'ok';
 1803:            }
 1804:        }
 1805:     }
 1806: }
 1807: 
 1808: # ------------------------------------------------ Get server side include body
 1809: sub ssi_body {
 1810:     my ($filelink,%form)=@_;
 1811:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1812:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1813:     }
 1814:     my $output='';
 1815:     my $response;
 1816:     if ($filelink=~/^https?\:/) {
 1817:        ($output,$response)=&externalssi($filelink);
 1818:     } else {
 1819:        ($output,$response)=&ssi($filelink,%form);
 1820:     }
 1821:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1822:     $output=~s/^.*?\<body[^\>]*\>//si;
 1823:     $output=~s/\<\/body\s*\>.*?$//si;
 1824:     if (wantarray) {
 1825:         return ($output, $response);
 1826:     } else {
 1827:         return $output;
 1828:     }
 1829: }
 1830: 
 1831: # --------------------------------------------------------- Server Side Include
 1832: 
 1833: sub absolute_url {
 1834:     my ($host_name) = @_;
 1835:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1836:     if ($host_name eq '') {
 1837: 	$host_name = $ENV{'SERVER_NAME'};
 1838:     }
 1839:     return $protocol.$host_name;
 1840: }
 1841: 
 1842: #
 1843: #   Server side include.
 1844: # Parameters:
 1845: #  fn     Possibly encrypted resource name/id.
 1846: #  form   Hash that describes how the rendering should be done
 1847: #         and other things.
 1848: # Returns:
 1849: #   Scalar context: The content of the response.
 1850: #   Array context:  2 element list of the content and the full response object.
 1851: #     
 1852: sub ssi {
 1853: 
 1854:     my ($fn,%form)=@_;
 1855:     my $ua=new LWP::UserAgent;
 1856:     my $request;
 1857: 
 1858:     $form{'no_update_last_known'}=1;
 1859:     &Apache::lonenc::check_encrypt(\$fn);
 1860:     if (%form) {
 1861:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1862:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1863:     } else {
 1864:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1865:     }
 1866: 
 1867:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1868:     my $response=$ua->request($request);
 1869: 
 1870:     if (wantarray) {
 1871: 	return ($response->content, $response);
 1872:     } else {
 1873: 	return $response->content;
 1874:     }
 1875: }
 1876: 
 1877: sub externalssi {
 1878:     my ($url)=@_;
 1879:     my $ua=new LWP::UserAgent;
 1880:     my $request=new HTTP::Request('GET',$url);
 1881:     my $response=$ua->request($request);
 1882:     if (wantarray) {
 1883:         return ($response->content, $response);
 1884:     } else {
 1885:         return $response->content;
 1886:     }
 1887: }
 1888: 
 1889: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1890: 
 1891: sub allowuploaded {
 1892:     my ($srcurl,$url)=@_;
 1893:     $url=&clutter(&declutter($url));
 1894:     my $dir=$url;
 1895:     $dir=~s/\/[^\/]+$//;
 1896:     my %httpref=();
 1897:     my $httpurl=&hreflocation('',$url);
 1898:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1899:     &Apache::lonnet::appenv(\%httpref);
 1900: }
 1901: 
 1902: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1903: # input: action, courseID, current domain, intended
 1904: #        path to file, source of file, instruction to parse file for objects,
 1905: #        ref to hash for embedded objects,
 1906: #        ref to hash for codebase of java objects.
 1907: #
 1908: # output: url to file (if action was uploaddoc), 
 1909: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1910: #
 1911: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1912: # course.
 1913: #
 1914: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1915: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1916: #          course's home server.
 1917: #
 1918: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1919: #          be copied from $source (current location) to 
 1920: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1921: #         and will then be copied to
 1922: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1923: #         course's home server.
 1924: #
 1925: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1926: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1927: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1928: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1929: #         in course's home server.
 1930: #
 1931: 
 1932: sub process_coursefile {
 1933:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1934:     my $fetchresult;
 1935:     my $home=&homeserver($docuname,$docudom);
 1936:     if ($action eq 'propagate') {
 1937:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1938: 			     $home);
 1939:     } else {
 1940:         my $fpath = '';
 1941:         my $fname = $file;
 1942:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1943:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1944:         my $filepath = &build_filepath($fpath);
 1945:         if ($action eq 'copy') {
 1946:             if ($source eq '') {
 1947:                 $fetchresult = 'no source file';
 1948:                 return $fetchresult;
 1949:             } else {
 1950:                 my $destination = $filepath.'/'.$fname;
 1951:                 rename($source,$destination);
 1952:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1953:                                  $home);
 1954:             }
 1955:         } elsif ($action eq 'uploaddoc') {
 1956:             open(my $fh,'>'.$filepath.'/'.$fname);
 1957:             print $fh $env{'form.'.$source};
 1958:             close($fh);
 1959:             if ($parser eq 'parse') {
 1960:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1961:                 unless ($parse_result eq 'ok') {
 1962:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1963:                 }
 1964:             }
 1965:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1966:                                  $home);
 1967:             if ($fetchresult eq 'ok') {
 1968:                 return '/uploaded/'.$fpath.'/'.$fname;
 1969:             } else {
 1970:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1971:                         ' to host '.$home.': '.$fetchresult);
 1972:                 return '/adm/notfound.html';
 1973:             }
 1974:         }
 1975:     }
 1976:     unless ( $fetchresult eq 'ok') {
 1977:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1978:              ' to host '.$home.': '.$fetchresult);
 1979:     }
 1980:     return $fetchresult;
 1981: }
 1982: 
 1983: sub build_filepath {
 1984:     my ($fpath) = @_;
 1985:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1986:     unless ($fpath eq '') {
 1987:         my @parts=split('/',$fpath);
 1988:         foreach my $part (@parts) {
 1989:             $filepath.= '/'.$part;
 1990:             if ((-e $filepath)!=1) {
 1991:                 mkdir($filepath,0777);
 1992:             }
 1993:         }
 1994:     }
 1995:     return $filepath;
 1996: }
 1997: 
 1998: sub store_edited_file {
 1999:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2000:     my $file = $primary_url;
 2001:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2002:     my $fpath = '';
 2003:     my $fname = $file;
 2004:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2005:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2006:     my $filepath = &build_filepath($fpath);
 2007:     open(my $fh,'>'.$filepath.'/'.$fname);
 2008:     print $fh $content;
 2009:     close($fh);
 2010:     my $home=&homeserver($docuname,$docudom);
 2011:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2012: 			  $home);
 2013:     if ($$fetchresult eq 'ok') {
 2014:         return '/uploaded/'.$fpath.'/'.$fname;
 2015:     } else {
 2016:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2017: 		 ' to host '.$home.': '.$$fetchresult);
 2018:         return '/adm/notfound.html';
 2019:     }
 2020: }
 2021: 
 2022: sub clean_filename {
 2023:     my ($fname,$args)=@_;
 2024: # Replace Windows backslashes by forward slashes
 2025:     $fname=~s/\\/\//g;
 2026:     if (!$args->{'keep_path'}) {
 2027:         # Get rid of everything but the actual filename
 2028: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2029:     }
 2030: # Replace spaces by underscores
 2031:     $fname=~s/\s+/\_/g;
 2032: # Replace all other weird characters by nothing
 2033:     $fname=~s{[^/\w\.\-]}{}g;
 2034: # Replace all .\d. sequences with _\d. so they no longer look like version
 2035: # numbers
 2036:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2037:     return $fname;
 2038: }
 2039: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2040: sub resizeImage {
 2041: 	my($img_url) = @_;	
 2042: 	my $ima = Image::Magick->new;                       
 2043:         $ima->Read($img_url);
 2044: 	if($ima->Get('width') > 400)
 2045: 	{
 2046: 		my $factor = $ima->Get('width')/400;
 2047:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2048: 	}
 2049: 	if($ima->Get('height') > 500)
 2050:         {
 2051:         	my $factor = $ima->Get('height')/500;
 2052:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2053:         } 
 2054: 		
 2055: 	$ima->Write($img_url);
 2056: }
 2057: 
 2058: #Wrapper function for userphotoupload
 2059: sub userphotoupload
 2060: {
 2061: 	my($formname,$subdir) = @_;
 2062: 	$upload_photo_form = 1;
 2063: 	return &userfileupload($formname,undef,$subdir);
 2064: }
 2065: 
 2066: # --------------- Take an uploaded file and put it into the userfiles directory
 2067: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2068: #                    the desired filenam is in $env{"form.$formname.filename"}
 2069: #        $coursedoc - if true up to the current course
 2070: #                     if false
 2071: #        $subdir - directory in userfile to store the file into
 2072: #        $parser - instruction to parse file for objects ($parser = parse)    
 2073: #        $allfiles - reference to hash for embedded objects
 2074: #        $codebase - reference to hash for codebase of java objects
 2075: #        $desuname - username for permanent storage of uploaded file
 2076: #        $dsetudom - domain for permanaent storage of uploaded file
 2077: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2078: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2079: # 
 2080: # output: url of file in userspace, or error: <message> 
 2081: #             or /adm/notfound.html if failure to upload occurse
 2082: 
 2083: 
 2084: sub userfileupload {
 2085:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2086:         $destudom,$thumbwidth,$thumbheight)=@_;
 2087:     if (!defined($subdir)) { $subdir='unknown'; }
 2088:     my $fname=$env{'form.'.$formname.'.filename'};
 2089:     $fname=&clean_filename($fname);
 2090: # See if there is anything left
 2091:     unless ($fname) { return 'error: no uploaded file'; }
 2092:     chop($env{'form.'.$formname});
 2093:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2094:         my $now = time;
 2095:         my $filepath = 'tmp/helprequests/'.$now;
 2096:         my @parts=split(/\//,$filepath);
 2097:         my $fullpath = $perlvar{'lonDaemons'};
 2098:         for (my $i=0;$i<@parts;$i++) {
 2099:             $fullpath .= '/'.$parts[$i];
 2100:             if ((-e $fullpath)!=1) {
 2101:                 mkdir($fullpath,0777);
 2102:             }
 2103:         }
 2104:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2105:         print $fh $env{'form.'.$formname};
 2106:         close($fh);
 2107:         return $fullpath.'/'.$fname;
 2108:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2109:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2110:                        '_'.$env{'user.domain'}.'/pending';
 2111:         my @parts=split(/\//,$filepath);
 2112:         my $fullpath = $perlvar{'lonDaemons'};
 2113:         for (my $i=0;$i<@parts;$i++) {
 2114:             $fullpath .= '/'.$parts[$i];
 2115:             if ((-e $fullpath)!=1) {
 2116:                 mkdir($fullpath,0777);
 2117:             }
 2118:         }
 2119:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2120:         print $fh $env{'form.'.$formname};
 2121:         close($fh);
 2122:         return $fullpath.'/'.$fname;
 2123:     }
 2124:     
 2125: # Create the directory if not present
 2126:     $fname="$subdir/$fname";
 2127:     if ($coursedoc) {
 2128: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2129: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2130:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2131:             return &finishuserfileupload($docuname,$docudom,
 2132: 					 $formname,$fname,$parser,$allfiles,
 2133: 					 $codebase,$thumbwidth,$thumbheight);
 2134:         } else {
 2135:             $fname=$env{'form.folder'}.'/'.$fname;
 2136:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2137: 				       $fname,$formname,$parser,
 2138: 				       $allfiles,$codebase);
 2139:         }
 2140:     } elsif (defined($destuname)) {
 2141:         my $docuname=$destuname;
 2142:         my $docudom=$destudom;
 2143: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2144: 				     $parser,$allfiles,$codebase,
 2145:                                      $thumbwidth,$thumbheight);
 2146:         
 2147:     } else {
 2148:         my $docuname=$env{'user.name'};
 2149:         my $docudom=$env{'user.domain'};
 2150:         if (exists($env{'form.group'})) {
 2151:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2152:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2153:         }
 2154: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2155: 				     $parser,$allfiles,$codebase,
 2156:                                      $thumbwidth,$thumbheight);
 2157:     }
 2158: }
 2159: 
 2160: sub finishuserfileupload {
 2161:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2162:         $thumbwidth,$thumbheight) = @_;
 2163:     my $path=$docudom.'/'.$docuname.'/';
 2164:     my $filepath=$perlvar{'lonDocRoot'};
 2165:   
 2166:     my ($fnamepath,$file,$fetchthumb);
 2167:     $file=$fname;
 2168:     if ($fname=~m|/|) {
 2169:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2170: 	$path.=$fnamepath.'/';
 2171:     }
 2172:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2173:     my $count;
 2174:     for ($count=4;$count<=$#parts;$count++) {
 2175:         $filepath.="/$parts[$count]";
 2176:         if ((-e $filepath)!=1) {
 2177: 	    mkdir($filepath,0777);
 2178:         }
 2179:     }
 2180: 
 2181: # Save the file
 2182:     {
 2183: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2184: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2185: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2186: 	    return '/adm/notfound.html';
 2187: 	}
 2188: 	if (!print FH ($env{'form.'.$formname})) {
 2189: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2190: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2191: 	    return '/adm/notfound.html';
 2192: 	}
 2193: 	close(FH);
 2194: 	if($upload_photo_form==1)
 2195: 	{
 2196: 		resizeImage($filepath.'/'.$file);		
 2197: 		$upload_photo_form = 0;
 2198: 	}
 2199:     }
 2200:     if ($parser eq 'parse') {
 2201:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2202: 						   $codebase);
 2203:         unless ($parse_result eq 'ok') {
 2204:             &logthis('Failed to parse '.$filepath.$file.
 2205: 		     ' for embedded media: '.$parse_result); 
 2206:         }
 2207:     }
 2208:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2209:         my $input = $filepath.'/'.$file;
 2210:         my $output = $filepath.'/'.'tn-'.$file;
 2211:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2212:         system("convert -sample $thumbsize $input $output");
 2213:         if (-e $filepath.'/'.'tn-'.$file) {
 2214:             $fetchthumb  = 1; 
 2215:         }
 2216:     }
 2217:  
 2218: # Notify homeserver to grep it
 2219: #
 2220:     my $docuhome=&homeserver($docuname,$docudom);	
 2221:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2222:     if ($fetchresult eq 'ok') {
 2223:         if ($fetchthumb) {
 2224:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2225:             if ($thumbresult ne 'ok') {
 2226:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2227:                          $docuhome.': '.$thumbresult);
 2228:             }
 2229:         }
 2230: #
 2231: # Return the URL to it
 2232:         return '/uploaded/'.$path.$file;
 2233:     } else {
 2234:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2235: 		 ': '.$fetchresult);
 2236:         return '/adm/notfound.html';
 2237:     }
 2238: }
 2239: 
 2240: sub extract_embedded_items {
 2241:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2242:     my @state = ();
 2243:     my %javafiles = (
 2244:                       codebase => '',
 2245:                       code => '',
 2246:                       archive => ''
 2247:                     );
 2248:     my %mediafiles = (
 2249:                       src => '',
 2250:                       movie => '',
 2251:                      );
 2252:     my $p;
 2253:     if ($content) {
 2254:         $p = HTML::LCParser->new($content);
 2255:     } else {
 2256:         $p = HTML::LCParser->new($fullpath);
 2257:     }
 2258:     while (my $t=$p->get_token()) {
 2259: 	if ($t->[0] eq 'S') {
 2260: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2261: 	    push(@state, $tagname);
 2262:             if (lc($tagname) eq 'allow') {
 2263:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2264:             }
 2265: 	    if (lc($tagname) eq 'img') {
 2266: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2267: 	    }
 2268: 	    if (lc($tagname) eq 'a') {
 2269: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2270: 	    }
 2271:             if (lc($tagname) eq 'script') {
 2272:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2273:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2274:                 } else {
 2275:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2276:                 }
 2277:             }
 2278:             if (lc($tagname) eq 'link') {
 2279:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2280:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2281:                 }
 2282:             }
 2283: 	    if (lc($tagname) eq 'object' ||
 2284: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2285: 		foreach my $item (keys(%javafiles)) {
 2286: 		    $javafiles{$item} = '';
 2287: 		}
 2288: 	    }
 2289: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2290: 		my $name = lc($attr->{'name'});
 2291: 		foreach my $item (keys(%javafiles)) {
 2292: 		    if ($name eq $item) {
 2293: 			$javafiles{$item} = $attr->{'value'};
 2294: 			last;
 2295: 		    }
 2296: 		}
 2297: 		foreach my $item (keys(%mediafiles)) {
 2298: 		    if ($name eq $item) {
 2299: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2300: 			last;
 2301: 		    }
 2302: 		}
 2303: 	    }
 2304: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2305: 		foreach my $item (keys(%javafiles)) {
 2306: 		    if ($attr->{$item}) {
 2307: 			$javafiles{$item} = $attr->{$item};
 2308: 			last;
 2309: 		    }
 2310: 		}
 2311: 		foreach my $item (keys(%mediafiles)) {
 2312: 		    if ($attr->{$item}) {
 2313: 			&add_filetype($allfiles,$attr->{$item},$item);
 2314: 			last;
 2315: 		    }
 2316: 		}
 2317: 	    }
 2318: 	} elsif ($t->[0] eq 'E') {
 2319: 	    my ($tagname) = ($t->[1]);
 2320: 	    if ($javafiles{'codebase'} ne '') {
 2321: 		$javafiles{'codebase'} .= '/';
 2322: 	    }  
 2323: 	    if (lc($tagname) eq 'applet' ||
 2324: 		lc($tagname) eq 'object' ||
 2325: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2326: 		) {
 2327: 		foreach my $item (keys(%javafiles)) {
 2328: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2329: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2330: 			&add_filetype($allfiles,$file,$item);
 2331: 		    }
 2332: 		}
 2333: 	    } 
 2334: 	    pop @state;
 2335: 	}
 2336:     }
 2337:     return 'ok';
 2338: }
 2339: 
 2340: sub add_filetype {
 2341:     my ($allfiles,$file,$type)=@_;
 2342:     if (exists($allfiles->{$file})) {
 2343: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2344: 	    push(@{$allfiles->{$file}}, &escape($type));
 2345: 	}
 2346:     } else {
 2347: 	@{$allfiles->{$file}} = (&escape($type));
 2348:     }
 2349: }
 2350: 
 2351: sub removeuploadedurl {
 2352:     my ($url)=@_;	
 2353:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2354:     return &removeuserfile($uname,$udom,$fname);
 2355: }
 2356: 
 2357: sub removeuserfile {
 2358:     my ($docuname,$docudom,$fname)=@_;
 2359:     my $home=&homeserver($docuname,$docudom);    
 2360:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2361:     if ($result eq 'ok') {	
 2362:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2363:             my $metafile = $fname.'.meta';
 2364:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2365: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2366:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2367:             my $sqlresult = 
 2368:                 &update_portfolio_table($docuname,$docudom,$file,
 2369:                                         'portfolio_metadata',$group,
 2370:                                         'delete');
 2371:         }
 2372:     }
 2373:     return $result;
 2374: }
 2375: 
 2376: sub mkdiruserfile {
 2377:     my ($docuname,$docudom,$dir)=@_;
 2378:     my $home=&homeserver($docuname,$docudom);
 2379:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2380: }
 2381: 
 2382: sub renameuserfile {
 2383:     my ($docuname,$docudom,$old,$new)=@_;
 2384:     my $home=&homeserver($docuname,$docudom);
 2385:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2386:                         &escape("$old").':'.&escape("$new"),$home);
 2387:     if ($result eq 'ok') {
 2388:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2389:             my $oldmeta = $old.'.meta';
 2390:             my $newmeta = $new.'.meta';
 2391:             my $metaresult = 
 2392:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2393: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2394:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2395:             my $sqlresult = 
 2396:                 &update_portfolio_table($docuname,$docudom,$file,
 2397:                                         'portfolio_metadata',$group,
 2398:                                         'delete');
 2399:         }
 2400:     }
 2401:     return $result;
 2402: }
 2403: 
 2404: # ------------------------------------------------------------------------- Log
 2405: 
 2406: sub log {
 2407:     my ($dom,$nam,$hom,$what)=@_;
 2408:     return critical("log:$dom:$nam:$what",$hom);
 2409: }
 2410: 
 2411: # ------------------------------------------------------------------ Course Log
 2412: #
 2413: # This routine flushes several buffers of non-mission-critical nature
 2414: #
 2415: 
 2416: sub flushcourselogs {
 2417:     &logthis('Flushing log buffers');
 2418: #
 2419: # course logs
 2420: # This is a log of all transactions in a course, which can be used
 2421: # for data mining purposes
 2422: #
 2423: # It also collects the courseid database, which lists last transaction
 2424: # times and course titles for all courseids
 2425: #
 2426:     my %courseidbuffer=();
 2427:     foreach my $crsid (keys(%courselogs)) {
 2428:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2429: 		          &escape($courselogs{$crsid}),
 2430: 		          $coursehombuf{$crsid}) eq 'ok') {
 2431: 	    delete $courselogs{$crsid};
 2432:         } else {
 2433:             &logthis('Failed to flush log buffer for '.$crsid);
 2434:             if (length($courselogs{$crsid})>40000) {
 2435:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2436:                         " exceeded maximum size, deleting.</font>");
 2437:                delete $courselogs{$crsid};
 2438:             }
 2439:         }
 2440:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2441:             'description' => $coursedescrbuf{$crsid},
 2442:             'inst_code'    => $courseinstcodebuf{$crsid},
 2443:             'type'        => $coursetypebuf{$crsid},
 2444:             'owner'       => $courseownerbuf{$crsid},
 2445:         };
 2446:     }
 2447: #
 2448: # Write course id database (reverse lookup) to homeserver of courses 
 2449: # Is used in pickcourse
 2450: #
 2451:     foreach my $crs_home (keys(%courseidbuffer)) {
 2452:         my $response = &courseidput(&host_domain($crs_home),
 2453:                                     $courseidbuffer{$crs_home},
 2454:                                     $crs_home,'timeonly');
 2455:     }
 2456: #
 2457: # File accesses
 2458: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2459: #
 2460:     foreach my $entry (keys(%accesshash)) {
 2461:         if ($entry =~ /___count$/) {
 2462:             my ($dom,$name);
 2463:             ($dom,$name,undef)=
 2464: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2465:             if (! defined($dom) || $dom eq '' || 
 2466:                 ! defined($name) || $name eq '') {
 2467:                 my $cid = $env{'request.course.id'};
 2468:                 $dom  = $env{'request.'.$cid.'.domain'};
 2469:                 $name = $env{'request.'.$cid.'.num'};
 2470:             }
 2471:             my $value = $accesshash{$entry};
 2472:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2473:             my %temphash=($url => $value);
 2474:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2475:             if ($result eq 'ok') {
 2476:                 delete $accesshash{$entry};
 2477:             } elsif ($result eq 'unknown_cmd') {
 2478:                 # Target server has old code running on it.
 2479:                 my %temphash=($entry => $value);
 2480:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2481:                     delete $accesshash{$entry};
 2482:                 }
 2483:             }
 2484:         } else {
 2485:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2486:             my %temphash=($entry => $accesshash{$entry});
 2487:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2488:                 delete $accesshash{$entry};
 2489:             }
 2490:         }
 2491:     }
 2492: #
 2493: # Roles
 2494: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2495: #
 2496:     foreach my $entry (keys(%userrolehash)) {
 2497:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2498: 	    split(/\:/,$entry);
 2499:         if (&Apache::lonnet::put('nohist_userroles',
 2500:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2501:                 $rudom,$runame) eq 'ok') {
 2502: 	    delete $userrolehash{$entry};
 2503:         }
 2504:     }
 2505: #
 2506: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2507: #
 2508:     my %domrolebuffer = ();
 2509:     foreach my $entry (keys %domainrolehash) {
 2510:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2511:         if ($domrolebuffer{$rudom}) {
 2512:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2513:                       '='.&escape($domainrolehash{$entry});
 2514:         } else {
 2515:             $domrolebuffer{$rudom}.=&escape($entry).
 2516:                       '='.&escape($domainrolehash{$entry});
 2517:         }
 2518:         delete $domainrolehash{$entry};
 2519:     }
 2520:     foreach my $dom (keys(%domrolebuffer)) {
 2521: 	my %servers = &get_servers($dom,'library');
 2522: 	foreach my $tryserver (keys(%servers)) {
 2523: 	    unless (&reply('domroleput:'.$dom.':'.
 2524: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2525: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2526: 	    }
 2527:         }
 2528:     }
 2529:     $dumpcount++;
 2530: }
 2531: 
 2532: sub courselog {
 2533:     my $what=shift;
 2534:     $what=time.':'.$what;
 2535:     unless ($env{'request.course.id'}) { return ''; }
 2536:     $coursedombuf{$env{'request.course.id'}}=
 2537:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2538:     $coursenumbuf{$env{'request.course.id'}}=
 2539:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2540:     $coursehombuf{$env{'request.course.id'}}=
 2541:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2542:     $coursedescrbuf{$env{'request.course.id'}}=
 2543:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2544:     $courseinstcodebuf{$env{'request.course.id'}}=
 2545:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2546:     $courseownerbuf{$env{'request.course.id'}}=
 2547:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2548:     $coursetypebuf{$env{'request.course.id'}}=
 2549:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2550:     if (defined $courselogs{$env{'request.course.id'}}) {
 2551: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2552:     } else {
 2553: 	$courselogs{$env{'request.course.id'}}.=$what;
 2554:     }
 2555:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2556: 	&flushcourselogs();
 2557:     }
 2558: }
 2559: 
 2560: sub courseacclog {
 2561:     my $fnsymb=shift;
 2562:     unless ($env{'request.course.id'}) { return ''; }
 2563:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2564:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2565:         $what.=':POST';
 2566:         # FIXME: Probably ought to escape things....
 2567: 	foreach my $key (keys(%env)) {
 2568:             if ($key=~/^form\.(.*)/) {
 2569:                 my $formitem = $1;
 2570:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2571:                     $what.=':'.$formitem.'='.$env{$key};
 2572:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2573:                     $what.=':'.$formitem.'='.$env{$key};
 2574:                 }
 2575:             }
 2576:         }
 2577:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2578:         # FIXME: We should not be depending on a form parameter that someone
 2579:         # editing lonsearchcat.pm might change in the future.
 2580:         if ($env{'form.phase'} eq 'course_search') {
 2581:             $what.= ':POST';
 2582:             # FIXME: Probably ought to escape things....
 2583:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2584:                                  'crsdiscuss') {
 2585:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2586:             }
 2587:         }
 2588:     }
 2589:     &courselog($what);
 2590: }
 2591: 
 2592: sub countacc {
 2593:     my $url=&declutter(shift);
 2594:     return if (! defined($url) || $url eq '');
 2595:     unless ($env{'request.course.id'}) { return ''; }
 2596:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2597:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2598:     $accesshash{$key}++;
 2599: }
 2600: 
 2601: sub linklog {
 2602:     my ($from,$to)=@_;
 2603:     $from=&declutter($from);
 2604:     $to=&declutter($to);
 2605:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2606:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2607: }
 2608:   
 2609: sub userrolelog {
 2610:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2611:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2612:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2613:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2614:         ($trole=~/^ta/)) {
 2615:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2616:        $userrolehash
 2617:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2618:                     =$tend.':'.$tstart;
 2619:     }
 2620:     if (($env{'request.role'} =~ /dc\./) &&
 2621: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2622: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2623: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2624:        $userrolehash
 2625:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2626:                     =$tend.':'.$tstart;
 2627:     }
 2628:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2629:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2630:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2631:         ($trole=~/^sc/)) {
 2632:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2633:        $domainrolehash
 2634:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2635:                     = $tend.':'.$tstart;
 2636:     }
 2637: }
 2638: 
 2639: sub courserolelog {
 2640:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2641:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2642:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2643:         ($trole eq 'ta') || ($trole eq 'st') ||
 2644:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2645:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2646:             my $cdom = $1;
 2647:             my $cnum = $2;
 2648:             my $sec = $3;
 2649:             my $namespace = 'rolelog';
 2650:             my %storehash = (
 2651:                                role    => $trole,
 2652:                                start   => $tstart,
 2653:                                end     => $tend,
 2654:                                selfenroll => $selfenroll,
 2655:                                context    => $context,
 2656:                             );
 2657:             if ($trole eq 'gr') {
 2658:                 $namespace = 'groupslog';
 2659:                 $storehash{'group'} = $sec;
 2660:             } else {
 2661:                 $storehash{'section'} = $sec;
 2662:             }
 2663:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2664:         }
 2665:     }
 2666:     return;
 2667: }
 2668: 
 2669: sub get_course_adv_roles {
 2670:     my ($cid,$codes) = @_;
 2671:     $cid=$env{'request.course.id'} unless (defined($cid));
 2672:     my %coursehash=&coursedescription($cid);
 2673:     my %nothide=();
 2674:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2675:         if ($user !~ /:/) {
 2676: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2677:         } else {
 2678:             $nothide{$user}=1;
 2679:         }
 2680:     }
 2681:     my %returnhash=();
 2682:     my %dumphash=
 2683:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2684:     my $now=time;
 2685:     foreach my $entry (keys %dumphash) {
 2686: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2687:         if (($tstart) && ($tstart<0)) { next; }
 2688:         if (($tend) && ($tend<$now)) { next; }
 2689:         if (($tstart) && ($now<$tstart)) { next; }
 2690:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2691: 	if ($username eq '' || $domain eq '') { next; }
 2692: 	if ((&privileged($username,$domain)) && 
 2693: 	    (!$nothide{$username.':'.$domain})) { next; }
 2694: 	if ($role eq 'cr') { next; }
 2695:         if ($codes) {
 2696:             if ($section) { $role .= ':'.$section; }
 2697:             if ($returnhash{$role}) {
 2698:                 $returnhash{$role}.=','.$username.':'.$domain;
 2699:             } else {
 2700:                 $returnhash{$role}=$username.':'.$domain;
 2701:             }
 2702:         } else {
 2703:             my $key=&plaintext($role);
 2704:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2705:             if ($returnhash{$key}) {
 2706: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2707:             } else {
 2708:                 $returnhash{$key}=$username.':'.$domain;
 2709:             }
 2710:         }
 2711:     }
 2712:     return %returnhash;
 2713: }
 2714: 
 2715: sub get_my_roles {
 2716:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2717:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2718:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2719:     my (%dumphash,%nothide);
 2720:     if ($context eq 'userroles') { 
 2721:         %dumphash = &dump('roles',$udom,$uname);
 2722:     } else {
 2723:         %dumphash=
 2724:             &dump('nohist_userroles',$udom,$uname);
 2725:         if ($hidepriv) {
 2726:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2727:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2728:                 if ($user !~ /:/) {
 2729:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2730:                 } else {
 2731:                     $nothide{$user} = 1;
 2732:                 }
 2733:             }
 2734:         }
 2735:     }
 2736:     my %returnhash=();
 2737:     my $now=time;
 2738:     foreach my $entry (keys(%dumphash)) {
 2739:         my ($role,$tend,$tstart);
 2740:         if ($context eq 'userroles') {
 2741: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2742:         } else {
 2743:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2744:         }
 2745:         if (($tstart) && ($tstart<0)) { next; }
 2746:         my $status = 'active';
 2747:         if (($tend) && ($tend<=$now)) {
 2748:             $status = 'previous';
 2749:         } 
 2750:         if (($tstart) && ($now<$tstart)) {
 2751:             $status = 'future';
 2752:         }
 2753:         if (ref($types) eq 'ARRAY') {
 2754:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2755:                 next;
 2756:             } 
 2757:         } else {
 2758:             if ($status ne 'active') {
 2759:                 next;
 2760:             }
 2761:         }
 2762:         my ($rolecode,$username,$domain,$section,$area);
 2763:         if ($context eq 'userroles') {
 2764:             ($area,$rolecode) = split(/_/,$entry);
 2765:             (undef,$domain,$username,$section) = split(/\//,$area);
 2766:         } else {
 2767:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2768:         }
 2769:         if (ref($roledoms) eq 'ARRAY') {
 2770:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2771:                 next;
 2772:             }
 2773:         }
 2774:         if (ref($roles) eq 'ARRAY') {
 2775:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2776:                 if ($role =~ /^cr\//) {
 2777:                     if (!grep(/^cr$/,@{$roles})) {
 2778:                         next;
 2779:                     }
 2780:                 } else {
 2781:                     next;
 2782:                 }
 2783:             }
 2784:         }
 2785:         if ($hidepriv) {
 2786:             if ((&privileged($username,$domain)) &&
 2787:                 (!$nothide{$username.':'.$domain})) { 
 2788:                 next;
 2789:             }
 2790:         }
 2791:         if ($withsec) {
 2792:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2793:                 $tstart.':'.$tend;
 2794:         } else {
 2795:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2796:         }
 2797:     }
 2798:     return %returnhash;
 2799: }
 2800: 
 2801: # ----------------------------------------------------- Frontpage Announcements
 2802: #
 2803: #
 2804: 
 2805: sub postannounce {
 2806:     my ($server,$text)=@_;
 2807:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2808:     unless ($text=~/\w/) { $text=''; }
 2809:     return &reply('setannounce:'.&escape($text),$server);
 2810: }
 2811: 
 2812: sub getannounce {
 2813: 
 2814:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2815: 	my $announcement='';
 2816: 	while (my $line = <$fh>) { $announcement .= $line; }
 2817: 	close($fh);
 2818: 	if ($announcement=~/\w/) { 
 2819: 	    return 
 2820:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2821:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2822: 	} else {
 2823: 	    return '';
 2824: 	}
 2825:     } else {
 2826: 	return '';
 2827:     }
 2828: }
 2829: 
 2830: # ---------------------------------------------------------- Course ID routines
 2831: # Deal with domain's nohist_courseid.db files
 2832: #
 2833: 
 2834: sub courseidput {
 2835:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2836:     my $outcome;
 2837:     if ($caller eq 'timeonly') {
 2838:         my $cids = '';
 2839:         foreach my $item (keys(%$storehash)) {
 2840:             $cids.=&escape($item).'&';
 2841:         }
 2842:         $cids=~s/\&$//;
 2843:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2844:                           $coursehome);       
 2845:     } else {
 2846:         my $items = '';
 2847:         foreach my $item (keys(%$storehash)) {
 2848:             $items.= &escape($item).'='.
 2849:                      &freeze_escape($$storehash{$item}).'&';
 2850:         }
 2851:         $items=~s/\&$//;
 2852:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2853:                           $coursehome);
 2854:     }
 2855:     if ($outcome eq 'unknown_cmd') {
 2856:         my $what;
 2857:         foreach my $cid (keys(%$storehash)) {
 2858:             $what .= &escape($cid).'=';
 2859:             foreach my $item ('description','inst_code','owner','type') {
 2860:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2861:             }
 2862:             $what =~ s/\:$/&/;
 2863:         }
 2864:         $what =~ s/\&$//;  
 2865:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2866:     } else {
 2867:         return $outcome;
 2868:     }
 2869: }
 2870: 
 2871: sub courseiddump {
 2872:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2873:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2874:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2875:     my $as_hash = 1;
 2876:     my %returnhash;
 2877:     if (!$domfilter) { $domfilter=''; }
 2878:     my %libserv = &all_library();
 2879:     foreach my $tryserver (keys(%libserv)) {
 2880:         if ( (  $hostidflag == 1 
 2881: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2882: 	     || (!defined($hostidflag)) ) {
 2883: 
 2884: 	    if (($domfilter eq '') ||
 2885: 		(&host_domain($tryserver) eq $domfilter)) {
 2886:                 my $rep = 
 2887:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2888:                          $sincefilter.':'.&escape($descfilter).':'.
 2889:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2890:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2891:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2892:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2893:                          $showhidden.':'.$caller,$tryserver);
 2894:                 my @pairs=split(/\&/,$rep);
 2895:                 foreach my $item (@pairs) {
 2896:                     my ($key,$value)=split(/\=/,$item,2);
 2897:                     $key = &unescape($key);
 2898:                     next if ($key =~ /^error: 2 /);
 2899:                     my $result = &thaw_unescape($value);
 2900:                     if (ref($result) eq 'HASH') {
 2901:                         $returnhash{$key}=$result;
 2902:                     } else {
 2903:                         my @responses = split(/:/,$value);
 2904:                         my @items = ('description','inst_code','owner','type');
 2905:                         for (my $i=0; $i<@responses; $i++) {
 2906:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2907:                         }
 2908:                     } 
 2909:                 }
 2910:             }
 2911:         }
 2912:     }
 2913:     return %returnhash;
 2914: }
 2915: 
 2916: # ---------------------------------------------------------- DC e-mail
 2917: 
 2918: sub dcmailput {
 2919:     my ($domain,$msgid,$message,$server)=@_;
 2920:     my $status = &Apache::lonnet::critical(
 2921:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2922:        &escape($message),$server);
 2923:     return $status;
 2924: }
 2925: 
 2926: sub dcmaildump {
 2927:     my ($dom,$startdate,$enddate,$senders) = @_;
 2928:     my %returnhash=();
 2929: 
 2930:     if (defined(&domain($dom,'primary'))) {
 2931:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2932:                                                          &escape($enddate).':';
 2933: 	my @esc_senders=map { &escape($_)} @$senders;
 2934: 	$cmd.=&escape(join('&',@esc_senders));
 2935: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2936:             my ($key,$value) = split(/\=/,$line,2);
 2937:             if (($key) && ($value)) {
 2938:                 $returnhash{&unescape($key)} = &unescape($value);
 2939:             }
 2940:         }
 2941:     }
 2942:     return %returnhash;
 2943: }
 2944: # ---------------------------------------------------------- Domain roles
 2945: 
 2946: sub get_domain_roles {
 2947:     my ($dom,$roles,$startdate,$enddate)=@_;
 2948:     if (undef($startdate) || $startdate eq '') {
 2949:         $startdate = '.';
 2950:     }
 2951:     if (undef($enddate) || $enddate eq '') {
 2952:         $enddate = '.';
 2953:     }
 2954:     my $rolelist;
 2955:     if (ref($roles) eq 'ARRAY') {
 2956:         $rolelist = join(':',@{$roles});
 2957:     }
 2958:     my %personnel = ();
 2959: 
 2960:     my %servers = &get_servers($dom,'library');
 2961:     foreach my $tryserver (keys(%servers)) {
 2962: 	%{$personnel{$tryserver}}=();
 2963: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2964: 					    &escape($startdate).':'.
 2965: 					    &escape($enddate).':'.
 2966: 					    &escape($rolelist), $tryserver))) {
 2967: 	    my ($key,$value) = split(/\=/,$line,2);
 2968: 	    if (($key) && ($value)) {
 2969: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2970: 	    }
 2971: 	}
 2972:     }
 2973:     return %personnel;
 2974: }
 2975: 
 2976: # ----------------------------------------------------------- Check out an item
 2977: 
 2978: sub get_first_access {
 2979:     my ($type,$argsymb)=@_;
 2980:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2981:     if ($argsymb) { $symb=$argsymb; }
 2982:     my ($map,$id,$res)=&decode_symb($symb);
 2983:     if ($type eq 'course') {
 2984: 	$res='course';
 2985:     } elsif ($type eq 'map') {
 2986: 	$res=&symbread($map);
 2987:     } else {
 2988: 	$res=$symb;
 2989:     }
 2990:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2991:     return $times{"$courseid\0$res"};
 2992: }
 2993: 
 2994: sub set_first_access {
 2995:     my ($type)=@_;
 2996:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2997:     my ($map,$id,$res)=&decode_symb($symb);
 2998:     if ($type eq 'course') {
 2999: 	$res='course';
 3000:     } elsif ($type eq 'map') {
 3001: 	$res=&symbread($map);
 3002:     } else {
 3003: 	$res=$symb;
 3004:     }
 3005:     my $firstaccess=&get_first_access($type,$symb);
 3006:     if (!$firstaccess) {
 3007: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3008:     }
 3009:     return 'already_set';
 3010: }
 3011: 
 3012: sub checkout {
 3013:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3014:     my $now=time;
 3015:     my $lonhost=$perlvar{'lonHostID'};
 3016:     my $infostr=&escape(
 3017:                  'CHECKOUTTOKEN&'.
 3018:                  $tuname.'&'.
 3019:                  $tudom.'&'.
 3020:                  $tcrsid.'&'.
 3021:                  $symb.'&'.
 3022: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3023:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3024:     if ($token=~/^error\:/) { 
 3025:         &logthis("<font color=\"blue\">WARNING: ".
 3026:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3027:                  "</font>");
 3028:         return ''; 
 3029:     }
 3030: 
 3031:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3032:     $token=~tr/a-z/A-Z/;
 3033: 
 3034:     my %infohash=('resource.0.outtoken' => $token,
 3035:                   'resource.0.checkouttime' => $now,
 3036:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3037: 
 3038:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3039:        return '';
 3040:     } else {
 3041:         &logthis("<font color=\"blue\">WARNING: ".
 3042:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3043:                  "</font>");
 3044:     }    
 3045: 
 3046:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3047:                          &escape('Checkout '.$infostr.' - '.
 3048:                                                  $token)) ne 'ok') {
 3049: 	return '';
 3050:     } else {
 3051:         &logthis("<font color=\"blue\">WARNING: ".
 3052:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3053:                  "</font>");
 3054:     }
 3055:     return $token;
 3056: }
 3057: 
 3058: # ------------------------------------------------------------ Check in an item
 3059: 
 3060: sub checkin {
 3061:     my $token=shift;
 3062:     my $now=time;
 3063:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3064:     $lonhost=~tr/A-Z/a-z/;
 3065:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3066:     $dtoken=~s/\W/\_/g;
 3067:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3068:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3069: 
 3070:     unless (($tuname) && ($tudom)) {
 3071:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3072:         return '';
 3073:     }
 3074:     
 3075:     unless (&allowed('mgr',$tcrsid)) {
 3076:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3077:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3078:         return '';
 3079:     }
 3080: 
 3081:     my %infohash=('resource.0.intoken' => $token,
 3082:                   'resource.0.checkintime' => $now,
 3083:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3084: 
 3085:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3086:        return '';
 3087:     }    
 3088: 
 3089:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3090:                          &escape('Checkin - '.$token)) ne 'ok') {
 3091: 	return '';
 3092:     }
 3093: 
 3094:     return ($symb,$tuname,$tudom,$tcrsid);    
 3095: }
 3096: 
 3097: # --------------------------------------------- Set Expire Date for Spreadsheet
 3098: 
 3099: sub expirespread {
 3100:     my ($uname,$udom,$stype,$usymb)=@_;
 3101:     my $cid=$env{'request.course.id'}; 
 3102:     if ($cid) {
 3103:        my $now=time;
 3104:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3105:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3106:                             $env{'course.'.$cid.'.num'}.
 3107: 	        	    ':nohist_expirationdates:'.
 3108:                             &escape($key).'='.$now,
 3109:                             $env{'course.'.$cid.'.home'})
 3110:     }
 3111:     return 'ok';
 3112: }
 3113: 
 3114: # ----------------------------------------------------- Devalidate Spreadsheets
 3115: 
 3116: sub devalidate {
 3117:     my ($symb,$uname,$udom)=@_;
 3118:     my $cid=$env{'request.course.id'}; 
 3119:     if ($cid) {
 3120:         # delete the stored spreadsheets for
 3121:         # - the student level sheet of this user in course's homespace
 3122:         # - the assessment level sheet for this resource 
 3123:         #   for this user in user's homespace
 3124: 	# - current conditional state info
 3125: 	my $key=$uname.':'.$udom.':';
 3126:         my $status=
 3127: 	    &del('nohist_calculatedsheets',
 3128: 		 [$key.'studentcalc:'],
 3129: 		 $env{'course.'.$cid.'.domain'},
 3130: 		 $env{'course.'.$cid.'.num'})
 3131: 		.' '.
 3132: 	    &del('nohist_calculatedsheets_'.$cid,
 3133: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3134:         unless ($status eq 'ok ok') {
 3135:            &logthis('Could not devalidate spreadsheet '.
 3136:                     $uname.' at '.$udom.' for '.
 3137: 		    $symb.': '.$status);
 3138:         }
 3139: 	&delenv('user.state.'.$cid);
 3140:     }
 3141: }
 3142: 
 3143: sub get_scalar {
 3144:     my ($string,$end) = @_;
 3145:     my $value;
 3146:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3147: 	$value = $1;
 3148:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3149: 	$value = $1;
 3150:     }
 3151:     return &unescape($value);
 3152: }
 3153: 
 3154: sub array2str {
 3155:   my (@array) = @_;
 3156:   my $result=&arrayref2str(\@array);
 3157:   $result=~s/^__ARRAY_REF__//;
 3158:   $result=~s/__END_ARRAY_REF__$//;
 3159:   return $result;
 3160: }
 3161: 
 3162: sub arrayref2str {
 3163:   my ($arrayref) = @_;
 3164:   my $result='__ARRAY_REF__';
 3165:   foreach my $elem (@$arrayref) {
 3166:     if(ref($elem) eq 'ARRAY') {
 3167:       $result.=&arrayref2str($elem).'&';
 3168:     } elsif(ref($elem) eq 'HASH') {
 3169:       $result.=&hashref2str($elem).'&';
 3170:     } elsif(ref($elem)) {
 3171:       #print("Got a ref of ".(ref($elem))." skipping.");
 3172:     } else {
 3173:       $result.=&escape($elem).'&';
 3174:     }
 3175:   }
 3176:   $result=~s/\&$//;
 3177:   $result .= '__END_ARRAY_REF__';
 3178:   return $result;
 3179: }
 3180: 
 3181: sub hash2str {
 3182:   my (%hash) = @_;
 3183:   my $result=&hashref2str(\%hash);
 3184:   $result=~s/^__HASH_REF__//;
 3185:   $result=~s/__END_HASH_REF__$//;
 3186:   return $result;
 3187: }
 3188: 
 3189: sub hashref2str {
 3190:   my ($hashref)=@_;
 3191:   my $result='__HASH_REF__';
 3192:   foreach my $key (sort(keys(%$hashref))) {
 3193:     if (ref($key) eq 'ARRAY') {
 3194:       $result.=&arrayref2str($key).'=';
 3195:     } elsif (ref($key) eq 'HASH') {
 3196:       $result.=&hashref2str($key).'=';
 3197:     } elsif (ref($key)) {
 3198:       $result.='=';
 3199:       #print("Got a ref of ".(ref($key))." skipping.");
 3200:     } else {
 3201: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3202:     }
 3203: 
 3204:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3205:       $result.=&arrayref2str($hashref->{$key}).'&';
 3206:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3207:       $result.=&hashref2str($hashref->{$key}).'&';
 3208:     } elsif(ref($hashref->{$key})) {
 3209:        $result.='&';
 3210:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3211:     } else {
 3212:       $result.=&escape($hashref->{$key}).'&';
 3213:     }
 3214:   }
 3215:   $result=~s/\&$//;
 3216:   $result .= '__END_HASH_REF__';
 3217:   return $result;
 3218: }
 3219: 
 3220: sub str2hash {
 3221:     my ($string)=@_;
 3222:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3223:     return %$hash;
 3224: }
 3225: 
 3226: sub str2hashref {
 3227:   my ($string) = @_;
 3228: 
 3229:   my %hash;
 3230: 
 3231:   if($string !~ /^__HASH_REF__/) {
 3232:       if (! ($string eq '' || !defined($string))) {
 3233: 	  $hash{'error'}='Not hash reference';
 3234:       }
 3235:       return (\%hash, $string);
 3236:   }
 3237: 
 3238:   $string =~ s/^__HASH_REF__//;
 3239: 
 3240:   while($string !~ /^__END_HASH_REF__/) {
 3241:       #key
 3242:       my $key='';
 3243:       if($string =~ /^__HASH_REF__/) {
 3244:           ($key, $string)=&str2hashref($string);
 3245:           if(defined($key->{'error'})) {
 3246:               $hash{'error'}='Bad data';
 3247:               return (\%hash, $string);
 3248:           }
 3249:       } elsif($string =~ /^__ARRAY_REF__/) {
 3250:           ($key, $string)=&str2arrayref($string);
 3251:           if($key->[0] eq 'Array reference error') {
 3252:               $hash{'error'}='Bad data';
 3253:               return (\%hash, $string);
 3254:           }
 3255:       } else {
 3256:           $string =~ s/^(.*?)=//;
 3257: 	  $key=&unescape($1);
 3258:       }
 3259:       $string =~ s/^=//;
 3260: 
 3261:       #value
 3262:       my $value='';
 3263:       if($string =~ /^__HASH_REF__/) {
 3264:           ($value, $string)=&str2hashref($string);
 3265:           if(defined($value->{'error'})) {
 3266:               $hash{'error'}='Bad data';
 3267:               return (\%hash, $string);
 3268:           }
 3269:       } elsif($string =~ /^__ARRAY_REF__/) {
 3270:           ($value, $string)=&str2arrayref($string);
 3271:           if($value->[0] eq 'Array reference error') {
 3272:               $hash{'error'}='Bad data';
 3273:               return (\%hash, $string);
 3274:           }
 3275:       } else {
 3276: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3277:       }
 3278:       $string =~ s/^&//;
 3279: 
 3280:       $hash{$key}=$value;
 3281:   }
 3282: 
 3283:   $string =~ s/^__END_HASH_REF__//;
 3284: 
 3285:   return (\%hash, $string);
 3286: }
 3287: 
 3288: sub str2array {
 3289:     my ($string)=@_;
 3290:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3291:     return @$array;
 3292: }
 3293: 
 3294: sub str2arrayref {
 3295:   my ($string) = @_;
 3296:   my @array;
 3297: 
 3298:   if($string !~ /^__ARRAY_REF__/) {
 3299:       if (! ($string eq '' || !defined($string))) {
 3300: 	  $array[0]='Array reference error';
 3301:       }
 3302:       return (\@array, $string);
 3303:   }
 3304: 
 3305:   $string =~ s/^__ARRAY_REF__//;
 3306: 
 3307:   while($string !~ /^__END_ARRAY_REF__/) {
 3308:       my $value='';
 3309:       if($string =~ /^__HASH_REF__/) {
 3310:           ($value, $string)=&str2hashref($string);
 3311:           if(defined($value->{'error'})) {
 3312:               $array[0] ='Array reference error';
 3313:               return (\@array, $string);
 3314:           }
 3315:       } elsif($string =~ /^__ARRAY_REF__/) {
 3316:           ($value, $string)=&str2arrayref($string);
 3317:           if($value->[0] eq 'Array reference error') {
 3318:               $array[0] ='Array reference error';
 3319:               return (\@array, $string);
 3320:           }
 3321:       } else {
 3322: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3323:       }
 3324:       $string =~ s/^&//;
 3325: 
 3326:       push(@array, $value);
 3327:   }
 3328: 
 3329:   $string =~ s/^__END_ARRAY_REF__//;
 3330: 
 3331:   return (\@array, $string);
 3332: }
 3333: 
 3334: # -------------------------------------------------------------------Temp Store
 3335: 
 3336: sub tmpreset {
 3337:   my ($symb,$namespace,$domain,$stuname) = @_;
 3338:   if (!$symb) {
 3339:     $symb=&symbread();
 3340:     if (!$symb) { $symb= $env{'request.url'}; }
 3341:   }
 3342:   $symb=escape($symb);
 3343: 
 3344:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3345:   $namespace=~s/\//\_/g;
 3346:   $namespace=~s/\W//g;
 3347: 
 3348:   if (!$domain) { $domain=$env{'user.domain'}; }
 3349:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3350:   if ($domain eq 'public' && $stuname eq 'public') {
 3351:       $stuname=$ENV{'REMOTE_ADDR'};
 3352:   }
 3353:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3354:   my %hash;
 3355:   if (tie(%hash,'GDBM_File',
 3356: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3357: 	  &GDBM_WRCREAT(),0640)) {
 3358:     foreach my $key (keys %hash) {
 3359:       if ($key=~ /:$symb/) {
 3360: 	delete($hash{$key});
 3361:       }
 3362:     }
 3363:   }
 3364: }
 3365: 
 3366: sub tmpstore {
 3367:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3368: 
 3369:   if (!$symb) {
 3370:     $symb=&symbread();
 3371:     if (!$symb) { $symb= $env{'request.url'}; }
 3372:   }
 3373:   $symb=escape($symb);
 3374: 
 3375:   if (!$namespace) {
 3376:     # I don't think we would ever want to store this for a course.
 3377:     # it seems this will only be used if we don't have a course.
 3378:     #$namespace=$env{'request.course.id'};
 3379:     #if (!$namespace) {
 3380:       $namespace=$env{'request.state'};
 3381:     #}
 3382:   }
 3383:   $namespace=~s/\//\_/g;
 3384:   $namespace=~s/\W//g;
 3385:   if (!$domain) { $domain=$env{'user.domain'}; }
 3386:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3387:   if ($domain eq 'public' && $stuname eq 'public') {
 3388:       $stuname=$ENV{'REMOTE_ADDR'};
 3389:   }
 3390:   my $now=time;
 3391:   my %hash;
 3392:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3393:   if (tie(%hash,'GDBM_File',
 3394: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3395: 	  &GDBM_WRCREAT(),0640)) {
 3396:     $hash{"version:$symb"}++;
 3397:     my $version=$hash{"version:$symb"};
 3398:     my $allkeys=''; 
 3399:     foreach my $key (keys(%$storehash)) {
 3400:       $allkeys.=$key.':';
 3401:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3402:     }
 3403:     $hash{"$version:$symb:timestamp"}=$now;
 3404:     $allkeys.='timestamp';
 3405:     $hash{"$version:keys:$symb"}=$allkeys;
 3406:     if (untie(%hash)) {
 3407:       return 'ok';
 3408:     } else {
 3409:       return "error:$!";
 3410:     }
 3411:   } else {
 3412:     return "error:$!";
 3413:   }
 3414: }
 3415: 
 3416: # -----------------------------------------------------------------Temp Restore
 3417: 
 3418: sub tmprestore {
 3419:   my ($symb,$namespace,$domain,$stuname) = @_;
 3420: 
 3421:   if (!$symb) {
 3422:     $symb=&symbread();
 3423:     if (!$symb) { $symb= $env{'request.url'}; }
 3424:   }
 3425:   $symb=escape($symb);
 3426: 
 3427:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3428: 
 3429:   if (!$domain) { $domain=$env{'user.domain'}; }
 3430:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3431:   if ($domain eq 'public' && $stuname eq 'public') {
 3432:       $stuname=$ENV{'REMOTE_ADDR'};
 3433:   }
 3434:   my %returnhash;
 3435:   $namespace=~s/\//\_/g;
 3436:   $namespace=~s/\W//g;
 3437:   my %hash;
 3438:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3439:   if (tie(%hash,'GDBM_File',
 3440: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3441: 	  &GDBM_READER(),0640)) {
 3442:     my $version=$hash{"version:$symb"};
 3443:     $returnhash{'version'}=$version;
 3444:     my $scope;
 3445:     for ($scope=1;$scope<=$version;$scope++) {
 3446:       my $vkeys=$hash{"$scope:keys:$symb"};
 3447:       my @keys=split(/:/,$vkeys);
 3448:       my $key;
 3449:       $returnhash{"$scope:keys"}=$vkeys;
 3450:       foreach $key (@keys) {
 3451: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3452: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3453:       }
 3454:     }
 3455:     if (!(untie(%hash))) {
 3456:       return "error:$!";
 3457:     }
 3458:   } else {
 3459:     return "error:$!";
 3460:   }
 3461:   return %returnhash;
 3462: }
 3463: 
 3464: # ----------------------------------------------------------------------- Store
 3465: 
 3466: sub store {
 3467:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3468:     my $home='';
 3469: 
 3470:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3471: 
 3472:     $symb=&symbclean($symb);
 3473:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3474: 
 3475:     if (!$domain) { $domain=$env{'user.domain'}; }
 3476:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3477: 
 3478:     &devalidate($symb,$stuname,$domain);
 3479: 
 3480:     $symb=escape($symb);
 3481:     if (!$namespace) { 
 3482:        unless ($namespace=$env{'request.course.id'}) { 
 3483:           return ''; 
 3484:        } 
 3485:     }
 3486:     if (!$home) { $home=$env{'user.home'}; }
 3487: 
 3488:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3489:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3490: 
 3491:     my $namevalue='';
 3492:     foreach my $key (keys(%$storehash)) {
 3493:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3494:     }
 3495:     $namevalue=~s/\&$//;
 3496:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3497:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3498: }
 3499: 
 3500: # -------------------------------------------------------------- Critical Store
 3501: 
 3502: sub cstore {
 3503:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3504:     my $home='';
 3505: 
 3506:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3507: 
 3508:     $symb=&symbclean($symb);
 3509:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3510: 
 3511:     if (!$domain) { $domain=$env{'user.domain'}; }
 3512:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3513: 
 3514:     &devalidate($symb,$stuname,$domain);
 3515: 
 3516:     $symb=escape($symb);
 3517:     if (!$namespace) { 
 3518:        unless ($namespace=$env{'request.course.id'}) { 
 3519:           return ''; 
 3520:        } 
 3521:     }
 3522:     if (!$home) { $home=$env{'user.home'}; }
 3523: 
 3524:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3525:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3526: 
 3527:     my $namevalue='';
 3528:     foreach my $key (keys(%$storehash)) {
 3529:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3530:     }
 3531:     $namevalue=~s/\&$//;
 3532:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3533:     return critical
 3534:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3535: }
 3536: 
 3537: # --------------------------------------------------------------------- Restore
 3538: 
 3539: sub restore {
 3540:     my ($symb,$namespace,$domain,$stuname) = @_;
 3541:     my $home='';
 3542: 
 3543:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3544: 
 3545:     if (!$symb) {
 3546:       unless ($symb=escape(&symbread())) { return ''; }
 3547:     } else {
 3548:       $symb=&escape(&symbclean($symb));
 3549:     }
 3550:     if (!$namespace) { 
 3551:        unless ($namespace=$env{'request.course.id'}) { 
 3552:           return ''; 
 3553:        } 
 3554:     }
 3555:     if (!$domain) { $domain=$env{'user.domain'}; }
 3556:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3557:     if (!$home) { $home=$env{'user.home'}; }
 3558:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3559: 
 3560:     my %returnhash=();
 3561:     foreach my $line (split(/\&/,$answer)) {
 3562: 	my ($name,$value)=split(/\=/,$line);
 3563:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3564:     }
 3565:     my $version;
 3566:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3567:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3568:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3569:        }
 3570:     }
 3571:     return %returnhash;
 3572: }
 3573: 
 3574: # ---------------------------------------------------------- Course Description
 3575: 
 3576: sub coursedescription {
 3577:     my ($courseid,$args)=@_;
 3578:     $courseid=~s/^\///;
 3579:     $courseid=~s/\_/\//g;
 3580:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3581:     my $chome=&homeserver($cnum,$cdomain);
 3582:     my $normalid=$cdomain.'_'.$cnum;
 3583:     # need to always cache even if we get errors otherwise we keep 
 3584:     # trying and trying and trying to get the course description.
 3585:     my %envhash=();
 3586:     my %returnhash=();
 3587:     
 3588:     my $expiretime=600;
 3589:     if ($env{'request.course.id'} eq $normalid) {
 3590: 	$expiretime=120;
 3591:     }
 3592: 
 3593:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3594:     if (!$args->{'freshen_cache'}
 3595: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3596: 	foreach my $key (keys(%env)) {
 3597: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3598: 	    my ($setting) = $1;
 3599: 	    $returnhash{$setting} = $env{$key};
 3600: 	}
 3601: 	return %returnhash;
 3602:     }
 3603: 
 3604:     # get the data agin
 3605:     if (!$args->{'one_time'}) {
 3606: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3607:     }
 3608: 
 3609:     if ($chome ne 'no_host') {
 3610:        %returnhash=&dump('environment',$cdomain,$cnum);
 3611:        if (!exists($returnhash{'con_lost'})) {
 3612:            $returnhash{'home'}= $chome;
 3613: 	   $returnhash{'domain'} = $cdomain;
 3614: 	   $returnhash{'num'} = $cnum;
 3615:            if (!defined($returnhash{'type'})) {
 3616:                $returnhash{'type'} = 'Course';
 3617:            }
 3618:            while (my ($name,$value) = each %returnhash) {
 3619:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3620:            }
 3621:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3622:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3623: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3624:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3625:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3626:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3627:        }
 3628:     }
 3629:     if (!$args->{'one_time'}) {
 3630: 	&appenv(\%envhash);
 3631:     }
 3632:     return %returnhash;
 3633: }
 3634: 
 3635: # -------------------------------------------------See if a user is privileged
 3636: 
 3637: sub privileged {
 3638:     my ($username,$domain)=@_;
 3639:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3640: 			&homeserver($username,$domain));
 3641:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3642:     my $now=time;
 3643:     if ($rolesdump ne '') {
 3644:         foreach my $entry (split(/&/,$rolesdump)) {
 3645: 	    if ($entry!~/^rolesdef_/) {
 3646: 		my ($area,$role)=split(/=/,$entry);
 3647: 		$area=~s/\_\w\w$//;
 3648: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3649: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3650: 		    my $active=1;
 3651: 		    if ($tend) {
 3652: 			if ($tend<$now) { $active=0; }
 3653: 		    }
 3654: 		    if ($tstart) {
 3655: 			if ($tstart>$now) { $active=0; }
 3656: 		    }
 3657: 		    if ($active) { return 1; }
 3658: 		}
 3659: 	    }
 3660: 	}
 3661:     }
 3662:     return 0;
 3663: }
 3664: 
 3665: # -------------------------------------------------------- Get user privileges
 3666: 
 3667: sub rolesinit {
 3668:     my ($domain,$username,$authhost)=@_;
 3669:     my %userroles;
 3670:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3671:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3672:     my %allroles=();
 3673:     my %allgroups=();   
 3674:     my $now=time;
 3675:     %userroles = ('user.login.time' => $now);
 3676:     my $group_privs;
 3677: 
 3678:     if ($rolesdump ne '') {
 3679:         foreach my $entry (split(/&/,$rolesdump)) {
 3680: 	  if ($entry!~/^rolesdef_/) {
 3681:             my ($area,$role)=split(/=/,$entry);
 3682: 	    $area=~s/\_\w\w$//;
 3683:             my ($trole,$tend,$tstart,$group_privs);
 3684: 	    if ($role=~/^cr/) { 
 3685: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3686: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3687: 		    ($tend,$tstart)=split('_',$trest);
 3688: 		} else {
 3689: 		    $trole=$role;
 3690: 		}
 3691:             } elsif ($role =~ m|^gr/|) {
 3692:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3693:                 ($trole,$group_privs) = split(/\//,$trole);
 3694:                 $group_privs = &unescape($group_privs);
 3695: 	    } else {
 3696: 		($trole,$tend,$tstart)=split(/_/,$role);
 3697: 	    }
 3698: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3699: 					 $username);
 3700: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3701:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3702:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3703:             if (($area ne '') && ($trole ne '')) {
 3704: 		my $spec=$trole.'.'.$area;
 3705: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3706: 		if ($trole =~ /^cr\//) {
 3707:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3708:                 } elsif ($trole eq 'gr') {
 3709:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3710: 		} else {
 3711:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3712: 		}
 3713:             }
 3714:           }
 3715:         }
 3716:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3717:         $userroles{'user.adv'}    = $adv;
 3718: 	$userroles{'user.author'} = $author;
 3719:         $env{'user.adv'}=$adv;
 3720:     }
 3721:     return \%userroles;  
 3722: }
 3723: 
 3724: sub set_arearole {
 3725:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3726: # log the associated role with the area
 3727:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3728:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3729: }
 3730: 
 3731: sub custom_roleprivs {
 3732:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3733:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3734:     my $homsvr=homeserver($rauthor,$rdomain);
 3735:     if (&hostname($homsvr) ne '') {
 3736:         my ($rdummy,$roledef)=
 3737:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3738:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3739:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3740:             if (defined($syspriv)) {
 3741:                 $$allroles{'cm./'}.=':'.$syspriv;
 3742:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3743:             }
 3744:             if ($tdomain ne '') {
 3745:                 if (defined($dompriv)) {
 3746:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3747:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3748:                 }
 3749:                 if (($trest ne '') && (defined($coursepriv))) {
 3750:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3751:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3752:                 }
 3753:             }
 3754:         }
 3755:     }
 3756: }
 3757: 
 3758: sub group_roleprivs {
 3759:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3760:     my $access = 1;
 3761:     my $now = time;
 3762:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3763:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3764:     if ($access) {
 3765:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3766:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3767:     }
 3768: }
 3769: 
 3770: sub standard_roleprivs {
 3771:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3772:     if (defined($pr{$trole.':s'})) {
 3773:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3774:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3775:     }
 3776:     if ($tdomain ne '') {
 3777:         if (defined($pr{$trole.':d'})) {
 3778:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3779:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3780:         }
 3781:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3782:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3783:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3784:         }
 3785:     }
 3786: }
 3787: 
 3788: sub set_userprivs {
 3789:     my ($userroles,$allroles,$allgroups) = @_; 
 3790:     my $author=0;
 3791:     my $adv=0;
 3792:     my %grouproles = ();
 3793:     if (keys(%{$allgroups}) > 0) {
 3794:         foreach my $role (keys %{$allroles}) {
 3795:             my ($trole,$area,$sec,$extendedarea);
 3796:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3797:                 $trole = $1;
 3798:                 $area = $2;
 3799:                 $sec = $3;
 3800:                 $extendedarea = $area.$sec;
 3801:                 if (exists($$allgroups{$area})) {
 3802:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3803:                         my $spec = $trole.'.'.$extendedarea;
 3804:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3805:                                                 $$allgroups{$area}{$group};
 3806:                     }
 3807:                 }
 3808:             }
 3809:         }
 3810:     }
 3811:     foreach my $group (keys(%grouproles)) {
 3812:         $$allroles{$group} = $grouproles{$group};
 3813:     }
 3814:     foreach my $role (keys(%{$allroles})) {
 3815:         my %thesepriv;
 3816:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3817:         foreach my $item (split(/:/,$$allroles{$role})) {
 3818:             if ($item ne '') {
 3819:                 my ($privilege,$restrictions)=split(/&/,$item);
 3820:                 if ($restrictions eq '') {
 3821:                     $thesepriv{$privilege}='F';
 3822:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3823:                     $thesepriv{$privilege}.=$restrictions;
 3824:                 }
 3825:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3826:             }
 3827:         }
 3828:         my $thesestr='';
 3829:         foreach my $priv (keys(%thesepriv)) {
 3830: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3831: 	}
 3832:         $userroles->{'user.priv.'.$role} = $thesestr;
 3833:     }
 3834:     return ($author,$adv);
 3835: }
 3836: 
 3837: # --------------------------------------------------------------- get interface
 3838: 
 3839: sub get {
 3840:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3841:    my $items='';
 3842:    foreach my $item (@$storearr) {
 3843:        $items.=&escape($item).'&';
 3844:    }
 3845:    $items=~s/\&$//;
 3846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3847:    if (!$uname) { $uname=$env{'user.name'}; }
 3848:    my $uhome=&homeserver($uname,$udomain);
 3849: 
 3850:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3851:    my @pairs=split(/\&/,$rep);
 3852:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3853:      return @pairs;
 3854:    }
 3855:    my %returnhash=();
 3856:    my $i=0;
 3857:    foreach my $item (@$storearr) {
 3858:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3859:       $i++;
 3860:    }
 3861:    return %returnhash;
 3862: }
 3863: 
 3864: # --------------------------------------------------------------- del interface
 3865: 
 3866: sub del {
 3867:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3868:    my $items='';
 3869:    foreach my $item (@$storearr) {
 3870:        $items.=&escape($item).'&';
 3871:    }
 3872: 
 3873:    $items=~s/\&$//;
 3874:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3875:    if (!$uname) { $uname=$env{'user.name'}; }
 3876:    my $uhome=&homeserver($uname,$udomain);
 3877:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3878: }
 3879: 
 3880: # -------------------------------------------------------------- dump interface
 3881: 
 3882: sub dump {
 3883:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3884:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3885:     if (!$uname) { $uname=$env{'user.name'}; }
 3886:     my $uhome=&homeserver($uname,$udomain);
 3887:     if ($regexp) {
 3888: 	$regexp=&escape($regexp);
 3889:     } else {
 3890: 	$regexp='.';
 3891:     }
 3892:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3893:     my @pairs=split(/\&/,$rep);
 3894:     my %returnhash=();
 3895:     foreach my $item (@pairs) {
 3896: 	my ($key,$value)=split(/=/,$item,2);
 3897: 	$key = &unescape($key);
 3898: 	next if ($key =~ /^error: 2 /);
 3899: 	$returnhash{$key}=&thaw_unescape($value);
 3900:     }
 3901:     return %returnhash;
 3902: }
 3903: 
 3904: # --------------------------------------------------------- dumpstore interface
 3905: 
 3906: sub dumpstore {
 3907:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3908:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3909:    if (!$uname) { $uname=$env{'user.name'}; }
 3910:    my $uhome=&homeserver($uname,$udomain);
 3911:    if ($regexp) {
 3912:        $regexp=&escape($regexp);
 3913:    } else {
 3914:        $regexp='.';
 3915:    }
 3916:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3917:    my @pairs=split(/\&/,$rep);
 3918:    my %returnhash=();
 3919:    foreach my $item (@pairs) {
 3920:        my ($key,$value)=split(/=/,$item,2);
 3921:        next if ($key =~ /^error: 2 /);
 3922:        $returnhash{$key}=&thaw_unescape($value);
 3923:    }
 3924:    return %returnhash;
 3925: }
 3926: 
 3927: # -------------------------------------------------------------- keys interface
 3928: 
 3929: sub getkeys {
 3930:    my ($namespace,$udomain,$uname)=@_;
 3931:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3932:    if (!$uname) { $uname=$env{'user.name'}; }
 3933:    my $uhome=&homeserver($uname,$udomain);
 3934:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3935:    my @keyarray=();
 3936:    foreach my $key (split(/\&/,$rep)) {
 3937:       next if ($key =~ /^error: 2 /);
 3938:       push(@keyarray,&unescape($key));
 3939:    }
 3940:    return @keyarray;
 3941: }
 3942: 
 3943: # --------------------------------------------------------------- currentdump
 3944: sub currentdump {
 3945:    my ($courseid,$sdom,$sname)=@_;
 3946:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3947:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3948:    $sname    = $env{'user.name'}         if (! defined($sname));
 3949:    my $uhome = &homeserver($sname,$sdom);
 3950:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3951:    return if ($rep =~ /^(error:|no_such_host)/);
 3952:    #
 3953:    my %returnhash=();
 3954:    #
 3955:    if ($rep eq "unknown_cmd") { 
 3956:        # an old lond will not know currentdump
 3957:        # Do a dump and make it look like a currentdump
 3958:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3959:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3960:        my %hash = @tmp;
 3961:        @tmp=();
 3962:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3963:    } else {
 3964:        my @pairs=split(/\&/,$rep);
 3965:        foreach my $pair (@pairs) {
 3966:            my ($key,$value)=split(/=/,$pair,2);
 3967:            my ($symb,$param) = split(/:/,$key);
 3968:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3969:                                                         &thaw_unescape($value);
 3970:        }
 3971:    }
 3972:    return %returnhash;
 3973: }
 3974: 
 3975: sub convert_dump_to_currentdump{
 3976:     my %hash = %{shift()};
 3977:     my %returnhash;
 3978:     # Code ripped from lond, essentially.  The only difference
 3979:     # here is the unescaping done by lonnet::dump().  Conceivably
 3980:     # we might run in to problems with parameter names =~ /^v\./
 3981:     while (my ($key,$value) = each(%hash)) {
 3982:         my ($v,$symb,$param) = split(/:/,$key);
 3983: 	$symb  = &unescape($symb);
 3984: 	$param = &unescape($param);
 3985:         next if ($v eq 'version' || $symb eq 'keys');
 3986:         next if (exists($returnhash{$symb}) &&
 3987:                  exists($returnhash{$symb}->{$param}) &&
 3988:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3989:         $returnhash{$symb}->{$param}=$value;
 3990:         $returnhash{$symb}->{'v.'.$param}=$v;
 3991:     }
 3992:     #
 3993:     # Remove all of the keys in the hashes which keep track of
 3994:     # the version of the parameter.
 3995:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3996:         # use a foreach because we are going to delete from the hash.
 3997:         foreach my $key (keys(%$param_hash)) {
 3998:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3999:         }
 4000:     }
 4001:     return \%returnhash;
 4002: }
 4003: 
 4004: # ------------------------------------------------------ critical inc interface
 4005: 
 4006: sub cinc {
 4007:     return &inc(@_,'critical');
 4008: }
 4009: 
 4010: # --------------------------------------------------------------- inc interface
 4011: 
 4012: sub inc {
 4013:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4014:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4015:     if (!$uname) { $uname=$env{'user.name'}; }
 4016:     my $uhome=&homeserver($uname,$udomain);
 4017:     my $items='';
 4018:     if (! ref($store)) {
 4019:         # got a single value, so use that instead
 4020:         $items = &escape($store).'=&';
 4021:     } elsif (ref($store) eq 'SCALAR') {
 4022:         $items = &escape($$store).'=&';        
 4023:     } elsif (ref($store) eq 'ARRAY') {
 4024:         $items = join('=&',map {&escape($_);} @{$store});
 4025:     } elsif (ref($store) eq 'HASH') {
 4026:         while (my($key,$value) = each(%{$store})) {
 4027:             $items.= &escape($key).'='.&escape($value).'&';
 4028:         }
 4029:     }
 4030:     $items=~s/\&$//;
 4031:     if ($critical) {
 4032: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4033:     } else {
 4034: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4035:     }
 4036: }
 4037: 
 4038: # --------------------------------------------------------------- put interface
 4039: 
 4040: sub put {
 4041:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4042:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4043:    if (!$uname) { $uname=$env{'user.name'}; }
 4044:    my $uhome=&homeserver($uname,$udomain);
 4045:    my $items='';
 4046:    foreach my $item (keys(%$storehash)) {
 4047:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4048:    }
 4049:    $items=~s/\&$//;
 4050:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4051: }
 4052: 
 4053: # ------------------------------------------------------------ newput interface
 4054: 
 4055: sub newput {
 4056:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4058:    if (!$uname) { $uname=$env{'user.name'}; }
 4059:    my $uhome=&homeserver($uname,$udomain);
 4060:    my $items='';
 4061:    foreach my $key (keys(%$storehash)) {
 4062:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4063:    }
 4064:    $items=~s/\&$//;
 4065:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4066: }
 4067: 
 4068: # ---------------------------------------------------------  putstore interface
 4069: 
 4070: sub putstore {
 4071:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4072:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4073:    if (!$uname) { $uname=$env{'user.name'}; }
 4074:    my $uhome=&homeserver($uname,$udomain);
 4075:    my $items='';
 4076:    foreach my $key (keys(%$storehash)) {
 4077:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4078:    }
 4079:    $items=~s/\&$//;
 4080:    my $esc_symb=&escape($symb);
 4081:    my $esc_v=&escape($version);
 4082:    my $reply =
 4083:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4084: 	      $uhome);
 4085:    if ($reply eq 'unknown_cmd') {
 4086:        # gfall back to way things use to be done
 4087:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4088: 			    $uname);
 4089:    }
 4090:    return $reply;
 4091: }
 4092: 
 4093: sub old_putstore {
 4094:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4095:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4096:     if (!$uname) { $uname=$env{'user.name'}; }
 4097:     my $uhome=&homeserver($uname,$udomain);
 4098:     my %newstorehash;
 4099:     foreach my $item (keys(%$storehash)) {
 4100: 	my $key = $version.':'.&escape($symb).':'.$item;
 4101: 	$newstorehash{$key} = $storehash->{$item};
 4102:     }
 4103:     my $items='';
 4104:     my %allitems = ();
 4105:     foreach my $item (keys(%newstorehash)) {
 4106: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4107: 	    my $key = $1.':keys:'.$2;
 4108: 	    $allitems{$key} .= $3.':';
 4109: 	}
 4110: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4111:     }
 4112:     foreach my $item (keys(%allitems)) {
 4113: 	$allitems{$item} =~ s/\:$//;
 4114: 	$items.= $item.'='.$allitems{$item}.'&';
 4115:     }
 4116:     $items=~s/\&$//;
 4117:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4118: }
 4119: 
 4120: # ------------------------------------------------------ critical put interface
 4121: 
 4122: sub cput {
 4123:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4124:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4125:    if (!$uname) { $uname=$env{'user.name'}; }
 4126:    my $uhome=&homeserver($uname,$udomain);
 4127:    my $items='';
 4128:    foreach my $item (keys(%$storehash)) {
 4129:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4130:    }
 4131:    $items=~s/\&$//;
 4132:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4133: }
 4134: 
 4135: # -------------------------------------------------------------- eget interface
 4136: 
 4137: sub eget {
 4138:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4139:    my $items='';
 4140:    foreach my $item (@$storearr) {
 4141:        $items.=&escape($item).'&';
 4142:    }
 4143:    $items=~s/\&$//;
 4144:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4145:    if (!$uname) { $uname=$env{'user.name'}; }
 4146:    my $uhome=&homeserver($uname,$udomain);
 4147:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4148:    my @pairs=split(/\&/,$rep);
 4149:    my %returnhash=();
 4150:    my $i=0;
 4151:    foreach my $item (@$storearr) {
 4152:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4153:       $i++;
 4154:    }
 4155:    return %returnhash;
 4156: }
 4157: 
 4158: # ------------------------------------------------------------ tmpput interface
 4159: sub tmpput {
 4160:     my ($storehash,$server,$context)=@_;
 4161:     my $items='';
 4162:     foreach my $item (keys(%$storehash)) {
 4163: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4164:     }
 4165:     $items=~s/\&$//;
 4166:     if (defined($context)) {
 4167:         $items .= ':'.&escape($context);
 4168:     }
 4169:     return &reply("tmpput:$items",$server);
 4170: }
 4171: 
 4172: # ------------------------------------------------------------ tmpget interface
 4173: sub tmpget {
 4174:     my ($token,$server)=@_;
 4175:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4176:     my $rep=&reply("tmpget:$token",$server);
 4177:     my %returnhash;
 4178:     foreach my $item (split(/\&/,$rep)) {
 4179: 	my ($key,$value)=split(/=/,$item);
 4180:         next if ($key =~ /^error: 2 /);
 4181: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4182:     }
 4183:     return %returnhash;
 4184: }
 4185: 
 4186: # ------------------------------------------------------------ tmpget interface
 4187: sub tmpdel {
 4188:     my ($token,$server)=@_;
 4189:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4190:     return &reply("tmpdel:$token",$server);
 4191: }
 4192: 
 4193: # -------------------------------------------------- portfolio access checking
 4194: 
 4195: sub portfolio_access {
 4196:     my ($requrl) = @_;
 4197:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4198:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4199:     if ($result) {
 4200:         my %setters;
 4201:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4202:             my ($startblock,$endblock) =
 4203:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4204:             if ($startblock && $endblock) {
 4205:                 return 'B';
 4206:             }
 4207:         } else {
 4208:             my ($startblock,$endblock) =
 4209:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4210:             if ($startblock && $endblock) {
 4211:                 return 'B';
 4212:             }
 4213:         }
 4214:     }
 4215:     if ($result eq 'ok') {
 4216:        return 'F';
 4217:     } elsif ($result =~ /^[^:]+:guest_/) {
 4218:        return 'A';
 4219:     }
 4220:     return '';
 4221: }
 4222: 
 4223: sub get_portfolio_access {
 4224:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4225: 
 4226:     if (!ref($access_hash)) {
 4227: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4228: 	my %access_controls = &get_access_controls($current_perms,$group,
 4229: 						   $file_name);
 4230: 	$access_hash = $access_controls{$file_name};
 4231:     }
 4232: 
 4233:     my ($public,$guest,@domains,@users,@courses,@groups);
 4234:     my $now = time;
 4235:     if (ref($access_hash) eq 'HASH') {
 4236:         foreach my $key (keys(%{$access_hash})) {
 4237:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4238:             if ($start > $now) {
 4239:                 next;
 4240:             }
 4241:             if ($end && $end<$now) {
 4242:                 next;
 4243:             }
 4244:             if ($scope eq 'public') {
 4245:                 $public = $key;
 4246:                 last;
 4247:             } elsif ($scope eq 'guest') {
 4248:                 $guest = $key;
 4249:             } elsif ($scope eq 'domains') {
 4250:                 push(@domains,$key);
 4251:             } elsif ($scope eq 'users') {
 4252:                 push(@users,$key);
 4253:             } elsif ($scope eq 'course') {
 4254:                 push(@courses,$key);
 4255:             } elsif ($scope eq 'group') {
 4256:                 push(@groups,$key);
 4257:             }
 4258:         }
 4259:         if ($public) {
 4260:             return 'ok';
 4261:         }
 4262:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4263:             if ($guest) {
 4264:                 return $guest;
 4265:             }
 4266:         } else {
 4267:             if (@domains > 0) {
 4268:                 foreach my $domkey (@domains) {
 4269:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4270:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4271:                             return 'ok';
 4272:                         }
 4273:                     }
 4274:                 }
 4275:             }
 4276:             if (@users > 0) {
 4277:                 foreach my $userkey (@users) {
 4278:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4279:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4280:                             if (ref($item) eq 'HASH') {
 4281:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4282:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4283:                                     return 'ok';
 4284:                                 }
 4285:                             }
 4286:                         }
 4287:                     } 
 4288:                 }
 4289:             }
 4290:             my %roleshash;
 4291:             my @courses_and_groups = @courses;
 4292:             push(@courses_and_groups,@groups); 
 4293:             if (@courses_and_groups > 0) {
 4294:                 my (%allgroups,%allroles); 
 4295:                 my ($start,$end,$role,$sec,$group);
 4296:                 foreach my $envkey (%env) {
 4297:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4298:                         my $cid = $2.'_'.$3; 
 4299:                         if ($1 eq 'gr') {
 4300:                             $group = $4;
 4301:                             $allgroups{$cid}{$group} = $env{$envkey};
 4302:                         } else {
 4303:                             if ($4 eq '') {
 4304:                                 $sec = 'none';
 4305:                             } else {
 4306:                                 $sec = $4;
 4307:                             }
 4308:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4309:                         }
 4310:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4311:                         my $cid = $2.'_'.$3;
 4312:                         if ($4 eq '') {
 4313:                             $sec = 'none';
 4314:                         } else {
 4315:                             $sec = $4;
 4316:                         }
 4317:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4318:                     }
 4319:                 }
 4320:                 if (keys(%allroles) == 0) {
 4321:                     return;
 4322:                 }
 4323:                 foreach my $key (@courses_and_groups) {
 4324:                     my %content = %{$$access_hash{$key}};
 4325:                     my $cnum = $content{'number'};
 4326:                     my $cdom = $content{'domain'};
 4327:                     my $cid = $cdom.'_'.$cnum;
 4328:                     if (!exists($allroles{$cid})) {
 4329:                         next;
 4330:                     }    
 4331:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4332:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4333:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4334:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4335:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4336:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4337:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4338:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4339:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4340:                                         if (grep/^all$/,@sections) {
 4341:                                             return 'ok';
 4342:                                         } else {
 4343:                                             if (grep/^$sec$/,@sections) {
 4344:                                                 return 'ok';
 4345:                                             }
 4346:                                         }
 4347:                                     }
 4348:                                 }
 4349:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4350:                                     if (grep/^none$/,@groups) {
 4351:                                         return 'ok';
 4352:                                     }
 4353:                                 } else {
 4354:                                     if (grep/^all$/,@groups) {
 4355:                                         return 'ok';
 4356:                                     } 
 4357:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4358:                                         if (grep/^$group$/,@groups) {
 4359:                                             return 'ok';
 4360:                                         }
 4361:                                     }
 4362:                                 } 
 4363:                             }
 4364:                         }
 4365:                     }
 4366:                 }
 4367:             }
 4368:             if ($guest) {
 4369:                 return $guest;
 4370:             }
 4371:         }
 4372:     }
 4373:     return;
 4374: }
 4375: 
 4376: sub course_group_datechecker {
 4377:     my ($dates,$now,$status) = @_;
 4378:     my ($start,$end) = split(/\./,$dates);
 4379:     if (!$start && !$end) {
 4380:         return 'ok';
 4381:     }
 4382:     if (grep/^active$/,@{$status}) {
 4383:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4384:             return 'ok';
 4385:         }
 4386:     }
 4387:     if (grep/^previous$/,@{$status}) {
 4388:         if ($end > $now ) {
 4389:             return 'ok';
 4390:         }
 4391:     }
 4392:     if (grep/^future$/,@{$status}) {
 4393:         if ($start > $now) {
 4394:             return 'ok';
 4395:         }
 4396:     }
 4397:     return; 
 4398: }
 4399: 
 4400: sub parse_portfolio_url {
 4401:     my ($url) = @_;
 4402: 
 4403:     my ($type,$udom,$unum,$group,$file_name);
 4404:     
 4405:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4406: 	$type = 1;
 4407:         $udom = $1;
 4408:         $unum = $2;
 4409:         $file_name = $3;
 4410:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4411: 	$type = 2;
 4412:         $udom = $1;
 4413:         $unum = $2;
 4414:         $group = $3;
 4415:         $file_name = $3.'/'.$4;
 4416:     }
 4417:     if (wantarray) {
 4418: 	return ($type,$udom,$unum,$file_name,$group);
 4419:     }
 4420:     return $type;
 4421: }
 4422: 
 4423: sub is_portfolio_url {
 4424:     my ($url) = @_;
 4425:     return scalar(&parse_portfolio_url($url));
 4426: }
 4427: 
 4428: sub is_portfolio_file {
 4429:     my ($file) = @_;
 4430:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4431:         return 1;
 4432:     }
 4433:     return;
 4434: }
 4435: 
 4436: sub usertools_access {
 4437:     my ($uname,$udom,$tool,$action,$context) = @_;
 4438:     my ($access,%tools);
 4439:     if ($context eq '') {
 4440:         $context = 'tools';
 4441:     }
 4442:     if ($context eq 'requestcourses') {
 4443:         %tools = (
 4444:                       official   => 1,
 4445:                       unofficial => 1,
 4446:                  );
 4447:     } else {
 4448:         %tools = (
 4449:                       aboutme   => 1,
 4450:                       blog      => 1,
 4451:                       portfolio => 1,
 4452:                  );
 4453:     }
 4454:     return if (!defined($tools{$tool}));
 4455: 
 4456:     if ((!defined($udom)) || (!defined($uname))) {
 4457:         $udom = $env{'user.domain'};
 4458:         $uname = $env{'user.name'};
 4459:     }
 4460: 
 4461:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4462:         if ($action ne 'reload') {
 4463:             if ($context eq 'requestcourses') {
 4464:                 return $env{'environment.canrequest.'.$tool};
 4465:             } else {
 4466:                 return $env{'environment.availabletools.'.$tool};
 4467:             }
 4468:         }
 4469:     }
 4470: 
 4471:     my ($toolstatus,$inststatus);
 4472: 
 4473:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4474:          ($action ne 'reload')) {
 4475:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4476:         $inststatus = $env{'environment.inststatus'};
 4477:     } else {
 4478:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4479:         $toolstatus = $userenv{$context.'.'.$tool};
 4480:         $inststatus = $userenv{'inststatus'};
 4481:     }
 4482: 
 4483:     if ($toolstatus ne '') {
 4484:         if ($toolstatus) {
 4485:             $access = 1;
 4486:         } else {
 4487:             $access = 0;
 4488:         }
 4489:         return $access;
 4490:     }
 4491: 
 4492:     my $is_adv = &is_advanced_user($udom,$uname);
 4493:     my %domdef = &get_domain_defaults($udom);
 4494:     if (ref($domdef{$tool}) eq 'HASH') {
 4495:         if ($is_adv) {
 4496:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4497:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4498:                     $access = 1;
 4499:                 } else {
 4500:                     $access = 0;
 4501:                 }
 4502:                 return $access;
 4503:             }
 4504:         }
 4505:         if ($inststatus ne '') {
 4506:             my ($hasaccess,$hasnoaccess);
 4507:             foreach my $affiliation (split(/:/,$inststatus)) {
 4508:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4509:                     if ($domdef{$tool}{$affiliation}) {
 4510:                         $hasaccess = 1;
 4511:                     } else {
 4512:                         $hasnoaccess = 1;
 4513:                     }
 4514:                 }
 4515:             }
 4516:             if ($hasaccess || $hasnoaccess) {
 4517:                 if ($hasaccess) {
 4518:                     $access = 1;
 4519:                 } elsif ($hasnoaccess) {
 4520:                     $access = 0; 
 4521:                 }
 4522:                 return $access;
 4523:             }
 4524:         } else {
 4525:             if ($domdef{$tool}{'default'} ne '') {
 4526:                 if ($domdef{$tool}{'default'}) {
 4527:                     $access = 1;
 4528:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4529:                     $access = 0;
 4530:                 }
 4531:                 return $access;
 4532:             }
 4533:         }
 4534:     } else {
 4535:         if ($context eq 'tools') {
 4536:             $access = 1;
 4537:         } else {
 4538:             $access = 0;
 4539:         }
 4540:         return $access;
 4541:     }
 4542: }
 4543: 
 4544: sub is_advanced_user {
 4545:     my ($udom,$uname) = @_;
 4546:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4547:     my %allroles;
 4548:     my $is_adv;
 4549:     foreach my $role (keys(%roleshash)) {
 4550:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4551:         my $area = '/'.$tdomain.'/'.$trest;
 4552:         if ($sec ne '') {
 4553:             $area .= '/'.$sec;
 4554:         }
 4555:         if (($area ne '') && ($trole ne '')) {
 4556:             my $spec=$trole.'.'.$area;
 4557:             if ($trole =~ /^cr\//) {
 4558:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4559:             } elsif ($trole ne 'gr') {
 4560:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4561:             }
 4562:         }
 4563:     }
 4564:     foreach my $role (keys(%allroles)) {
 4565:         last if ($is_adv);
 4566:         foreach my $item (split(/:/,$allroles{$role})) {
 4567:             if ($item ne '') {
 4568:                 my ($privilege,$restrictions)=split(/&/,$item);
 4569:                 if ($privilege eq 'adv') {
 4570:                     $is_adv = 1;
 4571:                     last;
 4572:                 }
 4573:             }
 4574:         }
 4575:     }
 4576:     return $is_adv;
 4577: }
 4578: 
 4579: # ---------------------------------------------- Custom access rule evaluation
 4580: 
 4581: sub customaccess {
 4582:     my ($priv,$uri)=@_;
 4583:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4584:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4585:     $udom = &LONCAPA::clean_domain($udom);
 4586:     $ucrs = &LONCAPA::clean_username($ucrs);
 4587:     my $access=0;
 4588:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4589: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4590: 	if ($type eq 'user') {
 4591: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4592: 		my ($tdom,$tuname)=split(m{/},$scope);
 4593: 		if ($tdom) {
 4594: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4595: 		}
 4596: 		if ($tuname) {
 4597: 		    if ($tuname ne $env{'user.name'}) { next; }
 4598: 		}
 4599: 		$access=($effect eq 'allow');
 4600: 		last;
 4601: 	    }
 4602: 	} else {
 4603: 	    if ($role) {
 4604: 		if ($role ne $urole) { next; }
 4605: 	    }
 4606: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4607: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4608: 		if ($tdom) {
 4609: 		    if ($tdom ne $udom) { next; }
 4610: 		}
 4611: 		if ($tcrs) {
 4612: 		    if ($tcrs ne $ucrs) { next; }
 4613: 		}
 4614: 		if ($tsec) {
 4615: 		    if ($tsec ne $usec) { next; }
 4616: 		}
 4617: 		$access=($effect eq 'allow');
 4618: 		last;
 4619: 	    }
 4620: 	    if ($realm eq '' && $role eq '') {
 4621: 		$access=($effect eq 'allow');
 4622: 	    }
 4623: 	}
 4624:     }
 4625:     return $access;
 4626: }
 4627: 
 4628: # ------------------------------------------------- Check for a user privilege
 4629: 
 4630: sub allowed {
 4631:     my ($priv,$uri,$symb,$role)=@_;
 4632:     my $ver_orguri=$uri;
 4633:     $uri=&deversion($uri);
 4634:     my $orguri=$uri;
 4635:     $uri=&declutter($uri);
 4636: 
 4637:     if ($priv eq 'evb') {
 4638: # Evade communication block restrictions for specified role in a course
 4639:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4640:             return $1;
 4641:         } else {
 4642:             return;
 4643:         }
 4644:     }
 4645: 
 4646:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4647: # Free bre access to adm and meta resources
 4648:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4649: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4650: 	&& ($priv eq 'bre')) {
 4651: 	return 'F';
 4652:     }
 4653: 
 4654: # Free bre access to user's own portfolio contents
 4655:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4656:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4657: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4658:         my %setters;
 4659:         my ($startblock,$endblock) = 
 4660:             &Apache::loncommon::blockcheck(\%setters,'port');
 4661:         if ($startblock && $endblock) {
 4662:             return 'B';
 4663:         } else {
 4664:             return 'F';
 4665:         }
 4666:     }
 4667: 
 4668: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4669:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4670:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4671:         if (exists($env{'request.course.id'})) {
 4672:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4673:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4674:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4675:                 my $courseprivid=$env{'request.course.id'};
 4676:                 $courseprivid=~s/\_/\//;
 4677:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4678:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4679:                     return $1; 
 4680:                 } else {
 4681:                     if ($env{'request.course.sec'}) {
 4682:                         $courseprivid.='/'.$env{'request.course.sec'};
 4683:                     }
 4684:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4685:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4686:                         return $2;
 4687:                     }
 4688:                 }
 4689:             }
 4690:         }
 4691:     }
 4692: 
 4693: # Free bre to public access
 4694: 
 4695:     if ($priv eq 'bre') {
 4696:         my $copyright=&metadata($uri,'copyright');
 4697: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4698:            return 'F'; 
 4699:         }
 4700:         if ($copyright eq 'priv') {
 4701:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4702: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4703: 		return '';
 4704:             }
 4705:         }
 4706:         if ($copyright eq 'domain') {
 4707:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4708: 	    unless (($env{'user.domain'} eq $1) ||
 4709:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4710: 		return '';
 4711:             }
 4712:         }
 4713:         if ($env{'request.role'}=~ /li\.\//) {
 4714:             # Library role, so allow browsing of resources in this domain.
 4715:             return 'F';
 4716:         }
 4717:         if ($copyright eq 'custom') {
 4718: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4719:         }
 4720:     }
 4721:     # Domain coordinator is trying to create a course
 4722:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4723:         # uri is the requested domain in this case.
 4724:         # comparison to 'request.role.domain' shows if the user has selected
 4725:         # a role of dc for the domain in question.
 4726:         return 'F' if ($uri eq $env{'request.role.domain'});
 4727:     }
 4728: 
 4729:     my $thisallowed='';
 4730:     my $statecond=0;
 4731:     my $courseprivid='';
 4732: 
 4733: # Course
 4734: 
 4735:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4736:        $thisallowed.=$1;
 4737:     }
 4738: 
 4739: # Domain
 4740: 
 4741:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4742:        =~/\Q$priv\E\&([^\:]*)/) {
 4743:        $thisallowed.=$1;
 4744:     }
 4745: 
 4746: # Course: uri itself is a course
 4747:     my $courseuri=$uri;
 4748:     $courseuri=~s/\_(\d)/\/$1/;
 4749:     $courseuri=~s/^([^\/])/\/$1/;
 4750: 
 4751:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4752:        =~/\Q$priv\E\&([^\:]*)/) {
 4753:        $thisallowed.=$1;
 4754:     }
 4755: 
 4756: # URI is an uploaded document for this course, default permissions don't matter
 4757: # not allowing 'edit' access (editupload) to uploaded course docs
 4758:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4759: 	$thisallowed='';
 4760:         my ($match)=&is_on_map($uri);
 4761:         if ($match) {
 4762:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4763:                   =~/\Q$priv\E\&([^\:]*)/) {
 4764:                 $thisallowed.=$1;
 4765:             }
 4766:         } else {
 4767:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4768:             if ($refuri) {
 4769:                 if ($refuri =~ m|^/adm/|) {
 4770:                     $thisallowed='F';
 4771:                 } else {
 4772:                     $refuri=&declutter($refuri);
 4773:                     my ($match) = &is_on_map($refuri);
 4774:                     if ($match) {
 4775:                         $thisallowed='F';
 4776:                     }
 4777:                 }
 4778:             }
 4779:         }
 4780:     }
 4781: 
 4782:     if ($priv eq 'bre'
 4783: 	&& $thisallowed ne 'F' 
 4784: 	&& $thisallowed ne '2'
 4785: 	&& &is_portfolio_url($uri)) {
 4786: 	$thisallowed = &portfolio_access($uri);
 4787:     }
 4788:     
 4789: # Full access at system, domain or course-wide level? Exit.
 4790:     if ($thisallowed=~/F/) {
 4791: 	return 'F';
 4792:     }
 4793: 
 4794: # If this is generating or modifying users, exit with special codes
 4795: 
 4796:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4797: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4798: 	    my ($audom,$auname)=split('/',$uri);
 4799: # no author name given, so this just checks on the general right to make a co-author in this domain
 4800: 	    unless ($auname) { return $thisallowed; }
 4801: # an author name is given, so we are about to actually make a co-author for a certain account
 4802: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4803: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4804: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4805: 	}
 4806: 	return $thisallowed;
 4807:     }
 4808: #
 4809: # Gathered so far: system, domain and course wide privileges
 4810: #
 4811: # Course: See if uri or referer is an individual resource that is part of 
 4812: # the course
 4813: 
 4814:     if ($env{'request.course.id'}) {
 4815: 
 4816:        $courseprivid=$env{'request.course.id'};
 4817:        if ($env{'request.course.sec'}) {
 4818:           $courseprivid.='/'.$env{'request.course.sec'};
 4819:        }
 4820:        $courseprivid=~s/\_/\//;
 4821:        my $checkreferer=1;
 4822:        my ($match,$cond)=&is_on_map($uri);
 4823:        if ($match) {
 4824:            $statecond=$cond;
 4825:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4826:                =~/\Q$priv\E\&([^\:]*)/) {
 4827:                $thisallowed.=$1;
 4828:                $checkreferer=0;
 4829:            }
 4830:        }
 4831:        
 4832:        if ($checkreferer) {
 4833: 	  my $refuri=$env{'httpref.'.$orguri};
 4834:             unless ($refuri) {
 4835:                 foreach my $key (keys(%env)) {
 4836: 		    if ($key=~/^httpref\..*\*/) {
 4837: 			my $pattern=$key;
 4838:                         $pattern=~s/^httpref\.\/res\///;
 4839:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4840:                         $pattern=~s/\//\\\//g;
 4841:                         if ($orguri=~/$pattern/) {
 4842: 			    $refuri=$env{$key};
 4843:                         }
 4844:                     }
 4845:                 }
 4846:             }
 4847: 
 4848:          if ($refuri) { 
 4849: 	  $refuri=&declutter($refuri);
 4850:           my ($match,$cond)=&is_on_map($refuri);
 4851:             if ($match) {
 4852:               my $refstatecond=$cond;
 4853:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4854:                   =~/\Q$priv\E\&([^\:]*)/) {
 4855:                   $thisallowed.=$1;
 4856:                   $uri=$refuri;
 4857:                   $statecond=$refstatecond;
 4858:               }
 4859:           }
 4860:         }
 4861:        }
 4862:    }
 4863: 
 4864: #
 4865: # Gathered now: all privileges that could apply, and condition number
 4866: # 
 4867: #
 4868: # Full or no access?
 4869: #
 4870: 
 4871:     if ($thisallowed=~/F/) {
 4872: 	return 'F';
 4873:     }
 4874: 
 4875:     unless ($thisallowed) {
 4876:         return '';
 4877:     }
 4878: 
 4879: # Restrictions exist, deal with them
 4880: #
 4881: #   C:according to course preferences
 4882: #   R:according to resource settings
 4883: #   L:unless locked
 4884: #   X:according to user session state
 4885: #
 4886: 
 4887: # Possibly locked functionality, check all courses
 4888: # Locks might take effect only after 10 minutes cache expiration for other
 4889: # courses, and 2 minutes for current course
 4890: 
 4891:     my $envkey;
 4892:     if ($thisallowed=~/L/) {
 4893:         foreach $envkey (keys %env) {
 4894:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4895:                my $courseid=$2;
 4896:                my $roleid=$1.'.'.$2;
 4897:                $courseid=~s/^\///;
 4898:                my $expiretime=600;
 4899:                if ($env{'request.role'} eq $roleid) {
 4900: 		  $expiretime=120;
 4901:                }
 4902: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4903:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4904:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4905: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4906:                }
 4907:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4908:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4909: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4910:                        &log($env{'user.domain'},$env{'user.name'},
 4911:                             $env{'user.home'},
 4912:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4913:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4914:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4915: 		       return '';
 4916:                    }
 4917:                }
 4918:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4919:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4920: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4921:                        &log($env{'user.domain'},$env{'user.name'},
 4922:                             $env{'user.home'},
 4923:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4924:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4925:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4926: 		       return '';
 4927:                    }
 4928:                }
 4929: 	   }
 4930:        }
 4931:     }
 4932:    
 4933: #
 4934: # Rest of the restrictions depend on selected course
 4935: #
 4936: 
 4937:     unless ($env{'request.course.id'}) {
 4938: 	if ($thisallowed eq 'A') {
 4939: 	    return 'A';
 4940:         } elsif ($thisallowed eq 'B') {
 4941:             return 'B';
 4942: 	} else {
 4943: 	    return '1';
 4944: 	}
 4945:     }
 4946: 
 4947: #
 4948: # Now user is definitely in a course
 4949: #
 4950: 
 4951: 
 4952: # Course preferences
 4953: 
 4954:    if ($thisallowed=~/C/) {
 4955:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4956:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4957:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4958: 	   =~/\Q$rolecode\E/) {
 4959: 	   if ($priv ne 'pch') { 
 4960: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4961: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4962: 			$env{'request.course.id'});
 4963: 	   }
 4964:            return '';
 4965:        }
 4966: 
 4967:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4968: 	   =~/\Q$unamedom\E/) {
 4969: 	   if ($priv ne 'pch') { 
 4970: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4971: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4972: 			$env{'request.course.id'});
 4973: 	   }
 4974:            return '';
 4975:        }
 4976:    }
 4977: 
 4978: # Resource preferences
 4979: 
 4980:    if ($thisallowed=~/R/) {
 4981:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4982:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4983: 	   if ($priv ne 'pch') { 
 4984: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4985: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4986: 	   }
 4987: 	   return '';
 4988:        }
 4989:    }
 4990: 
 4991: # Restricted by state or randomout?
 4992: 
 4993:    if ($thisallowed=~/X/) {
 4994:       if ($env{'acc.randomout'}) {
 4995: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4996:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4997:             return ''; 
 4998:          }
 4999:       }
 5000:       if (&condval($statecond)) {
 5001: 	 return '2';
 5002:       } else {
 5003:          return '';
 5004:       }
 5005:    }
 5006: 
 5007:     if ($thisallowed eq 'A') {
 5008: 	return 'A';
 5009:     } elsif ($thisallowed eq 'B') {
 5010:         return 'B';
 5011:     }
 5012:    return 'F';
 5013: }
 5014: 
 5015: sub split_uri_for_cond {
 5016:     my $uri=&deversion(&declutter(shift));
 5017:     my @uriparts=split(/\//,$uri);
 5018:     my $filename=pop(@uriparts);
 5019:     my $pathname=join('/',@uriparts);
 5020:     return ($pathname,$filename);
 5021: }
 5022: # --------------------------------------------------- Is a resource on the map?
 5023: 
 5024: sub is_on_map {
 5025:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5026:     #Trying to find the conditional for the file
 5027:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5028: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5029:     if ($match) {
 5030: 	return (1,$1);
 5031:     } else {
 5032: 	return (0,0);
 5033:     }
 5034: }
 5035: 
 5036: # --------------------------------------------------------- Get symb from alias
 5037: 
 5038: sub get_symb_from_alias {
 5039:     my $symb=shift;
 5040:     my ($map,$resid,$url)=&decode_symb($symb);
 5041: # Already is a symb
 5042:     if ($url) { return $symb; }
 5043: # Must be an alias
 5044:     my $aliassymb='';
 5045:     my %bighash;
 5046:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5047:                             &GDBM_READER(),0640)) {
 5048:         my $rid=$bighash{'mapalias_'.$symb};
 5049: 	if ($rid) {
 5050: 	    my ($mapid,$resid)=split(/\./,$rid);
 5051: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5052: 				    $resid,$bighash{'src_'.$rid});
 5053: 	}
 5054:         untie %bighash;
 5055:     }
 5056:     return $aliassymb;
 5057: }
 5058: 
 5059: # ----------------------------------------------------------------- Define Role
 5060: 
 5061: sub definerole {
 5062:   if (allowed('mcr','/')) {
 5063:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5064:     foreach my $role (split(':',$sysrole)) {
 5065: 	my ($crole,$cqual)=split(/\&/,$role);
 5066:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5067:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5068: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5069:                return "refused:s:$crole&$cqual"; 
 5070:             }
 5071:         }
 5072:     }
 5073:     foreach my $role (split(':',$domrole)) {
 5074: 	my ($crole,$cqual)=split(/\&/,$role);
 5075:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5076:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5077: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5078:                return "refused:d:$crole&$cqual"; 
 5079:             }
 5080:         }
 5081:     }
 5082:     foreach my $role (split(':',$courole)) {
 5083: 	my ($crole,$cqual)=split(/\&/,$role);
 5084:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5085:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5086: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5087:                return "refused:c:$crole&$cqual"; 
 5088:             }
 5089:         }
 5090:     }
 5091:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5092:                 "$env{'user.domain'}:$env{'user.name'}:".
 5093: 	        "rolesdef_$rolename=".
 5094:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5095:     return reply($command,$env{'user.home'});
 5096:   } else {
 5097:     return 'refused';
 5098:   }
 5099: }
 5100: 
 5101: # ---------------- Make a metadata query against the network of library servers
 5102: 
 5103: sub metadata_query {
 5104:     my ($query,$custom,$customshow,$server_array)=@_;
 5105:     my %rhash;
 5106:     my %libserv = &all_library();
 5107:     my @server_list = (defined($server_array) ? @$server_array
 5108:                                               : keys(%libserv) );
 5109:     for my $server (@server_list) {
 5110: 	unless ($custom or $customshow) {
 5111: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5112: 	    $rhash{$server}=$reply;
 5113: 	}
 5114: 	else {
 5115: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5116: 			     &escape($custom).':'.&escape($customshow),
 5117: 			     $server);
 5118: 	    $rhash{$server}=$reply;
 5119: 	}
 5120:     }
 5121:     return \%rhash;
 5122: }
 5123: 
 5124: # ----------------------------------------- Send log queries and wait for reply
 5125: 
 5126: sub log_query {
 5127:     my ($uname,$udom,$query,%filters)=@_;
 5128:     my $uhome=&homeserver($uname,$udom);
 5129:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5130:     my $uhost=&hostname($uhome);
 5131:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5132:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5133:                        $uhome);
 5134:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5135:     return get_query_reply($queryid);
 5136: }
 5137: 
 5138: # -------------------------- Update MySQL table for portfolio file
 5139: 
 5140: sub update_portfolio_table {
 5141:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5142:     if ($group ne '') {
 5143:         $file_name =~s /^\Q$group\E//;
 5144:     }
 5145:     my $homeserver = &homeserver($uname,$udom);
 5146:     my $queryid=
 5147:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5148:                ':'.&escape($file_name).':'.$action,$homeserver);
 5149:     my $reply = &get_query_reply($queryid);
 5150:     return $reply;
 5151: }
 5152: 
 5153: # -------------------------- Update MySQL allusers table
 5154: 
 5155: sub update_allusers_table {
 5156:     my ($uname,$udom,$names) = @_;
 5157:     my $homeserver = &homeserver($uname,$udom);
 5158:     my $queryid=
 5159:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5160:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5161:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5162:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5163:                'generation='.&escape($names->{'generation'}).'%%'.
 5164:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5165:                'id='.&escape($names->{'id'}),$homeserver);
 5166:     my $reply = &get_query_reply($queryid);
 5167:     return $reply;
 5168: }
 5169: 
 5170: # ------- Request retrieval of institutional classlists for course(s)
 5171: 
 5172: sub fetch_enrollment_query {
 5173:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5174:     my $homeserver;
 5175:     my $maxtries = 1;
 5176:     if ($context eq 'automated') {
 5177:         $homeserver = $perlvar{'lonHostID'};
 5178:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5179:     } else {
 5180:         $homeserver = &homeserver($cnum,$dom);
 5181:     }
 5182:     my $host=&hostname($homeserver);
 5183:     my $cmd = '';
 5184:     foreach my $affiliate (keys %{$affiliatesref}) {
 5185:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5186:     }
 5187:     $cmd =~ s/%%$//;
 5188:     $cmd = &escape($cmd);
 5189:     my $query = 'fetchenrollment';
 5190:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5191:     unless ($queryid=~/^\Q$host\E\_/) { 
 5192:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5193:         return 'error: '.$queryid;
 5194:     }
 5195:     my $reply = &get_query_reply($queryid);
 5196:     my $tries = 1;
 5197:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5198:         $reply = &get_query_reply($queryid);
 5199:         $tries ++;
 5200:     }
 5201:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5202:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5203:     } else {
 5204:         my @responses = split(/:/,$reply);
 5205:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5206:             foreach my $line (@responses) {
 5207:                 my ($key,$value) = split(/=/,$line,2);
 5208:                 $$replyref{$key} = $value;
 5209:             }
 5210:         } else {
 5211:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5212:             foreach my $line (@responses) {
 5213:                 my ($key,$value) = split(/=/,$line);
 5214:                 $$replyref{$key} = $value;
 5215:                 if ($value > 0) {
 5216:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5217:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5218:                         my $destname = $pathname.'/'.$filename;
 5219:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5220:                         if ($xml_classlist =~ /^error/) {
 5221:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5222:                         } else {
 5223:                             if ( open(FILE,">$destname") ) {
 5224:                                 print FILE &unescape($xml_classlist);
 5225:                                 close(FILE);
 5226:                             } else {
 5227:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5228:                             }
 5229:                         }
 5230:                     }
 5231:                 }
 5232:             }
 5233:         }
 5234:         return 'ok';
 5235:     }
 5236:     return 'error';
 5237: }
 5238: 
 5239: sub get_query_reply {
 5240:     my $queryid=shift;
 5241:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5242:     my $reply='';
 5243:     for (1..100) {
 5244: 	sleep 2;
 5245:         if (-e $replyfile.'.end') {
 5246: 	    if (open(my $fh,$replyfile)) {
 5247: 		$reply = join('',<$fh>);
 5248: 		close($fh);
 5249: 	   } else { return 'error: reply_file_error'; }
 5250:            return &unescape($reply);
 5251: 	}
 5252:     }
 5253:     return 'timeout:'.$queryid;
 5254: }
 5255: 
 5256: sub courselog_query {
 5257: #
 5258: # possible filters:
 5259: # url: url or symb
 5260: # username
 5261: # domain
 5262: # action: view, submit, grade
 5263: # start: timestamp
 5264: # end: timestamp
 5265: #
 5266:     my (%filters)=@_;
 5267:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5268:     if ($filters{'url'}) {
 5269: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5270:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5271:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5272:     }
 5273:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5274:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5275:     return &log_query($cname,$cdom,'courselog',%filters);
 5276: }
 5277: 
 5278: sub userlog_query {
 5279: #
 5280: # possible filters:
 5281: # action: log check role
 5282: # start: timestamp
 5283: # end: timestamp
 5284: #
 5285:     my ($uname,$udom,%filters)=@_;
 5286:     return &log_query($uname,$udom,'userlog',%filters);
 5287: }
 5288: 
 5289: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5290: 
 5291: sub auto_run {
 5292:     my ($cnum,$cdom) = @_;
 5293:     my $response = 0;
 5294:     my $settings;
 5295:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5296:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5297:         $settings = $domconfig{'autoenroll'};
 5298:         if ($settings->{'run'} eq '1') {
 5299:             $response = 1;
 5300:         }
 5301:     } else {
 5302:         my $homeserver;
 5303:         if (&is_course($cdom,$cnum)) {
 5304:             $homeserver = &homeserver($cnum,$cdom);
 5305:         } else {
 5306:             $homeserver = &domain($cdom,'primary');
 5307:         }
 5308:         if ($homeserver ne 'no_host') {
 5309:             $response = &reply('autorun:'.$cdom,$homeserver);
 5310:         }
 5311:     }
 5312:     return $response;
 5313: }
 5314: 
 5315: sub auto_get_sections {
 5316:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5317:     my $homeserver = &homeserver($cnum,$cdom);
 5318:     my @secs = ();
 5319:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5320:     unless ($response eq 'refused') {
 5321:         @secs = split(/:/,$response);
 5322:     }
 5323:     return @secs;
 5324: }
 5325: 
 5326: sub auto_new_course {
 5327:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5328:     my $homeserver = &homeserver($cnum,$cdom);
 5329:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5330:     return $response;
 5331: }
 5332: 
 5333: sub auto_validate_courseID {
 5334:     my ($cnum,$cdom,$inst_course_id) = @_;
 5335:     my $homeserver = &homeserver($cnum,$cdom);
 5336:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5337:     return $response;
 5338: }
 5339: 
 5340: sub auto_create_password {
 5341:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5342:     my ($homeserver,$response);
 5343:     my $create_passwd = 0;
 5344:     my $authchk = '';
 5345:     if ($udom =~ /^$match_domain$/) {
 5346:         $homeserver = &domain($udom,'primary');
 5347:     }
 5348:     if ($homeserver eq '') {
 5349:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5350:             $homeserver = &homeserver($cnum,$cdom);
 5351:         }
 5352:     }
 5353:     if ($homeserver eq '') {
 5354:         $authchk = 'nodomain';
 5355:     } else {
 5356:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5357:         if ($response eq 'refused') {
 5358:             $authchk = 'refused';
 5359:         } else {
 5360:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5361:         }
 5362:     }
 5363:     return ($authparam,$create_passwd,$authchk);
 5364: }
 5365: 
 5366: sub auto_photo_permission {
 5367:     my ($cnum,$cdom,$students) = @_;
 5368:     my $homeserver = &homeserver($cnum,$cdom);
 5369:     my ($outcome,$perm_reqd,$conditions) = 
 5370: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5371:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5372: 	return (undef,undef);
 5373:     }
 5374:     return ($outcome,$perm_reqd,$conditions);
 5375: }
 5376: 
 5377: sub auto_checkphotos {
 5378:     my ($uname,$udom,$pid) = @_;
 5379:     my $homeserver = &homeserver($uname,$udom);
 5380:     my ($result,$resulttype);
 5381:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5382: 				   &escape($uname).':'.&escape($pid),
 5383: 				   $homeserver));
 5384:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5385: 	return (undef,undef);
 5386:     }
 5387:     if ($outcome) {
 5388:         ($result,$resulttype) = split(/:/,$outcome);
 5389:     } 
 5390:     return ($result,$resulttype);
 5391: }
 5392: 
 5393: sub auto_photochoice {
 5394:     my ($cnum,$cdom) = @_;
 5395:     my $homeserver = &homeserver($cnum,$cdom);
 5396:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5397: 						       &escape($cdom),
 5398: 						       $homeserver)));
 5399:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5400: 	return (undef,undef);
 5401:     }
 5402:     return ($update,$comment);
 5403: }
 5404: 
 5405: sub auto_photoupdate {
 5406:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5407:     my $homeserver = &homeserver($cnum,$dom);
 5408:     my $host=&hostname($homeserver);
 5409:     my $cmd = '';
 5410:     my $maxtries = 1;
 5411:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5412:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5413:     }
 5414:     $cmd =~ s/%%$//;
 5415:     $cmd = &escape($cmd);
 5416:     my $query = 'institutionalphotos';
 5417:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5418:     unless ($queryid=~/^\Q$host\E\_/) {
 5419:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5420:         return 'error: '.$queryid;
 5421:     }
 5422:     my $reply = &get_query_reply($queryid);
 5423:     my $tries = 1;
 5424:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5425:         $reply = &get_query_reply($queryid);
 5426:         $tries ++;
 5427:     }
 5428:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5429:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5430:     } else {
 5431:         my @responses = split(/:/,$reply);
 5432:         my $outcome = shift(@responses); 
 5433:         foreach my $item (@responses) {
 5434:             my ($key,$value) = split(/=/,$item);
 5435:             $$photo{$key} = $value;
 5436:         }
 5437:         return $outcome;
 5438:     }
 5439:     return 'error';
 5440: }
 5441: 
 5442: sub auto_instcode_format {
 5443:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5444: 	$cat_order) = @_;
 5445:     my $courses = '';
 5446:     my @homeservers;
 5447:     if ($caller eq 'global') {
 5448: 	my %servers = &get_servers($codedom,'library');
 5449: 	foreach my $tryserver (keys(%servers)) {
 5450: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5451: 		push(@homeservers,$tryserver);
 5452: 	    }
 5453:         }
 5454:     } else {
 5455:         push(@homeservers,&homeserver($caller,$codedom));
 5456:     }
 5457:     foreach my $code (keys(%{$instcodes})) {
 5458:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5459:     }
 5460:     chop($courses);
 5461:     my $ok_response = 0;
 5462:     my $response;
 5463:     while (@homeservers > 0 && $ok_response == 0) {
 5464:         my $server = shift(@homeservers); 
 5465:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5466:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5467:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5468: 		split(/:/,$response);
 5469:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5470:             push(@{$codetitles},&str2array($codetitles_str));
 5471:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5472:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5473:             $ok_response = 1;
 5474:         }
 5475:     }
 5476:     if ($ok_response) {
 5477:         return 'ok';
 5478:     } else {
 5479:         return $response;
 5480:     }
 5481: }
 5482: 
 5483: sub auto_instcode_defaults {
 5484:     my ($domain,$returnhash,$code_order) = @_;
 5485:     my @homeservers;
 5486: 
 5487:     my %servers = &get_servers($domain,'library');
 5488:     foreach my $tryserver (keys(%servers)) {
 5489: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5490: 	    push(@homeservers,$tryserver);
 5491: 	}
 5492:     }
 5493: 
 5494:     my $response;
 5495:     foreach my $server (@homeservers) {
 5496:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5497:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5498: 	
 5499: 	foreach my $pair (split(/\&/,$response)) {
 5500: 	    my ($name,$value)=split(/\=/,$pair);
 5501: 	    if ($name eq 'code_order') {
 5502: 		@{$code_order} = split(/\&/,&unescape($value));
 5503: 	    } else {
 5504: 		$returnhash->{&unescape($name)}=&unescape($value);
 5505: 	    }
 5506: 	}
 5507: 	return 'ok';
 5508:     }
 5509: 
 5510:     return $response;
 5511: } 
 5512: 
 5513: sub auto_validate_class_sec {
 5514:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5515:     my $homeserver = &homeserver($cnum,$cdom);
 5516:     my $ownerlist;
 5517:     if (ref($owners) eq 'ARRAY') {
 5518:         $ownerlist = join(',',@{$owners});
 5519:     } else {
 5520:         $ownerlist = $owners;
 5521:     }
 5522:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5523:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5524:     return $response;
 5525: }
 5526: 
 5527: # ------------------------------------------------------- Course Group routines
 5528: 
 5529: sub get_coursegroups {
 5530:     my ($cdom,$cnum,$group,$namespace) = @_;
 5531:     return(&dump($namespace,$cdom,$cnum,$group));
 5532: }
 5533: 
 5534: sub modify_coursegroup {
 5535:     my ($cdom,$cnum,$groupsettings) = @_;
 5536:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5537: }
 5538: 
 5539: sub toggle_coursegroup_status {
 5540:     my ($cdom,$cnum,$group,$action) = @_;
 5541:     my ($from_namespace,$to_namespace);
 5542:     if ($action eq 'delete') {
 5543:         $from_namespace = 'coursegroups';
 5544:         $to_namespace = 'deleted_groups';
 5545:     } else {
 5546:         $from_namespace = 'deleted_groups';
 5547:         $to_namespace = 'coursegroups';
 5548:     }
 5549:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5550:     if (my $tmp = &error(%curr_group)) {
 5551:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5552:         return ('read error',$tmp);
 5553:     } else {
 5554:         my %savedsettings = %curr_group; 
 5555:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5556:         my $deloutcome;
 5557:         if ($result eq 'ok') {
 5558:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5559:         } else {
 5560:             return ('write error',$result);
 5561:         }
 5562:         if ($deloutcome eq 'ok') {
 5563:             return 'ok';
 5564:         } else {
 5565:             return ('delete error',$deloutcome);
 5566:         }
 5567:     }
 5568: }
 5569: 
 5570: sub modify_group_roles {
 5571:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5572:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5573:     my $role = 'gr/'.&escape($userprivs);
 5574:     my ($uname,$udom) = split(/:/,$user);
 5575:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5576:     if ($result eq 'ok') {
 5577:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5578:     }
 5579:     return $result;
 5580: }
 5581: 
 5582: sub modify_coursegroup_membership {
 5583:     my ($cdom,$cnum,$membership) = @_;
 5584:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5585:     return $result;
 5586: }
 5587: 
 5588: sub get_active_groups {
 5589:     my ($udom,$uname,$cdom,$cnum) = @_;
 5590:     my $now = time;
 5591:     my %groups = ();
 5592:     foreach my $key (keys(%env)) {
 5593:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5594:             my ($start,$end) = split(/\./,$env{$key});
 5595:             if (($end!=0) && ($end<$now)) { next; }
 5596:             if (($start!=0) && ($start>$now)) { next; }
 5597:             if ($1 eq $cdom && $2 eq $cnum) {
 5598:                 $groups{$3} = $env{$key} ;
 5599:             }
 5600:         }
 5601:     }
 5602:     return %groups;
 5603: }
 5604: 
 5605: sub get_group_membership {
 5606:     my ($cdom,$cnum,$group) = @_;
 5607:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5608: }
 5609: 
 5610: sub get_users_groups {
 5611:     my ($udom,$uname,$courseid) = @_;
 5612:     my @usersgroups;
 5613:     my $cachetime=1800;
 5614: 
 5615:     my $hashid="$udom:$uname:$courseid";
 5616:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5617:     if (defined($cached)) {
 5618:         @usersgroups = split(/:/,$grouplist);
 5619:     } else {  
 5620:         $grouplist = '';
 5621:         my $courseurl = &courseid_to_courseurl($courseid);
 5622:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5623:         my $access_end = $env{'course.'.$courseid.
 5624:                               '.default_enrollment_end_date'};
 5625:         my $now = time;
 5626:         foreach my $key (keys(%roleshash)) {
 5627:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5628:                 my $group = $1;
 5629:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5630:                     my $start = $2;
 5631:                     my $end = $1;
 5632:                     if ($start == -1) { next; } # deleted from group
 5633:                     if (($start!=0) && ($start>$now)) { next; }
 5634:                     if (($end!=0) && ($end<$now)) {
 5635:                         if ($access_end && $access_end < $now) {
 5636:                             if ($access_end - $end < 86400) {
 5637:                                 push(@usersgroups,$group);
 5638:                             }
 5639:                         }
 5640:                         next;
 5641:                     }
 5642:                     push(@usersgroups,$group);
 5643:                 }
 5644:             }
 5645:         }
 5646:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5647:         $grouplist = join(':',@usersgroups);
 5648:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5649:     }
 5650:     return @usersgroups;
 5651: }
 5652: 
 5653: sub devalidate_getgroups_cache {
 5654:     my ($udom,$uname,$cdom,$cnum)=@_;
 5655:     my $courseid = $cdom.'_'.$cnum;
 5656: 
 5657:     my $hashid="$udom:$uname:$courseid";
 5658:     &devalidate_cache_new('getgroups',$hashid);
 5659: }
 5660: 
 5661: # ------------------------------------------------------------------ Plain Text
 5662: 
 5663: sub plaintext {
 5664:     my ($short,$type,$cid) = @_;
 5665:     if ($short =~ /^cr/) {
 5666: 	return (split('/',$short))[-1];
 5667:     }
 5668:     if (!defined($cid)) {
 5669:         $cid = $env{'request.course.id'};
 5670:     }
 5671:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5672:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5673:                                           '.plaintext'});
 5674:     }
 5675:     my %rolenames = (
 5676:                       Course => 'std',
 5677:                       Group => 'alt1',
 5678:                     );
 5679:     if (defined($type) && 
 5680:          defined($rolenames{$type}) && 
 5681:          defined($prp{$short}{$rolenames{$type}})) {
 5682:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5683:     } else {
 5684:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5685:     }
 5686: }
 5687: 
 5688: # ----------------------------------------------------------------- Assign Role
 5689: 
 5690: sub assignrole {
 5691:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5692:         $context)=@_;
 5693:     my $mrole;
 5694:     if ($role =~ /^cr\//) {
 5695:         my $cwosec=$url;
 5696:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5697: 	unless (&allowed('ccr',$cwosec)) {
 5698:            &logthis('Refused custom assignrole: '.
 5699:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5700: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5701:            return 'refused'; 
 5702:         }
 5703:         $mrole='cr';
 5704:     } elsif ($role =~ /^gr\//) {
 5705:         my $cwogrp=$url;
 5706:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5707:         unless (&allowed('mdg',$cwogrp)) {
 5708:             &logthis('Refused group assignrole: '.
 5709:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5710:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5711:             return 'refused';
 5712:         }
 5713:         $mrole='gr';
 5714:     } else {
 5715:         my $cwosec=$url;
 5716:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5717:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5718:             my $refused;
 5719:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5720:                 if (!(&allowed('c'.$role,$url))) {
 5721:                     $refused = 1;
 5722:                 }
 5723:             } else {
 5724:                 $refused = 1;
 5725:             }
 5726:             if ($refused) {
 5727:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5728:                     $refused = '';
 5729:                 } else {
 5730:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5731:                              ' '.$role.' '.$end.' '.$start.' by '.
 5732: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5733:                     return 'refused';
 5734:                 }
 5735:             }
 5736:         }
 5737:         $mrole=$role;
 5738:     }
 5739:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5740:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5741:     if ($end) { $command.='_'.$end; }
 5742:     if ($start) {
 5743: 	if ($end) { 
 5744:            $command.='_'.$start; 
 5745:         } else {
 5746:            $command.='_0_'.$start;
 5747:         }
 5748:     }
 5749:     my $origstart = $start;
 5750:     my $origend = $end;
 5751:     my $delflag;
 5752: # actually delete
 5753:     if ($deleteflag) {
 5754: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5755: # modify command to delete the role
 5756:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5757:                 "$udom:$uname:$url".'_'."$mrole";
 5758: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5759: # set start and finish to negative values for userrolelog
 5760:            $start=-1;
 5761:            $end=-1;
 5762:            $delflag = 1;
 5763:         }
 5764:     }
 5765: # send command
 5766:     my $answer=&reply($command,&homeserver($uname,$udom));
 5767: # log new user role if status is ok
 5768:     if ($answer eq 'ok') {
 5769: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5770: # for course roles, perform group memberships changes triggered by role change.
 5771:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5772:         unless ($role =~ /^gr/) {
 5773:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5774:                                              $origstart,$selfenroll,$context);
 5775:         }
 5776:     }
 5777:     return $answer;
 5778: }
 5779: 
 5780: # -------------------------------------------------- Modify user authentication
 5781: # Overrides without validation
 5782: 
 5783: sub modifyuserauth {
 5784:     my ($udom,$uname,$umode,$upass)=@_;
 5785:     my $uhome=&homeserver($uname,$udom);
 5786:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5787:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5788:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5789:              ' in domain '.$env{'request.role.domain'});  
 5790:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5791: 		     &escape($upass),$uhome);
 5792:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5793:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5794:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5795:     &log($udom,,$uname,$uhome,
 5796:         'Authentication changed by '.$env{'user.domain'}.', '.
 5797:                                      $env{'user.name'}.', '.$umode.
 5798:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5799:     unless ($reply eq 'ok') {
 5800:         &logthis('Authentication mode error: '.$reply);
 5801: 	return 'error: '.$reply;
 5802:     }   
 5803:     return 'ok';
 5804: }
 5805: 
 5806: # --------------------------------------------------------------- Modify a user
 5807: 
 5808: sub modifyuser {
 5809:     my ($udom,    $uname, $uid,
 5810:         $umode,   $upass, $first,
 5811:         $middle,  $last,  $gene,
 5812:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5813:     $udom= &LONCAPA::clean_domain($udom);
 5814:     $uname=&LONCAPA::clean_username($uname);
 5815:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5816:              $umode.', '.$first.', '.$middle.', '.
 5817: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5818:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5819:                                      ' desiredhome not specified'). 
 5820:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5821:              ' in domain '.$env{'request.role.domain'});
 5822:     my $uhome=&homeserver($uname,$udom,'true');
 5823: # ----------------------------------------------------------------- Create User
 5824:     if (($uhome eq 'no_host') && 
 5825: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5826:         my $unhome='';
 5827:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5828:             $unhome = $desiredhome;
 5829: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5830: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5831:         } else { # load balancing routine for determining $unhome
 5832:             my $loadm=10000000;
 5833: 	    my %servers = &get_servers($udom,'library');
 5834: 	    foreach my $tryserver (keys(%servers)) {
 5835: 		my $answer=reply('load',$tryserver);
 5836: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5837: 		    $loadm=$answer;
 5838: 		    $unhome=$tryserver;
 5839: 		}
 5840: 	    }
 5841:         }
 5842:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5843: 	    return 'error: unable to find a home server for '.$uname.
 5844:                    ' in domain '.$udom;
 5845:         }
 5846:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5847:                          &escape($upass),$unhome);
 5848: 	unless ($reply eq 'ok') {
 5849:             return 'error: '.$reply;
 5850:         }   
 5851:         $uhome=&homeserver($uname,$udom,'true');
 5852:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5853: 	    return 'error: unable verify users home machine.';
 5854:         }
 5855:     }   # End of creation of new user
 5856: # ---------------------------------------------------------------------- Add ID
 5857:     if ($uid) {
 5858:        $uid=~tr/A-Z/a-z/;
 5859:        my %uidhash=&idrget($udom,$uname);
 5860:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5861:          && (!$forceid)) {
 5862: 	  unless ($uid eq $uidhash{$uname}) {
 5863: 	      return 'error: user id "'.$uid.'" does not match '.
 5864:                   'current user id "'.$uidhash{$uname}.'".';
 5865:           }
 5866:        } else {
 5867: 	  &idput($udom,($uname => $uid));
 5868:        }
 5869:     }
 5870: # -------------------------------------------------------------- Add names, etc
 5871:     my @tmp=&get('environment',
 5872: 		   ['firstname','middlename','lastname','generation','id',
 5873:                     'permanentemail','inststatus'],
 5874: 		   $udom,$uname);
 5875:     my %names;
 5876:     if ($tmp[0] =~ m/^error:.*/) { 
 5877:         %names=(); 
 5878:     } else {
 5879:         %names = @tmp;
 5880:     }
 5881: #
 5882: # Make sure to not trash student environment if instructor does not bother
 5883: # to supply name and email information
 5884: #
 5885:     if ($first)  { $names{'firstname'}  = $first; }
 5886:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5887:     if ($last)   { $names{'lastname'}   = $last; }
 5888:     if (defined($gene))   { $names{'generation'} = $gene; }
 5889:     if ($email) {
 5890:        $email=~s/[^\w\@\.\-\,]//gs;
 5891:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5892:     }
 5893:     if ($uid) { $names{'id'}  = $uid; }
 5894:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5895:     my $reply = &put('environment', \%names, $udom,$uname);
 5896:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5897:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5898:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5899:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5900:                  $umode.', '.$first.', '.$middle.', '.
 5901: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5902:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5903:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5904:     } else {
 5905:         $logmsg .= ' during self creation';
 5906:     }
 5907:     &logthis($logmsg);
 5908:     return 'ok';
 5909: }
 5910: 
 5911: # -------------------------------------------------------------- Modify student
 5912: 
 5913: sub modifystudent {
 5914:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5915:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5916:         $selfenroll,$context)=@_;
 5917:     if (!$cid) {
 5918: 	unless ($cid=$env{'request.course.id'}) {
 5919: 	    return 'not_in_class';
 5920: 	}
 5921:     }
 5922: # --------------------------------------------------------------- Make the user
 5923:     my $reply=&modifyuser
 5924: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5925:          $desiredhome,$email);
 5926:     unless ($reply eq 'ok') { return $reply; }
 5927:     # This will cause &modify_student_enrollment to get the uid from the
 5928:     # students environment
 5929:     $uid = undef if (!$forceid);
 5930:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5931: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5932:     return $reply;
 5933: }
 5934: 
 5935: sub modify_student_enrollment {
 5936:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5937:     my ($cdom,$cnum,$chome);
 5938:     if (!$cid) {
 5939: 	unless ($cid=$env{'request.course.id'}) {
 5940: 	    return 'not_in_class';
 5941: 	}
 5942: 	$cdom=$env{'course.'.$cid.'.domain'};
 5943: 	$cnum=$env{'course.'.$cid.'.num'};
 5944:     } else {
 5945: 	($cdom,$cnum)=split(/_/,$cid);
 5946:     }
 5947:     $chome=$env{'course.'.$cid.'.home'};
 5948:     if (!$chome) {
 5949: 	$chome=&homeserver($cnum,$cdom);
 5950:     }
 5951:     if (!$chome) { return 'unknown_course'; }
 5952:     # Make sure the user exists
 5953:     my $uhome=&homeserver($uname,$udom);
 5954:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5955: 	return 'error: no such user';
 5956:     }
 5957:     # Get student data if we were not given enough information
 5958:     if (!defined($first)  || $first  eq '' || 
 5959:         !defined($last)   || $last   eq '' || 
 5960:         !defined($uid)    || $uid    eq '' || 
 5961:         !defined($middle) || $middle eq '' || 
 5962:         !defined($gene)   || $gene   eq '') {
 5963:         # They did not supply us with enough data to enroll the student, so
 5964:         # we need to pick up more information.
 5965:         my %tmp = &get('environment',
 5966:                        ['firstname','middlename','lastname', 'generation','id']
 5967:                        ,$udom,$uname);
 5968: 
 5969:         #foreach my $key (keys(%tmp)) {
 5970:         #    &logthis("key $key = ".$tmp{$key});
 5971:         #}
 5972:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5973:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5974:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5975:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5976:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5977:     }
 5978:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5979:     my $reply=cput('classlist',
 5980: 		   {"$uname:$udom" => 
 5981: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5982: 		   $cdom,$cnum);
 5983:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5984: 	return 'error: '.$reply;
 5985:     } else {
 5986: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5987:     }
 5988:     # Add student role to user
 5989:     my $uurl='/'.$cid;
 5990:     $uurl=~s/\_/\//g;
 5991:     if ($usec) {
 5992: 	$uurl.='/'.$usec;
 5993:     }
 5994:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5995: }
 5996: 
 5997: sub format_name {
 5998:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5999:     my $name;
 6000:     if ($first ne 'lastname') {
 6001: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6002:     } else {
 6003: 	if ($lastname=~/\S/) {
 6004: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6005: 	    $name=~s/\s+,/,/;
 6006: 	} else {
 6007: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6008: 	}
 6009:     }
 6010:     $name=~s/^\s+//;
 6011:     $name=~s/\s+$//;
 6012:     $name=~s/\s+/ /g;
 6013:     return $name;
 6014: }
 6015: 
 6016: # ------------------------------------------------- Write to course preferences
 6017: 
 6018: sub writecoursepref {
 6019:     my ($courseid,%prefs)=@_;
 6020:     $courseid=~s/^\///;
 6021:     $courseid=~s/\_/\//g;
 6022:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6023:     my $chome=homeserver($cnum,$cdomain);
 6024:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6025: 	return 'error: no such course';
 6026:     }
 6027:     my $cstring='';
 6028:     foreach my $pref (keys(%prefs)) {
 6029: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6030:     }
 6031:     $cstring=~s/\&$//;
 6032:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6033: }
 6034: 
 6035: # ---------------------------------------------------------- Make/modify course
 6036: 
 6037: sub createcourse {
 6038:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6039:         $course_owner,$crstype)=@_;
 6040:     $url=&declutter($url);
 6041:     my $cid='';
 6042:     unless (&allowed('ccc',$udom)) {
 6043:         return 'refused';
 6044:     }
 6045: # ------------------------------------------------------------------- Create ID
 6046:    my $uname=int(1+rand(9)).
 6047:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6048:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6049:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6050: # ----------------------------------------------- Make sure that does not exist
 6051:    my $uhome=&homeserver($uname,$udom,'true');
 6052:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6053:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6054:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6055:        $uhome=&homeserver($uname,$udom,'true');       
 6056:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6057:            return 'error: unable to generate unique course-ID';
 6058:        } 
 6059:    }
 6060: # ------------------------------------------------ Check supplied server name
 6061:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6062:     if (! &is_library($course_server)) {
 6063:         return 'error:bad server name '.$course_server;
 6064:     }
 6065: # ------------------------------------------------------------- Make the course
 6066:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6067:                       $course_server);
 6068:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6069:     $uhome=&homeserver($uname,$udom,'true');
 6070:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6071: 	return 'error: no such course';
 6072:     }
 6073: # ----------------------------------------------------------------- Course made
 6074: # log existence
 6075:     my $newcourse = {
 6076:                     $udom.'_'.$uname => {
 6077:                                      description => $description,
 6078:                                      inst_code   => $inst_code,
 6079:                                      owner       => $course_owner,
 6080:                                      type        => $crstype,
 6081:                                                 },
 6082:                     };
 6083:     &courseidput($udom,$newcourse,$uhome,'notime');
 6084: # set toplevel url
 6085:     my $topurl=$url;
 6086:     unless ($nonstandard) {
 6087: # ------------------------------------------ For standard courses, make top url
 6088:         my $mapurl=&clutter($url);
 6089:         if ($mapurl eq '/res/') { $mapurl=''; }
 6090:         $env{'form.initmap'}=(<<ENDINITMAP);
 6091: <map>
 6092: <resource id="1" type="start"></resource>
 6093: <resource id="2" src="$mapurl"></resource>
 6094: <resource id="3" type="finish"></resource>
 6095: <link index="1" from="1" to="2"></link>
 6096: <link index="2" from="2" to="3"></link>
 6097: </map>
 6098: ENDINITMAP
 6099:         $topurl=&declutter(
 6100:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6101:                           );
 6102:     }
 6103: # ----------------------------------------------------------- Write preferences
 6104:     &writecoursepref($udom.'_'.$uname,
 6105:                      ('description' => $description,
 6106:                       'url'         => $topurl));
 6107:     return '/'.$udom.'/'.$uname;
 6108: }
 6109: 
 6110: sub is_course {
 6111:     my ($cdom,$cnum) = @_;
 6112:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6113: 				undef,'.');
 6114:     if (exists($courses{$cdom.'_'.$cnum})) {
 6115:         return 1;
 6116:     }
 6117:     return 0;
 6118: }
 6119: 
 6120: # ---------------------------------------------------------- Assign Custom Role
 6121: 
 6122: sub assigncustomrole {
 6123:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6124:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6125:                        $end,$start,$deleteflag,$selfenroll,$context);
 6126: }
 6127: 
 6128: # ----------------------------------------------------------------- Revoke Role
 6129: 
 6130: sub revokerole {
 6131:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6132:     my $now=time;
 6133:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6134: }
 6135: 
 6136: # ---------------------------------------------------------- Revoke Custom Role
 6137: 
 6138: sub revokecustomrole {
 6139:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6140:     my $now=time;
 6141:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6142:            $deleteflag,$selfenroll,$context);
 6143: }
 6144: 
 6145: # ------------------------------------------------------------ Disk usage
 6146: sub diskusage {
 6147:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6148:     $directorypath =~ s/\/$//;
 6149:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6150:                        .&escape($getpropath).':'.&escape($uname).':'
 6151:                        .&escape($udom),homeserver($uname,$udom));
 6152:     if ($listing eq 'unknown_cmd') {
 6153:         if ($getpropath) {
 6154:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6155:         }
 6156:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6157:     }
 6158:     return $listing;
 6159: }
 6160: 
 6161: sub is_locked {
 6162:     my ($file_name, $domain, $user) = @_;
 6163:     my @check;
 6164:     my $is_locked;
 6165:     push @check, $file_name;
 6166:     my %locked = &get('file_permissions',\@check,
 6167: 		      $env{'user.domain'},$env{'user.name'});
 6168:     my ($tmp)=keys(%locked);
 6169:     if ($tmp=~/^error:/) { undef(%locked); }
 6170:     
 6171:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6172:         $is_locked = 'false';
 6173:         foreach my $entry (@{$locked{$file_name}}) {
 6174:            if (ref($entry) eq 'ARRAY') { 
 6175:                $is_locked = 'true';
 6176:                last;
 6177:            }
 6178:        }
 6179:     } else {
 6180:         $is_locked = 'false';
 6181:     }
 6182: }
 6183: 
 6184: sub declutter_portfile {
 6185:     my ($file) = @_;
 6186:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6187:     return $file;
 6188: }
 6189: 
 6190: # ------------------------------------------------------------- Mark as Read Only
 6191: 
 6192: sub mark_as_readonly {
 6193:     my ($domain,$user,$files,$what) = @_;
 6194:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6195:     my ($tmp)=keys(%current_permissions);
 6196:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6197:     foreach my $file (@{$files}) {
 6198: 	$file = &declutter_portfile($file);
 6199:         push(@{$current_permissions{$file}},$what);
 6200:     }
 6201:     &put('file_permissions',\%current_permissions,$domain,$user);
 6202:     return;
 6203: }
 6204: 
 6205: # ------------------------------------------------------------Save Selected Files
 6206: 
 6207: sub save_selected_files {
 6208:     my ($user, $path, @files) = @_;
 6209:     my $filename = $user."savedfiles";
 6210:     my @other_files = &files_not_in_path($user, $path);
 6211:     open (OUT, '>'.$tmpdir.$filename);
 6212:     foreach my $file (@files) {
 6213:         print (OUT $env{'form.currentpath'}.$file."\n");
 6214:     }
 6215:     foreach my $file (@other_files) {
 6216:         print (OUT $file."\n");
 6217:     }
 6218:     close (OUT);
 6219:     return 'ok';
 6220: }
 6221: 
 6222: sub clear_selected_files {
 6223:     my ($user) = @_;
 6224:     my $filename = $user."savedfiles";
 6225:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6226:     print (OUT undef);
 6227:     close (OUT);
 6228:     return ("ok");    
 6229: }
 6230: 
 6231: sub files_in_path {
 6232:     my ($user, $path) = @_;
 6233:     my $filename = $user."savedfiles";
 6234:     my %return_files;
 6235:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6236:     while (my $line_in = <IN>) {
 6237:         chomp ($line_in);
 6238:         my @paths_and_file = split (m!/!, $line_in);
 6239:         my $file_part = pop (@paths_and_file);
 6240:         my $path_part = join ('/', @paths_and_file);
 6241:         $path_part.='/';
 6242:         my $path_and_file = $path_part.$file_part;
 6243:         if ($path_part eq $path) {
 6244:             $return_files{$file_part}= 'selected';
 6245:         }
 6246:     }
 6247:     close (IN);
 6248:     return (\%return_files);
 6249: }
 6250: 
 6251: # called in portfolio select mode, to show files selected NOT in current directory
 6252: sub files_not_in_path {
 6253:     my ($user, $path) = @_;
 6254:     my $filename = $user."savedfiles";
 6255:     my @return_files;
 6256:     my $path_part;
 6257:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6258:     while (my $line = <IN>) {
 6259:         #ok, I know it's clunky, but I want it to work
 6260:         my @paths_and_file = split(m|/|, $line);
 6261:         my $file_part = pop(@paths_and_file);
 6262:         chomp($file_part);
 6263:         my $path_part = join('/', @paths_and_file);
 6264:         $path_part .= '/';
 6265:         my $path_and_file = $path_part.$file_part;
 6266:         if ($path_part ne $path) {
 6267:             push(@return_files, ($path_and_file));
 6268:         }
 6269:     }
 6270:     close(OUT);
 6271:     return (@return_files);
 6272: }
 6273: 
 6274: #----------------------------------------------Get portfolio file permissions
 6275: 
 6276: sub get_portfile_permissions {
 6277:     my ($domain,$user) = @_;
 6278:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6279:     my ($tmp)=keys(%current_permissions);
 6280:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6281:     return \%current_permissions;
 6282: }
 6283: 
 6284: #---------------------------------------------Get portfolio file access controls
 6285: 
 6286: sub get_access_controls {
 6287:     my ($current_permissions,$group,$file) = @_;
 6288:     my %access;
 6289:     my $real_file = $file;
 6290:     $file =~ s/\.meta$//;
 6291:     if (defined($file)) {
 6292:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6293:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6294:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6295:             }
 6296:         }
 6297:     } else {
 6298:         foreach my $key (keys(%{$current_permissions})) {
 6299:             if ($key =~ /\0accesscontrol$/) {
 6300:                 if (defined($group)) {
 6301:                     if ($key !~ m-^\Q$group\E/-) {
 6302:                         next;
 6303:                     }
 6304:                 }
 6305:                 my ($fullpath) = split(/\0/,$key);
 6306:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6307:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6308:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6309:                     }
 6310:                 }
 6311:             }
 6312:         }
 6313:     }
 6314:     return %access;
 6315: }
 6316: 
 6317: sub modify_access_controls {
 6318:     my ($file_name,$changes,$domain,$user)=@_;
 6319:     my ($outcome,$deloutcome);
 6320:     my %store_permissions;
 6321:     my %new_values;
 6322:     my %new_control;
 6323:     my %translation;
 6324:     my @deletions = ();
 6325:     my $now = time;
 6326:     if (exists($$changes{'activate'})) {
 6327:         if (ref($$changes{'activate'}) eq 'HASH') {
 6328:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6329:             my $numnew = scalar(@newitems);
 6330:             for (my $i=0; $i<$numnew; $i++) {
 6331:                 my $newkey = $newitems[$i];
 6332:                 my $newid = &Apache::loncommon::get_cgi_id();
 6333:                 if ($newkey =~ /^\d+:/) { 
 6334:                     $newkey =~ s/^(\d+)/$newid/;
 6335:                     $translation{$1} = $newid;
 6336:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6337:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6338:                     $translation{$1} = $newid;
 6339:                 }
 6340:                 $new_values{$file_name."\0".$newkey} = 
 6341:                                           $$changes{'activate'}{$newitems[$i]};
 6342:                 $new_control{$newkey} = $now;
 6343:             }
 6344:         }
 6345:     }
 6346:     my %todelete;
 6347:     my %changed_items;
 6348:     foreach my $action ('delete','update') {
 6349:         if (exists($$changes{$action})) {
 6350:             if (ref($$changes{$action}) eq 'HASH') {
 6351:                 foreach my $key (keys(%{$$changes{$action}})) {
 6352:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6353:                     if ($action eq 'delete') { 
 6354:                         $todelete{$itemnum} = 1;
 6355:                     } else {
 6356:                         $changed_items{$itemnum} = $key;
 6357:                     }
 6358:                 }
 6359:             }
 6360:         }
 6361:     }
 6362:     # get lock on access controls for file.
 6363:     my $lockhash = {
 6364:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6365:                                                        ':'.$env{'user.domain'},
 6366:                    }; 
 6367:     my $tries = 0;
 6368:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6369:    
 6370:     while (($gotlock ne 'ok') && $tries <3) {
 6371:         $tries ++;
 6372:         sleep 1;
 6373:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6374:     }
 6375:     if ($gotlock eq 'ok') {
 6376:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6377:         my ($tmp)=keys(%curr_permissions);
 6378:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6379:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6380:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6381:             if (ref($curr_controls) eq 'HASH') {
 6382:                 foreach my $control_item (keys(%{$curr_controls})) {
 6383:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6384:                     if (defined($todelete{$itemnum})) {
 6385:                         push(@deletions,$file_name."\0".$control_item);
 6386:                     } else {
 6387:                         if (defined($changed_items{$itemnum})) {
 6388:                             $new_control{$changed_items{$itemnum}} = $now;
 6389:                             push(@deletions,$file_name."\0".$control_item);
 6390:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6391:                         } else {
 6392:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6393:                         }
 6394:                     }
 6395:                 }
 6396:             }
 6397:         }
 6398:         my ($group);
 6399:         if (&is_course($domain,$user)) {
 6400:             ($group,my $file) = split(/\//,$file_name,2);
 6401:         }
 6402:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6403:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6404:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6405:         #  remove lock
 6406:         my @del_lock = ($file_name."\0".'locked_access_records');
 6407:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6408:         my $sqlresult =
 6409:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6410:                                     $group);
 6411:     } else {
 6412:         $outcome = "error: could not obtain lockfile\n";  
 6413:     }
 6414:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6415: }
 6416: 
 6417: sub make_public_indefinitely {
 6418:     my ($requrl) = @_;
 6419:     my $now = time;
 6420:     my $action = 'activate';
 6421:     my $aclnum = 0;
 6422:     if (&is_portfolio_url($requrl)) {
 6423:         my (undef,$udom,$unum,$file_name,$group) =
 6424:             &parse_portfolio_url($requrl);
 6425:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6426:         my %access_controls = &get_access_controls($current_perms,
 6427:                                                    $group,$file_name);
 6428:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6429:             my ($num,$scope,$end,$start) = 
 6430:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6431:             if ($scope eq 'public') {
 6432:                 if ($start <= $now && $end == 0) {
 6433:                     $action = 'none';
 6434:                 } else {
 6435:                     $action = 'update';
 6436:                     $aclnum = $num;
 6437:                 }
 6438:                 last;
 6439:             }
 6440:         }
 6441:         if ($action eq 'none') {
 6442:              return 'ok';
 6443:         } else {
 6444:             my %changes;
 6445:             my $newend = 0;
 6446:             my $newstart = $now;
 6447:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6448:             $changes{$action}{$newkey} = {
 6449:                 type => 'public',
 6450:                 time => {
 6451:                     start => $newstart,
 6452:                     end   => $newend,
 6453:                 },
 6454:             };
 6455:             my ($outcome,$deloutcome,$new_values,$translation) =
 6456:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6457:             return $outcome;
 6458:         }
 6459:     } else {
 6460:         return 'invalid';
 6461:     }
 6462: }
 6463: 
 6464: #------------------------------------------------------Get Marked as Read Only
 6465: 
 6466: sub get_marked_as_readonly {
 6467:     my ($domain,$user,$what,$group) = @_;
 6468:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6469:     my @readonly_files;
 6470:     my $cmp1=$what;
 6471:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6472:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6473:         if (defined($group)) {
 6474:             if ($file_name !~ m-^\Q$group\E/-) {
 6475:                 next;
 6476:             }
 6477:         }
 6478:         if (ref($value) eq "ARRAY"){
 6479:             foreach my $stored_what (@{$value}) {
 6480:                 my $cmp2=$stored_what;
 6481:                 if (ref($stored_what) eq 'ARRAY') {
 6482:                     $cmp2=join('',@{$stored_what});
 6483:                 }
 6484:                 if ($cmp1 eq $cmp2) {
 6485:                     push(@readonly_files, $file_name);
 6486:                     last;
 6487:                 } elsif (!defined($what)) {
 6488:                     push(@readonly_files, $file_name);
 6489:                     last;
 6490:                 }
 6491:             }
 6492:         }
 6493:     }
 6494:     return @readonly_files;
 6495: }
 6496: #-----------------------------------------------------------Get Marked as Read Only Hash
 6497: 
 6498: sub get_marked_as_readonly_hash {
 6499:     my ($current_permissions,$group,$what) = @_;
 6500:     my %readonly_files;
 6501:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6502:         if (defined($group)) {
 6503:             if ($file_name !~ m-^\Q$group\E/-) {
 6504:                 next;
 6505:             }
 6506:         }
 6507:         if (ref($value) eq "ARRAY"){
 6508:             foreach my $stored_what (@{$value}) {
 6509:                 if (ref($stored_what) eq 'ARRAY') {
 6510:                     foreach my $lock_descriptor(@{$stored_what}) {
 6511:                         if ($lock_descriptor eq 'graded') {
 6512:                             $readonly_files{$file_name} = 'graded';
 6513:                         } elsif ($lock_descriptor eq 'handback') {
 6514:                             $readonly_files{$file_name} = 'handback';
 6515:                         } else {
 6516:                             if (!exists($readonly_files{$file_name})) {
 6517:                                 $readonly_files{$file_name} = 'locked';
 6518:                             }
 6519:                         }
 6520:                     }
 6521:                 } 
 6522:             }
 6523:         } 
 6524:     }
 6525:     return %readonly_files;
 6526: }
 6527: # ------------------------------------------------------------ Unmark as Read Only
 6528: 
 6529: sub unmark_as_readonly {
 6530:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6531:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6532:     my ($domain,$user,$what,$file_name,$group) = @_;
 6533:     $file_name = &declutter_portfile($file_name);
 6534:     my $symb_crs = $what;
 6535:     if (ref($what)) { $symb_crs=join('',@$what); }
 6536:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6537:     my ($tmp)=keys(%current_permissions);
 6538:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6539:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6540:     foreach my $file (@readonly_files) {
 6541: 	my $clean_file = &declutter_portfile($file);
 6542: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6543: 	my $current_locks = $current_permissions{$file};
 6544:         my @new_locks;
 6545:         my @del_keys;
 6546:         if (ref($current_locks) eq "ARRAY"){
 6547:             foreach my $locker (@{$current_locks}) {
 6548:                 my $compare=$locker;
 6549:                 if (ref($locker) eq 'ARRAY') {
 6550:                     $compare=join('',@{$locker});
 6551:                     if ($compare ne $symb_crs) {
 6552:                         push(@new_locks, $locker);
 6553:                     }
 6554:                 }
 6555:             }
 6556:             if (scalar(@new_locks) > 0) {
 6557:                 $current_permissions{$file} = \@new_locks;
 6558:             } else {
 6559:                 push(@del_keys, $file);
 6560:                 &del('file_permissions',\@del_keys, $domain, $user);
 6561:                 delete($current_permissions{$file});
 6562:             }
 6563:         }
 6564:     }
 6565:     &put('file_permissions',\%current_permissions,$domain,$user);
 6566:     return;
 6567: }
 6568: 
 6569: # ------------------------------------------------------------ Directory lister
 6570: 
 6571: sub dirlist {
 6572:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6573:     $uri=~s/^\///;
 6574:     $uri=~s/\/$//;
 6575:     my ($udom, $uname);
 6576:     if ($getuserdir) {
 6577:         $udom = $userdomain;
 6578:         $uname = $username;
 6579:     } else {
 6580:         (undef,$udom,$uname)=split(/\//,$uri);
 6581:         if(defined($userdomain)) {
 6582:             $udom = $userdomain;
 6583:         }
 6584:         if(defined($username)) {
 6585:             $uname = $username;
 6586:         }
 6587:     }
 6588:     my ($dirRoot,$listing,@listing_results);
 6589: 
 6590:     $dirRoot = $perlvar{'lonDocRoot'};
 6591:     if (defined($getpropath)) {
 6592:         $dirRoot = &propath($udom,$uname);
 6593:         $dirRoot =~ s/\/$//;
 6594:     } elsif (defined($getuserdir)) {
 6595:         my $subdir=$uname.'__';
 6596:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6597:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6598:                    ."/$udom/$subdir/$uname";
 6599:     } elsif (defined($alternateRoot)) {
 6600:         $dirRoot = $alternateRoot;
 6601:     }
 6602: 
 6603:     if($udom) {
 6604:         if($uname) {
 6605:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6606:                               .$getuserdir.':'.&escape($dirRoot)
 6607:                               .':'.&escape($uname).':'.&escape($udom),
 6608:                               &homeserver($uname,$udom));
 6609:             if ($listing eq 'unknown_cmd') {
 6610:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6611:                                   &homeserver($uname,$udom));
 6612:             } else {
 6613:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6614:             }
 6615:             if ($listing eq 'unknown_cmd') {
 6616:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6617: 				  &homeserver($uname,$udom));
 6618:                 @listing_results = split(/:/,$listing);
 6619:             } else {
 6620:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6621:             }
 6622:             return @listing_results;
 6623:         } elsif(!$alternateRoot) {
 6624:             my %allusers;
 6625: 	    my %servers = &get_servers($udom,'library');
 6626:  	    foreach my $tryserver (keys(%servers)) {
 6627:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6628:                                   &escape($udom),$tryserver);
 6629:                 if ($listing eq 'unknown_cmd') {
 6630: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6631: 				      $udom, $tryserver);
 6632:                 } else {
 6633:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6634:                 }
 6635: 		if ($listing eq 'unknown_cmd') {
 6636: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6637: 				      $udom, $tryserver);
 6638: 		    @listing_results = split(/:/,$listing);
 6639: 		} else {
 6640: 		    @listing_results =
 6641: 			map { &unescape($_); } split(/:/,$listing);
 6642: 		}
 6643: 		if ($listing_results[0] ne 'no_such_dir' && 
 6644: 		    $listing_results[0] ne 'empty'       &&
 6645: 		    $listing_results[0] ne 'con_lost') {
 6646: 		    foreach my $line (@listing_results) {
 6647: 			my ($entry) = split(/&/,$line,2);
 6648: 			$allusers{$entry} = 1;
 6649: 		    }
 6650: 		}
 6651:             }
 6652:             my $alluserstr='';
 6653:             foreach my $user (sort(keys(%allusers))) {
 6654:                 $alluserstr.=$user.'&user:';
 6655:             }
 6656:             $alluserstr=~s/:$//;
 6657:             return split(/:/,$alluserstr);
 6658:         } else {
 6659:             return ('missing user name');
 6660:         }
 6661:     } elsif(!defined($getpropath)) {
 6662:         my @all_domains = sort(&all_domains());
 6663:         foreach my $domain (@all_domains) {
 6664:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6665:         }
 6666:         return @all_domains;
 6667:     } else {
 6668:         return ('missing domain');
 6669:     }
 6670: }
 6671: 
 6672: # --------------------------------------------- GetFileTimestamp
 6673: # This function utilizes dirlist and returns the date stamp for
 6674: # when it was last modified.  It will also return an error of -1
 6675: # if an error occurs
 6676: 
 6677: sub GetFileTimestamp {
 6678:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6679:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6680:     $studentName   = &LONCAPA::clean_username($studentName);
 6681:     my ($fileStat) = 
 6682:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6683:                                  undef,$getuserdir);
 6684:     my @stats = split('&', $fileStat);
 6685:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6686:         # @stats contains first the filename, then the stat output
 6687:         return $stats[10]; # so this is 10 instead of 9.
 6688:     } else {
 6689:         return -1;
 6690:     }
 6691: }
 6692: 
 6693: sub stat_file {
 6694:     my ($uri) = @_;
 6695:     $uri = &clutter_with_no_wrapper($uri);
 6696: 
 6697:     my ($udom,$uname,$file);
 6698:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6699: 	($udom,$uname,$file) =
 6700: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6701: 	$file = 'userfiles/'.$file;
 6702:     }
 6703:     if ($uri =~ m-^/res/-) {
 6704: 	($udom,$uname) = 
 6705: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6706: 	$file = $uri;
 6707:     }
 6708: 
 6709:     if (!$udom || !$uname || !$file) {
 6710: 	# unable to handle the uri
 6711: 	return ();
 6712:     }
 6713:     my $getpropath;
 6714:     if ($file =~ /^userfiles\//) {
 6715:         $getpropath = 1;
 6716:     }
 6717:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6718:     my @stats = split('&', $result);
 6719:     
 6720:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6721: 	shift(@stats); #filename is first
 6722: 	return @stats;
 6723:     }
 6724:     return ();
 6725: }
 6726: 
 6727: # -------------------------------------------------------- Value of a Condition
 6728: 
 6729: # gets the value of a specific preevaluated condition
 6730: #    stored in the string  $env{user.state.<cid>}
 6731: # or looks up a condition reference in the bighash and if if hasn't
 6732: # already been evaluated recurses into docondval to get the value of
 6733: # the condition, then memoizing it to 
 6734: #   $env{user.state.<cid>.<condition>}
 6735: sub directcondval {
 6736:     my $number=shift;
 6737:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6738: 	&Apache::lonuserstate::evalstate();
 6739:     }
 6740:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6741: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6742:     } elsif ($number =~ /^_/) {
 6743: 	my $sub_condition;
 6744: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6745: 		&GDBM_READER(),0640)) {
 6746: 	    $sub_condition=$bighash{'conditions'.$number};
 6747: 	    untie(%bighash);
 6748: 	}
 6749: 	my $value = &docondval($sub_condition);
 6750: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6751: 	return $value;
 6752:     }
 6753:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6754:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6755:     } else {
 6756:        return 2;
 6757:     }
 6758: }
 6759: 
 6760: # get the collection of conditions for this resource
 6761: sub condval {
 6762:     my $condidx=shift;
 6763:     my $allpathcond='';
 6764:     foreach my $cond (split(/\|/,$condidx)) {
 6765: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6766: 	    $allpathcond.=
 6767: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6768: 	}
 6769:     }
 6770:     $allpathcond=~s/\|$//;
 6771:     return &docondval($allpathcond);
 6772: }
 6773: 
 6774: #evaluates an expression of conditions
 6775: sub docondval {
 6776:     my ($allpathcond) = @_;
 6777:     my $result=0;
 6778:     if ($env{'request.course.id'}
 6779: 	&& defined($allpathcond)) {
 6780: 	my $operand='|';
 6781: 	my @stack;
 6782: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6783: 	    if ($chunk eq '(') {
 6784: 		push @stack,($operand,$result);
 6785: 	    } elsif ($chunk eq ')') {
 6786: 		my $before=pop @stack;
 6787: 		if (pop @stack eq '&') {
 6788: 		    $result=$result>$before?$before:$result;
 6789: 		} else {
 6790: 		    $result=$result>$before?$result:$before;
 6791: 		}
 6792: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6793: 		$operand=$chunk;
 6794: 	    } else {
 6795: 		my $new=directcondval($chunk);
 6796: 		if ($operand eq '&') {
 6797: 		    $result=$result>$new?$new:$result;
 6798: 		} else {
 6799: 		    $result=$result>$new?$result:$new;
 6800: 		}
 6801: 	    }
 6802: 	}
 6803:     }
 6804:     return $result;
 6805: }
 6806: 
 6807: # ---------------------------------------------------- Devalidate courseresdata
 6808: 
 6809: sub devalidatecourseresdata {
 6810:     my ($coursenum,$coursedomain)=@_;
 6811:     my $hashid=$coursenum.':'.$coursedomain;
 6812:     &devalidate_cache_new('courseres',$hashid);
 6813: }
 6814: 
 6815: 
 6816: # --------------------------------------------------- Course Resourcedata Query
 6817: #
 6818: #  Parameters:
 6819: #      $coursenum    - Number of the course.
 6820: #      $coursedomain - Domain at which the course was created.
 6821: #  Returns:
 6822: #     A hash of the course parameters along (I think) with timestamps
 6823: #     and version info.
 6824: 
 6825: sub get_courseresdata {
 6826:     my ($coursenum,$coursedomain)=@_;
 6827:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6828:     my $hashid=$coursenum.':'.$coursedomain;
 6829:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6830:     my %dumpreply;
 6831:     unless (defined($cached)) {
 6832: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6833: 	$result=\%dumpreply;
 6834: 	my ($tmp) = keys(%dumpreply);
 6835: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6836: 	    &do_cache_new('courseres',$hashid,$result,600);
 6837: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6838: 	    return $tmp;
 6839: 	} elsif ($tmp =~ /^(error)/) {
 6840: 	    $result=undef;
 6841: 	    &do_cache_new('courseres',$hashid,$result,600);
 6842: 	}
 6843:     }
 6844:     return $result;
 6845: }
 6846: 
 6847: sub devalidateuserresdata {
 6848:     my ($uname,$udom)=@_;
 6849:     my $hashid="$udom:$uname";
 6850:     &devalidate_cache_new('userres',$hashid);
 6851: }
 6852: 
 6853: sub get_userresdata {
 6854:     my ($uname,$udom)=@_;
 6855:     #most student don\'t have any data set, check if there is some data
 6856:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6857: 
 6858:     my $hashid="$udom:$uname";
 6859:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6860:     if (!defined($cached)) {
 6861: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6862: 	$result=\%resourcedata;
 6863: 	&do_cache_new('userres',$hashid,$result,600);
 6864:     }
 6865:     my ($tmp)=keys(%$result);
 6866:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6867: 	return $result;
 6868:     }
 6869:     #error 2 occurs when the .db doesn't exist
 6870:     if ($tmp!~/error: 2 /) {
 6871: 	&logthis("<font color=\"blue\">WARNING:".
 6872: 		 " Trying to get resource data for ".
 6873: 		 $uname." at ".$udom.": ".
 6874: 		 $tmp."</font>");
 6875:     } elsif ($tmp=~/error: 2 /) {
 6876: 	#&EXT_cache_set($udom,$uname);
 6877: 	&do_cache_new('userres',$hashid,undef,600);
 6878: 	undef($tmp); # not really an error so don't send it back
 6879:     }
 6880:     return $tmp;
 6881: }
 6882: #----------------------------------------------- resdata - return resource data
 6883: #  Purpose:
 6884: #    Return resource data for either users or for a course.
 6885: #  Parameters:
 6886: #     $name      - Course/user name.
 6887: #     $domain    - Name of the domain the user/course is registered on.
 6888: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6889: #     @which     - Array of names of resources desired.
 6890: #  Returns:
 6891: #     The value of the first reasource in @which that is found in the
 6892: #     resource hash.
 6893: #  Exceptional Conditions:
 6894: #     If the $type passed in is not valid (not the string 'course' or 
 6895: #     'user', an undefined  reference is returned.
 6896: #     If none of the resources are found, an undef is returned
 6897: sub resdata {
 6898:     my ($name,$domain,$type,@which)=@_;
 6899:     my $result;
 6900:     if ($type eq 'course') {
 6901: 	$result=&get_courseresdata($name,$domain);
 6902:     } elsif ($type eq 'user') {
 6903: 	$result=&get_userresdata($name,$domain);
 6904:     }
 6905:     if (!ref($result)) { return $result; }    
 6906:     foreach my $item (@which) {
 6907: 	if (defined($result->{$item->[0]})) {
 6908: 	    return [$result->{$item->[0]},$item->[1]];
 6909: 	}
 6910:     }
 6911:     return undef;
 6912: }
 6913: 
 6914: #
 6915: # EXT resource caching routines
 6916: #
 6917: 
 6918: sub clear_EXT_cache_status {
 6919:     &delenv('cache.EXT.');
 6920: }
 6921: 
 6922: sub EXT_cache_status {
 6923:     my ($target_domain,$target_user) = @_;
 6924:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6925:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6926:         # We know already the user has no data
 6927:         return 1;
 6928:     } else {
 6929:         return 0;
 6930:     }
 6931: }
 6932: 
 6933: sub EXT_cache_set {
 6934:     my ($target_domain,$target_user) = @_;
 6935:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6936:     #&appenv({$cachename => time});
 6937: }
 6938: 
 6939: # --------------------------------------------------------- Value of a Variable
 6940: sub EXT {
 6941: 
 6942:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6943:     unless ($varname) { return ''; }
 6944:     #get real user name/domain, courseid and symb
 6945:     my $courseid;
 6946:     my $publicuser;
 6947:     if ($symbparm) {
 6948: 	$symbparm=&get_symb_from_alias($symbparm);
 6949:     }
 6950:     if (!($uname && $udom)) {
 6951:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6952:       if (!$symbparm) {	$symbparm=$cursymb; }
 6953:     } else {
 6954: 	$courseid=$env{'request.course.id'};
 6955:     }
 6956:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6957:     my $rest;
 6958:     if (defined($therest[0])) {
 6959:        $rest=join('.',@therest);
 6960:     } else {
 6961:        $rest='';
 6962:     }
 6963: 
 6964:     my $qualifierrest=$qualifier;
 6965:     if ($rest) { $qualifierrest.='.'.$rest; }
 6966:     my $spacequalifierrest=$space;
 6967:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6968:     if ($realm eq 'user') {
 6969: # --------------------------------------------------------------- user.resource
 6970: 	if ($space eq 'resource') {
 6971: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6972: 		  || defined($Apache::lonhomework::parsing_a_task))
 6973: 		 &&
 6974: 		 ($symbparm eq &symbread()) ) {	
 6975: 		# if we are in the middle of processing the resource the
 6976: 		# get the value we are planning on committing
 6977:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6978:                     return $Apache::lonhomework::results{$qualifierrest};
 6979:                 } else {
 6980:                     return $Apache::lonhomework::history{$qualifierrest};
 6981:                 }
 6982: 	    } else {
 6983: 		my %restored;
 6984: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6985: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6986: 		} else {
 6987: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6988: 		}
 6989: 		return $restored{$qualifierrest};
 6990: 	    }
 6991: # ----------------------------------------------------------------- user.access
 6992:         } elsif ($space eq 'access') {
 6993: 	    # FIXME - not supporting calls for a specific user
 6994:             return &allowed($qualifier,$rest);
 6995: # ------------------------------------------ user.preferences, user.environment
 6996:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6997: 	    if (($uname eq $env{'user.name'}) &&
 6998: 		($udom eq $env{'user.domain'})) {
 6999: 		return $env{join('.',('environment',$qualifierrest))};
 7000: 	    } else {
 7001: 		my %returnhash;
 7002: 		if (!$publicuser) {
 7003: 		    %returnhash=&userenvironment($udom,$uname,
 7004: 						 $qualifierrest);
 7005: 		}
 7006: 		return $returnhash{$qualifierrest};
 7007: 	    }
 7008: # ----------------------------------------------------------------- user.course
 7009:         } elsif ($space eq 'course') {
 7010: 	    # FIXME - not supporting calls for a specific user
 7011:             return $env{join('.',('request.course',$qualifier))};
 7012: # ------------------------------------------------------------------- user.role
 7013:         } elsif ($space eq 'role') {
 7014: 	    # FIXME - not supporting calls for a specific user
 7015:             my ($role,$where)=split(/\./,$env{'request.role'});
 7016:             if ($qualifier eq 'value') {
 7017: 		return $role;
 7018:             } elsif ($qualifier eq 'extent') {
 7019:                 return $where;
 7020:             }
 7021: # ----------------------------------------------------------------- user.domain
 7022:         } elsif ($space eq 'domain') {
 7023:             return $udom;
 7024: # ------------------------------------------------------------------- user.name
 7025:         } elsif ($space eq 'name') {
 7026:             return $uname;
 7027: # ---------------------------------------------------- Any other user namespace
 7028:         } else {
 7029: 	    my %reply;
 7030: 	    if (!$publicuser) {
 7031: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7032: 	    }
 7033: 	    return $reply{$qualifierrest};
 7034:         }
 7035:     } elsif ($realm eq 'query') {
 7036: # ---------------------------------------------- pull stuff out of query string
 7037:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7038: 						[$spacequalifierrest]);
 7039: 	return $env{'form.'.$spacequalifierrest}; 
 7040:    } elsif ($realm eq 'request') {
 7041: # ------------------------------------------------------------- request.browser
 7042:         if ($space eq 'browser') {
 7043: 	    if ($qualifier eq 'textremote') {
 7044: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7045: 		    return 1;
 7046: 		} else {
 7047: 		    return 0;
 7048: 		}
 7049: 	    } else {
 7050: 		return $env{'browser.'.$qualifier};
 7051: 	    }
 7052: # ------------------------------------------------------------ request.filename
 7053:         } else {
 7054:             return $env{'request.'.$spacequalifierrest};
 7055:         }
 7056:     } elsif ($realm eq 'course') {
 7057: # ---------------------------------------------------------- course.description
 7058:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7059:     } elsif ($realm eq 'resource') {
 7060: 
 7061: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7062: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7063: 	}
 7064: 
 7065: 	if ($space eq 'title') {
 7066: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7067: 	    return &gettitle($symbparm);
 7068: 	}
 7069: 	
 7070: 	if ($space eq 'map') {
 7071: 	    my ($map) = &decode_symb($symbparm);
 7072: 	    return &symbread($map);
 7073: 	}
 7074: 	if ($space eq 'filename') {
 7075: 	    if ($symbparm) {
 7076: 		return &clutter((&decode_symb($symbparm))[2]);
 7077: 	    }
 7078: 	    return &hreflocation('',$env{'request.filename'});
 7079: 	}
 7080: 
 7081: 	my ($section, $group, @groups);
 7082: 	my ($courselevelm,$courselevel);
 7083: 	if ($symbparm && defined($courseid) && 
 7084: 	    $courseid eq $env{'request.course.id'}) {
 7085: 
 7086: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7087: 
 7088: # ----------------------------------------------------- Cascading lookup scheme
 7089: 	    my $symbp=$symbparm;
 7090: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7091: 
 7092: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7093: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7094: 
 7095: 	    if (($env{'user.name'} eq $uname) &&
 7096: 		($env{'user.domain'} eq $udom)) {
 7097: 		$section=$env{'request.course.sec'};
 7098:                 @groups = split(/:/,$env{'request.course.groups'});  
 7099:                 @groups=&sort_course_groups($courseid,@groups); 
 7100: 	    } else {
 7101: 		if (! defined($usection)) {
 7102: 		    $section=&getsection($udom,$uname,$courseid);
 7103: 		} else {
 7104: 		    $section = $usection;
 7105: 		}
 7106:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7107: 	    }
 7108: 
 7109: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7110: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7111: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7112: 
 7113: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7114: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7115: 	    $courselevelm=$courseid.'.'.$mapparm;
 7116: 
 7117: # ----------------------------------------------------------- first, check user
 7118: 
 7119: 	    my $userreply=&resdata($uname,$udom,'user',
 7120: 				       ([$courselevelr,'resource'],
 7121: 					[$courselevelm,'map'     ],
 7122: 					[$courselevel, 'course'  ]));
 7123: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7124: 
 7125: # ------------------------------------------------ second, check some of course
 7126:             my $coursereply;
 7127:             if (@groups > 0) {
 7128:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7129:                                        $mapparm,$spacequalifierrest);
 7130:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7131:             }
 7132: 
 7133: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7134: 				  $env{'course.'.$courseid.'.domain'},
 7135: 				  'course',
 7136: 				  ([$seclevelr,   'resource'],
 7137: 				   [$seclevelm,   'map'     ],
 7138: 				   [$seclevel,    'course'  ],
 7139: 				   [$courselevelr,'resource']));
 7140: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7141: 
 7142: # ------------------------------------------------------ third, check map parms
 7143: 	    my %parmhash=();
 7144: 	    my $thisparm='';
 7145: 	    if (tie(%parmhash,'GDBM_File',
 7146: 		    $env{'request.course.fn'}.'_parms.db',
 7147: 		    &GDBM_READER(),0640)) {
 7148: 		$thisparm=$parmhash{$symbparm};
 7149: 		untie(%parmhash);
 7150: 	    }
 7151: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7152: 	}
 7153: # ------------------------------------------ fourth, look in resource metadata
 7154: 
 7155: 	$spacequalifierrest=~s/\./\_/;
 7156: 	my $filename;
 7157: 	if (!$symbparm) { $symbparm=&symbread(); }
 7158: 	if ($symbparm) {
 7159: 	    $filename=(&decode_symb($symbparm))[2];
 7160: 	} else {
 7161: 	    $filename=$env{'request.filename'};
 7162: 	}
 7163: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7164: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7165: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7166: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7167: 
 7168: # ---------------------------------------------- fourth, look in rest of course
 7169: 	if ($symbparm && defined($courseid) && 
 7170: 	    $courseid eq $env{'request.course.id'}) {
 7171: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7172: 				     $env{'course.'.$courseid.'.domain'},
 7173: 				     'course',
 7174: 				     ([$courselevelm,'map'   ],
 7175: 				      [$courselevel, 'course']));
 7176: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7177: 	}
 7178: # ------------------------------------------------------------------ Cascade up
 7179: 	unless ($space eq '0') {
 7180: 	    my @parts=split(/_/,$space);
 7181: 	    my $id=pop(@parts);
 7182: 	    my $part=join('_',@parts);
 7183: 	    if ($part eq '') { $part='0'; }
 7184: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7185: 				 $symbparm,$udom,$uname,$section,1);
 7186: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7187: 	}
 7188: 	if ($recurse) { return undef; }
 7189: 	my $pack_def=&packages_tab_default($filename,$varname);
 7190: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7191: # ---------------------------------------------------- Any other user namespace
 7192:     } elsif ($realm eq 'environment') {
 7193: # ----------------------------------------------------------------- environment
 7194: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7195: 	    return $env{'environment.'.$spacequalifierrest};
 7196: 	} else {
 7197: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7198: 		return '';
 7199: 	    }
 7200: 	    my %returnhash=&userenvironment($udom,$uname,
 7201: 					    $spacequalifierrest);
 7202: 	    return $returnhash{$spacequalifierrest};
 7203: 	}
 7204:     } elsif ($realm eq 'system') {
 7205: # ----------------------------------------------------------------- system.time
 7206: 	if ($space eq 'time') {
 7207: 	    return time;
 7208:         }
 7209:     } elsif ($realm eq 'server') {
 7210: # ----------------------------------------------------------------- system.time
 7211: 	if ($space eq 'name') {
 7212: 	    return $ENV{'SERVER_NAME'};
 7213:         }
 7214:     }
 7215:     return '';
 7216: }
 7217: 
 7218: sub get_reply {
 7219:     my ($reply_value) = @_;
 7220:     if (ref($reply_value) eq 'ARRAY') {
 7221:         if (wantarray) {
 7222: 	    return @$reply_value;
 7223:         }
 7224:         return $reply_value->[0];
 7225:     } else {
 7226:         return $reply_value;
 7227:     }
 7228: }
 7229: 
 7230: sub check_group_parms {
 7231:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7232:     my @groupitems = ();
 7233:     my $resultitem;
 7234:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7235:     foreach my $group (@{$groups}) {
 7236:         foreach my $level (@levels) {
 7237:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7238:              push(@groupitems,[$item,$level->[1]]);
 7239:         }
 7240:     }
 7241:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7242:                             $env{'course.'.$courseid.'.domain'},
 7243:                                      'course',@groupitems);
 7244:     return $coursereply;
 7245: }
 7246: 
 7247: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7248:     my ($courseid,@groups) = @_;
 7249:     @groups = sort(@groups);
 7250:     return @groups;
 7251: }
 7252: 
 7253: sub packages_tab_default {
 7254:     my ($uri,$varname)=@_;
 7255:     my (undef,$part,$name)=split(/\./,$varname);
 7256: 
 7257:     my (@extension,@specifics,$do_default);
 7258:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7259: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7260: 	if ($pack_type eq 'default') {
 7261: 	    $do_default=1;
 7262: 	} elsif ($pack_type eq 'extension') {
 7263: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7264: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7265: 	    # only look at packages defaults for packages that this id is
 7266: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7267: 	}
 7268:     }
 7269:     # first look for a package that matches the requested part id
 7270:     foreach my $package (@specifics) {
 7271: 	my (undef,$pack_type,$pack_part)=@{$package};
 7272: 	next if ($pack_part ne $part);
 7273: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7274: 	    return $packagetab{"$pack_type&$name&default"};
 7275: 	}
 7276:     }
 7277:     # look for any possible matching non extension_ package
 7278:     foreach my $package (@specifics) {
 7279: 	my (undef,$pack_type,$pack_part)=@{$package};
 7280: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7281: 	    return $packagetab{"$pack_type&$name&default"};
 7282: 	}
 7283: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7284: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7285: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7286: 	}
 7287:     }
 7288:     # look for any posible extension_ match
 7289:     foreach my $package (@extension) {
 7290: 	my ($package,$pack_type)=@{$package};
 7291: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7292: 	    return $packagetab{"$pack_type&$name&default"};
 7293: 	}
 7294: 	if (defined($packagetab{$package."&$name&default"})) {
 7295: 	    return $packagetab{$package."&$name&default"};
 7296: 	}
 7297:     }
 7298:     # look for a global default setting
 7299:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7300: 	return $packagetab{"default&$name&default"};
 7301:     }
 7302:     return undef;
 7303: }
 7304: 
 7305: sub add_prefix_and_part {
 7306:     my ($prefix,$part)=@_;
 7307:     my $keyroot;
 7308:     if (defined($prefix) && $prefix !~ /^__/) {
 7309: 	# prefix that has a part already
 7310: 	$keyroot=$prefix;
 7311:     } elsif (defined($prefix)) {
 7312: 	# prefix that is missing a part
 7313: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7314:     } else {
 7315: 	# no prefix at all
 7316: 	if (defined($part)) { $keyroot='_'.$part; }
 7317:     }
 7318:     return $keyroot;
 7319: }
 7320: 
 7321: # ---------------------------------------------------------------- Get metadata
 7322: 
 7323: my %metaentry;
 7324: sub metadata {
 7325:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7326:     $uri=&declutter($uri);
 7327:     # if it is a non metadata possible uri return quickly
 7328:     if (($uri eq '') || 
 7329: 	(($uri =~ m|^/*adm/|) && 
 7330: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7331:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7332: 	return undef;
 7333:     }
 7334:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7335: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7336: 	return undef;
 7337:     }
 7338:     my $filename=$uri;
 7339:     $uri=~s/\.meta$//;
 7340: #
 7341: # Is the metadata already cached?
 7342: # Look at timestamp of caching
 7343: # Everything is cached by the main uri, libraries are never directly cached
 7344: #
 7345:     if (!defined($liburi)) {
 7346: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7347: 	if (defined($cached)) { return $result->{':'.$what}; }
 7348:     }
 7349:     {
 7350: #
 7351: # Is this a recursive call for a library?
 7352: #
 7353: #	if (! exists($metacache{$uri})) {
 7354: #	    $metacache{$uri}={};
 7355: #	}
 7356: 	my $cachetime = 60*60;
 7357:         if ($liburi) {
 7358: 	    $liburi=&declutter($liburi);
 7359:             $filename=$liburi;
 7360:         } else {
 7361: 	    &devalidate_cache_new('meta',$uri);
 7362: 	    undef(%metaentry);
 7363: 	}
 7364:         my %metathesekeys=();
 7365:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7366: 	my $metastring;
 7367: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7368: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7369: 	    $metastring = 
 7370: 		&Apache::lonnet::ssi_body($which,
 7371: 					  ('grade_target' => 'meta'));
 7372: 	    $cachetime = 1; # only want this cached in the child not long term
 7373: 	} elsif ($uri !~ m -^(editupload)/-) {
 7374: 	    my $file=&filelocation('',&clutter($filename));
 7375: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7376: 	    $metastring=&getfile($file);
 7377: 	}
 7378:         my $parser=HTML::LCParser->new(\$metastring);
 7379:         my $token;
 7380:         undef %metathesekeys;
 7381:         while ($token=$parser->get_token) {
 7382: 	    if ($token->[0] eq 'S') {
 7383: 		if (defined($token->[2]->{'package'})) {
 7384: #
 7385: # This is a package - get package info
 7386: #
 7387: 		    my $package=$token->[2]->{'package'};
 7388: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7389: 		    if (defined($token->[2]->{'id'})) { 
 7390: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7391: 		    }
 7392: 		    if ($metaentry{':packages'}) {
 7393: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7394: 		    } else {
 7395: 			$metaentry{':packages'}=$package.$keyroot;
 7396: 		    }
 7397: 		    foreach my $pack_entry (keys(%packagetab)) {
 7398: 			my $part=$keyroot;
 7399: 			$part=~s/^\_//;
 7400: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7401: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7402: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7403: 			    # ignore package.tab specified default values
 7404:                             # here &package_tab_default() will fetch those
 7405: 			    if ($subp eq 'default') { next; }
 7406: 			    my $value=$packagetab{$pack_entry};
 7407: 			    my $unikey;
 7408: 			    if ($pack =~ /_0$/) {
 7409: 				$unikey='parameter_0_'.$name;
 7410: 				$part=0;
 7411: 			    } else {
 7412: 				$unikey='parameter'.$keyroot.'_'.$name;
 7413: 			    }
 7414: 			    if ($subp eq 'display') {
 7415: 				$value.=' [Part: '.$part.']';
 7416: 			    }
 7417: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7418: 			    $metathesekeys{$unikey}=1;
 7419: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7420: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7421: 			    }
 7422: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7423: 				$metaentry{':'.$unikey}=
 7424: 				    $metaentry{':'.$unikey.'.default'};
 7425: 			    }
 7426: 			}
 7427: 		    }
 7428: 		} else {
 7429: #
 7430: # This is not a package - some other kind of start tag
 7431: #
 7432: 		    my $entry=$token->[1];
 7433: 		    my $unikey;
 7434: 		    if ($entry eq 'import') {
 7435: 			$unikey='';
 7436: 		    } else {
 7437: 			$unikey=$entry;
 7438: 		    }
 7439: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7440: 
 7441: 		    if (defined($token->[2]->{'id'})) { 
 7442: 			$unikey.='_'.$token->[2]->{'id'}; 
 7443: 		    }
 7444: 
 7445: 		    if ($entry eq 'import') {
 7446: #
 7447: # Importing a library here
 7448: #
 7449: 			if ($depthcount<20) {
 7450: 			    my $location=$parser->get_text('/import');
 7451: 			    my $dir=$filename;
 7452: 			    $dir=~s|[^/]*$||;
 7453: 			    $location=&filelocation($dir,$location);
 7454: 			    my $metadata = 
 7455: 				&metadata($uri,'keys', $location,$unikey,
 7456: 					  $depthcount+1);
 7457: 			    foreach my $meta (split(',',$metadata)) {
 7458: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7459: 				$metathesekeys{$meta}=1;
 7460: 			    }
 7461: 			}
 7462: 		    } else { 
 7463: 			
 7464: 			if (defined($token->[2]->{'name'})) { 
 7465: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7466: 			}
 7467: 			$metathesekeys{$unikey}=1;
 7468: 			foreach my $param (@{$token->[3]}) {
 7469: 			    $metaentry{':'.$unikey.'.'.$param} =
 7470: 				$token->[2]->{$param};
 7471: 			}
 7472: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7473: 			my $default=$metaentry{':'.$unikey.'.default'};
 7474: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7475: 		 # only ws inside the tag, and not in default, so use default
 7476: 		 # as value
 7477: 			    $metaentry{':'.$unikey}=$default;
 7478: 			} elsif ( $internaltext =~ /\S/ ) {
 7479: 		  # something interesting inside the tag
 7480: 			    $metaentry{':'.$unikey}=$internaltext;
 7481: 			} else {
 7482: 		  # no interesting values, don't set a default
 7483: 			}
 7484: # end of not-a-package not-a-library import
 7485: 		    }
 7486: # end of not-a-package start tag
 7487: 		}
 7488: # the next is the end of "start tag"
 7489: 	    }
 7490: 	}
 7491: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7492: 	$extension = lc($extension);
 7493: 	if ($extension eq 'htm') { $extension='html'; }
 7494: 
 7495: 	foreach my $key (keys(%packagetab)) {
 7496: 	    #no specific packages #how's our extension
 7497: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7498: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7499: 					 \%metathesekeys);
 7500: 	}
 7501: 
 7502: 	if (!exists($metaentry{':packages'})
 7503: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7504: 	    foreach my $key (keys(%packagetab)) {
 7505: 		#no specific packages well let's get default then
 7506: 		if ($key!~/^default&/) { next; }
 7507: 		&metadata_create_package_def($uri,$key,'default',
 7508: 					     \%metathesekeys);
 7509: 	    }
 7510: 	}
 7511: # are there custom rights to evaluate
 7512: 	if ($metaentry{':copyright'} eq 'custom') {
 7513: 
 7514:     #
 7515:     # Importing a rights file here
 7516:     #
 7517: 	    unless ($depthcount) {
 7518: 		my $location=$metaentry{':customdistributionfile'};
 7519: 		my $dir=$filename;
 7520: 		$dir=~s|[^/]*$||;
 7521: 		$location=&filelocation($dir,$location);
 7522: 		my $rights_metadata =
 7523: 		    &metadata($uri,'keys',$location,'_rights',
 7524: 			      $depthcount+1);
 7525: 		foreach my $rights (split(',',$rights_metadata)) {
 7526: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7527: 		    $metathesekeys{$rights}=1;
 7528: 		}
 7529: 	    }
 7530: 	}
 7531: 	# uniqifiy package listing
 7532: 	my %seen;
 7533: 	my @uniq_packages =
 7534: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7535: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7536: 
 7537: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7538: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7539: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7540: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7541: # this is the end of "was not already recently cached
 7542:     }
 7543:     return $metaentry{':'.$what};
 7544: }
 7545: 
 7546: sub metadata_create_package_def {
 7547:     my ($uri,$key,$package,$metathesekeys)=@_;
 7548:     my ($pack,$name,$subp)=split(/\&/,$key);
 7549:     if ($subp eq 'default') { next; }
 7550:     
 7551:     if (defined($metaentry{':packages'})) {
 7552: 	$metaentry{':packages'}.=','.$package;
 7553:     } else {
 7554: 	$metaentry{':packages'}=$package;
 7555:     }
 7556:     my $value=$packagetab{$key};
 7557:     my $unikey;
 7558:     $unikey='parameter_0_'.$name;
 7559:     $metaentry{':'.$unikey.'.part'}=0;
 7560:     $$metathesekeys{$unikey}=1;
 7561:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7562: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7563:     }
 7564:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7565: 	$metaentry{':'.$unikey}=
 7566: 	    $metaentry{':'.$unikey.'.default'};
 7567:     }
 7568: }
 7569: 
 7570: sub metadata_generate_part0 {
 7571:     my ($metadata,$metacache,$uri) = @_;
 7572:     my %allnames;
 7573:     foreach my $metakey (keys(%$metadata)) {
 7574: 	if ($metakey=~/^parameter\_(.*)/) {
 7575: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7576: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7577: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7578: 	    $allnames{$name}=$part;
 7579: 	  }
 7580: 	}
 7581:     }
 7582:     foreach my $name (keys(%allnames)) {
 7583:       $$metadata{"parameter_0_$name"}=1;
 7584:       my $key=":parameter_0_$name";
 7585:       $$metacache{"$key.part"}='0';
 7586:       $$metacache{"$key.name"}=$name;
 7587:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7588: 					   $allnames{$name}.'_'.$name.
 7589: 					   '.type'};
 7590:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7591: 			     '.display'};
 7592:       my $expr='[Part: '.$allnames{$name}.']';
 7593:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7594:       $$metacache{"$key.display"}=$olddis;
 7595:     }
 7596: }
 7597: 
 7598: # ------------------------------------------------------ Devalidate title cache
 7599: 
 7600: sub devalidate_title_cache {
 7601:     my ($url)=@_;
 7602:     if (!$env{'request.course.id'}) { return; }
 7603:     my $symb=&symbread($url);
 7604:     if (!$symb) { return; }
 7605:     my $key=$env{'request.course.id'}."\0".$symb;
 7606:     &devalidate_cache_new('title',$key);
 7607: }
 7608: 
 7609: # ------------------------------------------------- Get the title of a resource
 7610: 
 7611: sub gettitle {
 7612:     my $urlsymb=shift;
 7613:     my $symb=&symbread($urlsymb);
 7614:     if ($symb) {
 7615: 	my $key=$env{'request.course.id'}."\0".$symb;
 7616: 	my ($result,$cached)=&is_cached_new('title',$key);
 7617: 	if (defined($cached)) { 
 7618: 	    return $result;
 7619: 	}
 7620: 	my ($map,$resid,$url)=&decode_symb($symb);
 7621: 	my $title='';
 7622: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7623: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7624: 	} else {
 7625: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7626: 		    &GDBM_READER(),0640)) {
 7627: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7628: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7629: 		untie(%bighash);
 7630: 	    }
 7631: 	}
 7632: 	$title=~s/\&colon\;/\:/gs;
 7633: 	if ($title) {
 7634: 	    return &do_cache_new('title',$key,$title,600);
 7635: 	}
 7636: 	$urlsymb=$url;
 7637:     }
 7638:     my $title=&metadata($urlsymb,'title');
 7639:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7640:     return $title;
 7641: }
 7642: 
 7643: sub get_slot {
 7644:     my ($which,$cnum,$cdom)=@_;
 7645:     if (!$cnum || !$cdom) {
 7646: 	(undef,my $courseid)=&whichuser();
 7647: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7648: 	$cnum=$env{'course.'.$courseid.'.num'};
 7649:     }
 7650:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7651:     my %slotinfo;
 7652:     if (exists($remembered{$key})) {
 7653: 	$slotinfo{$which} = $remembered{$key};
 7654:     } else {
 7655: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7656: 	&Apache::lonhomework::showhash(%slotinfo);
 7657: 	my ($tmp)=keys(%slotinfo);
 7658: 	if ($tmp=~/^error:/) { return (); }
 7659: 	$remembered{$key} = $slotinfo{$which};
 7660:     }
 7661:     if (ref($slotinfo{$which}) eq 'HASH') {
 7662: 	return %{$slotinfo{$which}};
 7663:     }
 7664:     return $slotinfo{$which};
 7665: }
 7666: # ------------------------------------------------- Update symbolic store links
 7667: 
 7668: sub symblist {
 7669:     my ($mapname,%newhash)=@_;
 7670:     $mapname=&deversion(&declutter($mapname));
 7671:     my %hash;
 7672:     if (($env{'request.course.fn'}) && (%newhash)) {
 7673:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7674:                       &GDBM_WRCREAT(),0640)) {
 7675: 	    foreach my $url (keys %newhash) {
 7676: 		next if ($url eq 'last_known'
 7677: 			 && $env{'form.no_update_last_known'});
 7678: 		$hash{declutter($url)}=&encode_symb($mapname,
 7679: 						    $newhash{$url}->[1],
 7680: 						    $newhash{$url}->[0]);
 7681:             }
 7682:             if (untie(%hash)) {
 7683: 		return 'ok';
 7684:             }
 7685:         }
 7686:     }
 7687:     return 'error';
 7688: }
 7689: 
 7690: # --------------------------------------------------------------- Verify a symb
 7691: 
 7692: sub symbverify {
 7693:     my ($symb,$thisurl)=@_;
 7694:     my $thisfn=$thisurl;
 7695:     $thisfn=&declutter($thisfn);
 7696: # direct jump to resource in page or to a sequence - will construct own symbs
 7697:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7698: # check URL part
 7699:     my ($map,$resid,$url)=&decode_symb($symb);
 7700: 
 7701:     unless ($url eq $thisfn) { return 0; }
 7702: 
 7703:     $symb=&symbclean($symb);
 7704:     $thisurl=&deversion($thisurl);
 7705:     $thisfn=&deversion($thisfn);
 7706: 
 7707:     my %bighash;
 7708:     my $okay=0;
 7709: 
 7710:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7711:                             &GDBM_READER(),0640)) {
 7712:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7713:         unless ($ids) { 
 7714:            $ids=$bighash{'ids_/'.$thisurl};
 7715:         }
 7716:         if ($ids) {
 7717: # ------------------------------------------------------------------- Has ID(s)
 7718: 	    foreach my $id (split(/\,/,$ids)) {
 7719: 	       my ($mapid,$resid)=split(/\./,$id);
 7720:                if (
 7721:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7722:    eq $symb) { 
 7723: 		   if (($env{'request.role.adv'}) ||
 7724: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7725: 		       $okay=1; 
 7726: 		   }
 7727: 	       }
 7728: 	   }
 7729:         }
 7730: 	untie(%bighash);
 7731:     }
 7732:     return $okay;
 7733: }
 7734: 
 7735: # --------------------------------------------------------------- Clean-up symb
 7736: 
 7737: sub symbclean {
 7738:     my $symb=shift;
 7739:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7740: # remove version from map
 7741:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7742: 
 7743: # remove version from URL
 7744:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7745: 
 7746: # remove wrapper
 7747: 
 7748:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7749:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7750:     return $symb;
 7751: }
 7752: 
 7753: # ---------------------------------------------- Split symb to find map and url
 7754: 
 7755: sub encode_symb {
 7756:     my ($map,$resid,$url)=@_;
 7757:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7758: }
 7759: 
 7760: sub decode_symb {
 7761:     my $symb=shift;
 7762:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7763:     my ($map,$resid,$url)=split(/___/,$symb);
 7764:     return (&fixversion($map),$resid,&fixversion($url));
 7765: }
 7766: 
 7767: sub fixversion {
 7768:     my $fn=shift;
 7769:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7770:     my %bighash;
 7771:     my $uri=&clutter($fn);
 7772:     my $key=$env{'request.course.id'}.'_'.$uri;
 7773: # is this cached?
 7774:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7775:     if (defined($cached)) { return $result; }
 7776: # unfortunately not cached, or expired
 7777:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7778: 	    &GDBM_READER(),0640)) {
 7779:  	if ($bighash{'version_'.$uri}) {
 7780:  	    my $version=$bighash{'version_'.$uri};
 7781:  	    unless (($version eq 'mostrecent') || 
 7782: 		    ($version==&getversion($uri))) {
 7783:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7784:  	    }
 7785:  	}
 7786:  	untie %bighash;
 7787:     }
 7788:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7789: }
 7790: 
 7791: sub deversion {
 7792:     my $url=shift;
 7793:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7794:     return $url;
 7795: }
 7796: 
 7797: # ------------------------------------------------------ Return symb list entry
 7798: 
 7799: sub symbread {
 7800:     my ($thisfn,$donotrecurse)=@_;
 7801:     my $cache_str='request.symbread.cached.'.$thisfn;
 7802:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7803: # no filename provided? try from environment
 7804:     unless ($thisfn) {
 7805:         if ($env{'request.symb'}) {
 7806: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7807: 	}
 7808: 	$thisfn=$env{'request.filename'};
 7809:     }
 7810:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7811: # is that filename actually a symb? Verify, clean, and return
 7812:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7813: 	if (&symbverify($thisfn,$1)) {
 7814: 	    return $env{$cache_str}=&symbclean($thisfn);
 7815: 	}
 7816:     }
 7817:     $thisfn=declutter($thisfn);
 7818:     my %hash;
 7819:     my %bighash;
 7820:     my $syval='';
 7821:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7822:         my $targetfn = $thisfn;
 7823:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7824:             $targetfn = 'adm/wrapper/'.$thisfn;
 7825:         }
 7826: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7827: 	    $targetfn=$1;
 7828: 	}
 7829:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7830:                       &GDBM_READER(),0640)) {
 7831: 	    $syval=$hash{$targetfn};
 7832:             untie(%hash);
 7833:         }
 7834: # ---------------------------------------------------------- There was an entry
 7835:         if ($syval) {
 7836: 	    #unless ($syval=~/\_\d+$/) {
 7837: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7838: 		    #&appenv({'request.ambiguous' => $thisfn});
 7839: 		    #return $env{$cache_str}='';
 7840: 		#}    
 7841: 		#$syval.=$1;
 7842: 	    #}
 7843:         } else {
 7844: # ------------------------------------------------------- Was not in symb table
 7845:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7846:                             &GDBM_READER(),0640)) {
 7847: # ---------------------------------------------- Get ID(s) for current resource
 7848:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7849:               unless ($ids) { 
 7850:                  $ids=$bighash{'ids_/'.$thisfn};
 7851:               }
 7852:               unless ($ids) {
 7853: # alias?
 7854: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7855:               }
 7856:               if ($ids) {
 7857: # ------------------------------------------------------------------- Has ID(s)
 7858:                  my @possibilities=split(/\,/,$ids);
 7859:                  if ($#possibilities==0) {
 7860: # ----------------------------------------------- There is only one possibility
 7861: 		     my ($mapid,$resid)=split(/\./,$ids);
 7862: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7863: 						    $resid,$thisfn);
 7864:                  } elsif (!$donotrecurse) {
 7865: # ------------------------------------------ There is more than one possibility
 7866:                      my $realpossible=0;
 7867:                      foreach my $id (@possibilities) {
 7868: 			 my $file=$bighash{'src_'.$id};
 7869:                          if (&allowed('bre',$file)) {
 7870:          		    my ($mapid,$resid)=split(/\./,$id);
 7871:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7872: 				$realpossible++;
 7873:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7874: 						    $resid,$thisfn);
 7875:                             }
 7876: 			 }
 7877:                      }
 7878: 		     if ($realpossible!=1) { $syval=''; }
 7879:                  } else {
 7880:                      $syval='';
 7881:                  }
 7882: 	      }
 7883:               untie(%bighash)
 7884:            }
 7885:         }
 7886:         if ($syval) {
 7887: 	    return $env{$cache_str}=$syval;
 7888:         }
 7889:     }
 7890:     &appenv({'request.ambiguous' => $thisfn});
 7891:     return $env{$cache_str}='';
 7892: }
 7893: 
 7894: # ---------------------------------------------------------- Return random seed
 7895: 
 7896: sub numval {
 7897:     my $txt=shift;
 7898:     $txt=~tr/A-J/0-9/;
 7899:     $txt=~tr/a-j/0-9/;
 7900:     $txt=~tr/K-T/0-9/;
 7901:     $txt=~tr/k-t/0-9/;
 7902:     $txt=~tr/U-Z/0-5/;
 7903:     $txt=~tr/u-z/0-5/;
 7904:     $txt=~s/\D//g;
 7905:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7906:     return int($txt);
 7907: }
 7908: 
 7909: sub numval2 {
 7910:     my $txt=shift;
 7911:     $txt=~tr/A-J/0-9/;
 7912:     $txt=~tr/a-j/0-9/;
 7913:     $txt=~tr/K-T/0-9/;
 7914:     $txt=~tr/k-t/0-9/;
 7915:     $txt=~tr/U-Z/0-5/;
 7916:     $txt=~tr/u-z/0-5/;
 7917:     $txt=~s/\D//g;
 7918:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7919:     my $total;
 7920:     foreach my $val (@txts) { $total+=$val; }
 7921:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7922:     return int($total);
 7923: }
 7924: 
 7925: sub numval3 {
 7926:     use integer;
 7927:     my $txt=shift;
 7928:     $txt=~tr/A-J/0-9/;
 7929:     $txt=~tr/a-j/0-9/;
 7930:     $txt=~tr/K-T/0-9/;
 7931:     $txt=~tr/k-t/0-9/;
 7932:     $txt=~tr/U-Z/0-5/;
 7933:     $txt=~tr/u-z/0-5/;
 7934:     $txt=~s/\D//g;
 7935:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7936:     my $total;
 7937:     foreach my $val (@txts) { $total+=$val; }
 7938:     if ($_64bit) { $total=(($total<<32)>>32); }
 7939:     return $total;
 7940: }
 7941: 
 7942: sub digest {
 7943:     my ($data)=@_;
 7944:     my $digest=&Digest::MD5::md5($data);
 7945:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7946:     my ($e,$f);
 7947:     {
 7948:         use integer;
 7949:         $e=($a+$b);
 7950:         $f=($c+$d);
 7951:         if ($_64bit) {
 7952:             $e=(($e<<32)>>32);
 7953:             $f=(($f<<32)>>32);
 7954:         }
 7955:     }
 7956:     if (wantarray) {
 7957: 	return ($e,$f);
 7958:     } else {
 7959: 	my $g;
 7960: 	{
 7961: 	    use integer;
 7962: 	    $g=($e+$f);
 7963: 	    if ($_64bit) {
 7964: 		$g=(($g<<32)>>32);
 7965: 	    }
 7966: 	}
 7967: 	return $g;
 7968:     }
 7969: }
 7970: 
 7971: sub latest_rnd_algorithm_id {
 7972:     return '64bit5';
 7973: }
 7974: 
 7975: sub get_rand_alg {
 7976:     my ($courseid)=@_;
 7977:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7978:     if ($courseid) {
 7979: 	return $env{"course.$courseid.rndseed"};
 7980:     }
 7981:     return &latest_rnd_algorithm_id();
 7982: }
 7983: 
 7984: sub validCODE {
 7985:     my ($CODE)=@_;
 7986:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7987:     return 0;
 7988: }
 7989: 
 7990: sub getCODE {
 7991:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7992:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7993: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7994: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7995: 	return $Apache::lonhomework::history{'resource.CODE'};
 7996:     }
 7997:     return undef;
 7998: }
 7999: 
 8000: sub rndseed {
 8001:     my ($symb,$courseid,$domain,$username)=@_;
 8002:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8003:     if (!defined($symb)) {
 8004: 	unless ($symb=$wsymb) { return time; }
 8005:     }
 8006:     if (!$courseid) { $courseid=$wcourseid; }
 8007:     if (!$domain) { $domain=$wdomain; }
 8008:     if (!$username) { $username=$wusername }
 8009:     my $which=&get_rand_alg();
 8010: 
 8011:     if (defined(&getCODE())) {
 8012: 	if ($which eq '64bit5') {
 8013: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8014: 	} elsif ($which eq '64bit4') {
 8015: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8016: 	} else {
 8017: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8018: 	}
 8019:     } elsif ($which eq '64bit5') {
 8020: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8021:     } elsif ($which eq '64bit4') {
 8022: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8023:     } elsif ($which eq '64bit3') {
 8024: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8025:     } elsif ($which eq '64bit2') {
 8026: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8027:     } elsif ($which eq '64bit') {
 8028: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8029:     }
 8030:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8031: }
 8032: 
 8033: sub rndseed_32bit {
 8034:     my ($symb,$courseid,$domain,$username)=@_;
 8035:     {
 8036: 	use integer;
 8037: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8038: 	my $symbseed=numval($symb) << 22;
 8039: 	my $namechck=unpack("%32C*",$username) << 17;
 8040: 	my $nameseed=numval($username) << 12;
 8041: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8042: 	my $courseseed=unpack("%32C*",$courseid);
 8043: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8044: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8045: 	#&logthis("rndseed :$num:$symb");
 8046: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8047: 	return $num;
 8048:     }
 8049: }
 8050: 
 8051: sub rndseed_64bit {
 8052:     my ($symb,$courseid,$domain,$username)=@_;
 8053:     {
 8054: 	use integer;
 8055: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8056: 	my $symbseed=numval($symb) << 10;
 8057: 	my $namechck=unpack("%32S*",$username);
 8058: 	
 8059: 	my $nameseed=numval($username) << 21;
 8060: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8061: 	my $courseseed=unpack("%32S*",$courseid);
 8062: 	
 8063: 	my $num1=$symbchck+$symbseed+$namechck;
 8064: 	my $num2=$nameseed+$domainseed+$courseseed;
 8065: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8066: 	#&logthis("rndseed :$num:$symb");
 8067: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8068: 	return "$num1,$num2";
 8069:     }
 8070: }
 8071: 
 8072: sub rndseed_64bit2 {
 8073:     my ($symb,$courseid,$domain,$username)=@_;
 8074:     {
 8075: 	use integer;
 8076: 	# strings need to be an even # of cahracters long, it it is odd the
 8077:         # last characters gets thrown away
 8078: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8079: 	my $symbseed=numval($symb) << 10;
 8080: 	my $namechck=unpack("%32S*",$username.' ');
 8081: 	
 8082: 	my $nameseed=numval($username) << 21;
 8083: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8084: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8085: 	
 8086: 	my $num1=$symbchck+$symbseed+$namechck;
 8087: 	my $num2=$nameseed+$domainseed+$courseseed;
 8088: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8089: 	#&logthis("rndseed :$num:$symb");
 8090: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8091: 	return "$num1,$num2";
 8092:     }
 8093: }
 8094: 
 8095: sub rndseed_64bit3 {
 8096:     my ($symb,$courseid,$domain,$username)=@_;
 8097:     {
 8098: 	use integer;
 8099: 	# strings need to be an even # of cahracters long, it it is odd the
 8100:         # last characters gets thrown away
 8101: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8102: 	my $symbseed=numval2($symb) << 10;
 8103: 	my $namechck=unpack("%32S*",$username.' ');
 8104: 	
 8105: 	my $nameseed=numval2($username) << 21;
 8106: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8107: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8108: 	
 8109: 	my $num1=$symbchck+$symbseed+$namechck;
 8110: 	my $num2=$nameseed+$domainseed+$courseseed;
 8111: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8112: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8113: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8114: 	
 8115: 	return "$num1:$num2";
 8116:     }
 8117: }
 8118: 
 8119: sub rndseed_64bit4 {
 8120:     my ($symb,$courseid,$domain,$username)=@_;
 8121:     {
 8122: 	use integer;
 8123: 	# strings need to be an even # of cahracters long, it it is odd the
 8124:         # last characters gets thrown away
 8125: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8126: 	my $symbseed=numval3($symb) << 10;
 8127: 	my $namechck=unpack("%32S*",$username.' ');
 8128: 	
 8129: 	my $nameseed=numval3($username) << 21;
 8130: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8131: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8132: 	
 8133: 	my $num1=$symbchck+$symbseed+$namechck;
 8134: 	my $num2=$nameseed+$domainseed+$courseseed;
 8135: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8136: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8137: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8138: 	
 8139: 	return "$num1:$num2";
 8140:     }
 8141: }
 8142: 
 8143: sub rndseed_64bit5 {
 8144:     my ($symb,$courseid,$domain,$username)=@_;
 8145:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8146:     return "$num1:$num2";
 8147: }
 8148: 
 8149: sub rndseed_CODE_64bit {
 8150:     my ($symb,$courseid,$domain,$username)=@_;
 8151:     {
 8152: 	use integer;
 8153: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8154: 	my $symbseed=numval2($symb);
 8155: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8156: 	my $CODEseed=numval(&getCODE());
 8157: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8158: 	my $num1=$symbseed+$CODEchck;
 8159: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8160: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8161: 	#&logthis("rndseed :$num1:$num2:$symb");
 8162: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8163: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8164: 	return "$num1:$num2";
 8165:     }
 8166: }
 8167: 
 8168: sub rndseed_CODE_64bit4 {
 8169:     my ($symb,$courseid,$domain,$username)=@_;
 8170:     {
 8171: 	use integer;
 8172: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8173: 	my $symbseed=numval3($symb);
 8174: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8175: 	my $CODEseed=numval3(&getCODE());
 8176: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8177: 	my $num1=$symbseed+$CODEchck;
 8178: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8179: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8180: 	#&logthis("rndseed :$num1:$num2:$symb");
 8181: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8182: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8183: 	return "$num1:$num2";
 8184:     }
 8185: }
 8186: 
 8187: sub rndseed_CODE_64bit5 {
 8188:     my ($symb,$courseid,$domain,$username)=@_;
 8189:     my $code = &getCODE();
 8190:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8191:     return "$num1:$num2";
 8192: }
 8193: 
 8194: sub setup_random_from_rndseed {
 8195:     my ($rndseed)=@_;
 8196:     if ($rndseed =~/([,:])/) {
 8197: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8198: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8199:     } else {
 8200: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8201:     }
 8202: }
 8203: 
 8204: sub latest_receipt_algorithm_id {
 8205:     return 'receipt3';
 8206: }
 8207: 
 8208: sub recunique {
 8209:     my $fucourseid=shift;
 8210:     my $unique;
 8211:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8212: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8213: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8214:     } else {
 8215: 	$unique=$perlvar{'lonReceipt'};
 8216:     }
 8217:     return unpack("%32C*",$unique);
 8218: }
 8219: 
 8220: sub recprefix {
 8221:     my $fucourseid=shift;
 8222:     my $prefix;
 8223:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8224: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8225: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8226:     } else {
 8227: 	$prefix=$perlvar{'lonHostID'};
 8228:     }
 8229:     return unpack("%32C*",$prefix);
 8230: }
 8231: 
 8232: sub ireceipt {
 8233:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8234: 
 8235:     my $return =&recprefix($fucourseid).'-';
 8236: 
 8237:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8238: 	$env{'request.state'} eq 'construct') {
 8239: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8240: 	return $return;
 8241:     }
 8242: 
 8243:     my $cuname=unpack("%32C*",$funame);
 8244:     my $cudom=unpack("%32C*",$fudom);
 8245:     my $cucourseid=unpack("%32C*",$fucourseid);
 8246:     my $cusymb=unpack("%32C*",$fusymb);
 8247:     my $cunique=&recunique($fucourseid);
 8248:     my $cpart=unpack("%32S*",$part);
 8249:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8250: 
 8251: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8252: 			       
 8253: 	$return.= ($cunique%$cuname+
 8254: 		   $cunique%$cudom+
 8255: 		   $cusymb%$cuname+
 8256: 		   $cusymb%$cudom+
 8257: 		   $cucourseid%$cuname+
 8258: 		   $cucourseid%$cudom+
 8259: 		   $cpart%$cuname+
 8260: 		   $cpart%$cudom);
 8261:     } else {
 8262: 	$return.= ($cunique%$cuname+
 8263: 		   $cunique%$cudom+
 8264: 		   $cusymb%$cuname+
 8265: 		   $cusymb%$cudom+
 8266: 		   $cucourseid%$cuname+
 8267: 		   $cucourseid%$cudom);
 8268:     }
 8269:     return $return;
 8270: }
 8271: 
 8272: sub receipt {
 8273:     my ($part)=@_;
 8274:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8275:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8276: }
 8277: 
 8278: sub whichuser {
 8279:     my ($passedsymb)=@_;
 8280:     my ($symb,$courseid,$domain,$name,$publicuser);
 8281:     if (defined($env{'form.grade_symb'})) {
 8282: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8283: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8284: 	if (!$allowed &&
 8285: 	    exists($env{'request.course.sec'}) &&
 8286: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8287: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8288: 			      '/'.$env{'request.course.sec'});
 8289: 	}
 8290: 	if ($allowed) {
 8291: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8292: 	    $courseid=$tmp_courseid;
 8293: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8294: 	    ($name)=&get_env_multiple('form.grade_username');
 8295: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8296: 	}
 8297:     }
 8298:     if (!$passedsymb) {
 8299: 	$symb=&symbread();
 8300:     } else {
 8301: 	$symb=$passedsymb;
 8302:     }
 8303:     $courseid=$env{'request.course.id'};
 8304:     $domain=$env{'user.domain'};
 8305:     $name=$env{'user.name'};
 8306:     if ($name eq 'public' && $domain eq 'public') {
 8307: 	if (!defined($env{'form.username'})) {
 8308: 	    $env{'form.username'}.=time.rand(10000000);
 8309: 	}
 8310: 	$name.=$env{'form.username'};
 8311:     }
 8312:     return ($symb,$courseid,$domain,$name,$publicuser);
 8313: 
 8314: }
 8315: 
 8316: # ------------------------------------------------------------ Serves up a file
 8317: # returns either the contents of the file or 
 8318: # -1 if the file doesn't exist
 8319: #
 8320: # if the target is a file that was uploaded via DOCS, 
 8321: # a check will be made to see if a current copy exists on the local server,
 8322: # if it does this will be served, otherwise a copy will be retrieved from
 8323: # the home server for the course and stored in /home/httpd/html/userfiles on
 8324: # the local server.   
 8325: 
 8326: sub getfile {
 8327:     my ($file) = @_;
 8328:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8329:     &repcopy($file);
 8330:     return &readfile($file);
 8331: }
 8332: 
 8333: sub repcopy_userfile {
 8334:     my ($file)=@_;
 8335:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8336:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8337:     my ($cdom,$cnum,$filename) = 
 8338: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8339:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8340:     if (-e "$file") {
 8341: # we already have a local copy, check it out
 8342: 	my @fileinfo = stat($file);
 8343: 	my $rtncode;
 8344: 	my $info;
 8345: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8346: 	if ($lwpresp ne 'ok') {
 8347: # there is no such file anymore, even though we had a local copy
 8348: 	    if ($rtncode eq '404') {
 8349: 		unlink($file);
 8350: 	    }
 8351: 	    return -1;
 8352: 	}
 8353: 	if ($info < $fileinfo[9]) {
 8354: # nice, the file we have is up-to-date, just say okay
 8355: 	    return 'ok';
 8356: 	} else {
 8357: # the file is outdated, get rid of it
 8358: 	    unlink($file);
 8359: 	}
 8360:     }
 8361: # one way or the other, at this point, we don't have the file
 8362: # construct the correct path for the file
 8363:     my @parts = ($cdom,$cnum); 
 8364:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8365: 	push @parts, split(/\//,$1);
 8366:     }
 8367:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8368:     foreach my $part (@parts) {
 8369: 	$path .= '/'.$part;
 8370: 	if (!-e $path) {
 8371: 	    mkdir($path,0770);
 8372: 	}
 8373:     }
 8374: # now the path exists for sure
 8375: # get a user agent
 8376:     my $ua=new LWP::UserAgent;
 8377:     my $transferfile=$file.'.in.transfer';
 8378: # FIXME: this should flock
 8379:     if (-e $transferfile) { return 'ok'; }
 8380:     my $request;
 8381:     $uri=~s/^\///;
 8382:     my $homeserver = &homeserver($cnum,$cdom);
 8383:     my $protocol = $protocol{$homeserver};
 8384:     $protocol = 'http' if ($protocol ne 'https');
 8385:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8386:     my $response=$ua->request($request,$transferfile);
 8387: # did it work?
 8388:     if ($response->is_error()) {
 8389: 	unlink($transferfile);
 8390: 	&logthis("Userfile repcopy failed for $uri");
 8391: 	return -1;
 8392:     }
 8393: # worked, rename the transfer file
 8394:     rename($transferfile,$file);
 8395:     return 'ok';
 8396: }
 8397: 
 8398: sub tokenwrapper {
 8399:     my $uri=shift;
 8400:     $uri=~s|^https?\://([^/]+)||;
 8401:     $uri=~s|^/||;
 8402:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8403:     my $token=$1;
 8404:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8405:     if ($udom && $uname && $file) {
 8406: 	$file=~s|(\?\.*)*$||;
 8407:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8408:         my $homeserver = &homeserver($uname,$udom);
 8409:         my $protocol = $protocol{$homeserver};
 8410:         $protocol = 'http' if ($protocol ne 'https');
 8411:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8412:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8413:                                '&tokenissued='.$perlvar{'lonHostID'};
 8414:     } else {
 8415:         return '/adm/notfound.html';
 8416:     }
 8417: }
 8418: 
 8419: # call with reqtype HEAD: get last modification time
 8420: # call with reqtype GET: get the file contents
 8421: # Do not call this with reqtype GET for large files! It loads everything into memory
 8422: #
 8423: sub getuploaded {
 8424:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8425:     $uri=~s/^\///;
 8426:     my $homeserver = &homeserver($cnum,$cdom);
 8427:     my $protocol = $protocol{$homeserver};
 8428:     $protocol = 'http' if ($protocol ne 'https');
 8429:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8430:     my $ua=new LWP::UserAgent;
 8431:     my $request=new HTTP::Request($reqtype,$uri);
 8432:     my $response=$ua->request($request);
 8433:     $$rtncode = $response->code;
 8434:     if (! $response->is_success()) {
 8435: 	return 'failed';
 8436:     }      
 8437:     if ($reqtype eq 'HEAD') {
 8438: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8439:     } elsif ($reqtype eq 'GET') {
 8440: 	$$info = $response->content;
 8441:     }
 8442:     return 'ok';
 8443: }
 8444: 
 8445: sub readfile {
 8446:     my $file = shift;
 8447:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8448:     my $fh;
 8449:     open($fh,"<$file");
 8450:     my $a='';
 8451:     while (my $line = <$fh>) { $a .= $line; }
 8452:     return $a;
 8453: }
 8454: 
 8455: sub filelocation {
 8456:     my ($dir,$file) = @_;
 8457:     my $location;
 8458:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8459: 
 8460:     if ($file =~ m-^/adm/-) {
 8461: 	$file=~s-^/adm/wrapper/-/-;
 8462: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8463:     }
 8464: 
 8465:     if ($file=~m:^/~:) { # is a contruction space reference
 8466:         $location = $file;
 8467:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8468:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8469: 	# is a correct contruction space reference
 8470:         $location = $file;
 8471:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8472:         $location = $file;
 8473:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8474:         my ($udom,$uname,$filename)=
 8475:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8476:         my $home=&homeserver($uname,$udom);
 8477:         my $is_me=0;
 8478:         my @ids=&current_machine_ids();
 8479:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8480:         if ($is_me) {
 8481:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8482:         } else {
 8483:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8484:   	      $udom.'/'.$uname.'/'.$filename;
 8485:         }
 8486:     } elsif ($file =~ m-^/adm/-) {
 8487: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8488:     } else {
 8489:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8490:         $file=~s:^/res/:/:;
 8491:         if ( !( $file =~ m:^/:) ) {
 8492:             $location = $dir. '/'.$file;
 8493:         } else {
 8494:             $location = '/home/httpd/html/res'.$file;
 8495:         }
 8496:     }
 8497:     $location=~s://+:/:g; # remove duplicate /
 8498:     while ($location=~m{/\.\./}) {
 8499: 	if ($location =~ m{/[^/]+/\.\./}) {
 8500: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8501: 	} else {
 8502: 	    $location=~ s{/\.\./}{/}g;
 8503: 	}
 8504:     } #remove dir/..
 8505:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8506:     return $location;
 8507: }
 8508: 
 8509: sub hreflocation {
 8510:     my ($dir,$file)=@_;
 8511:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8512: 	$file=filelocation($dir,$file);
 8513:     } elsif ($file=~m-^/adm/-) {
 8514: 	$file=~s-^/adm/wrapper/-/-;
 8515: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8516:     }
 8517:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8518: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8519:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8520: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8521:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8522: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8523: 	    -/uploaded/$1/$2/-x;
 8524:     }
 8525:     if ($file=~ m{^/userfiles/}) {
 8526: 	$file =~ s{^/userfiles/}{/uploaded/};
 8527:     }
 8528:     return $file;
 8529: }
 8530: 
 8531: sub current_machine_domains {
 8532:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8533: }
 8534: 
 8535: sub machine_domains {
 8536:     my ($hostname) = @_;
 8537:     my @domains;
 8538:     my %hostname = &all_hostnames();
 8539:     while( my($id, $name) = each(%hostname)) {
 8540: #	&logthis("-$id-$name-$hostname-");
 8541: 	if ($hostname eq $name) {
 8542: 	    push(@domains,&host_domain($id));
 8543: 	}
 8544:     }
 8545:     return @domains;
 8546: }
 8547: 
 8548: sub current_machine_ids {
 8549:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8550: }
 8551: 
 8552: sub machine_ids {
 8553:     my ($hostname) = @_;
 8554:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8555:     my @ids;
 8556:     my %name_to_host = &all_names();
 8557:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8558: 	return @{ $name_to_host{$hostname} };
 8559:     }
 8560:     return;
 8561: }
 8562: 
 8563: sub additional_machine_domains {
 8564:     my @domains;
 8565:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8566:     while( my $line = <$fh>) {
 8567:         $line =~ s/\s//g;
 8568:         push(@domains,$line);
 8569:     }
 8570:     return @domains;
 8571: }
 8572: 
 8573: sub default_login_domain {
 8574:     my $domain = $perlvar{'lonDefDomain'};
 8575:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8576:     foreach my $posdom (&current_machine_domains(),
 8577:                         &additional_machine_domains()) {
 8578:         if (lc($posdom) eq lc($testdomain)) {
 8579:             $domain=$posdom;
 8580:             last;
 8581:         }
 8582:     }
 8583:     return $domain;
 8584: }
 8585: 
 8586: # ------------------------------------------------------------- Declutters URLs
 8587: 
 8588: sub declutter {
 8589:     my $thisfn=shift;
 8590:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8591:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8592:     $thisfn=~s/^\///;
 8593:     $thisfn=~s|^adm/wrapper/||;
 8594:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8595:     $thisfn=~s/^res\///;
 8596:     $thisfn=~s/\?.+$//;
 8597:     return $thisfn;
 8598: }
 8599: 
 8600: # ------------------------------------------------------------- Clutter up URLs
 8601: 
 8602: sub clutter {
 8603:     my $thisfn='/'.&declutter(shift);
 8604:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8605: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8606:        $thisfn='/res'.$thisfn; 
 8607:     }
 8608:     if ($thisfn !~m|/adm|) {
 8609: 	if ($thisfn =~ m|/ext/|) {
 8610: 	    $thisfn='/adm/wrapper'.$thisfn;
 8611: 	} else {
 8612: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8613: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8614: 	    if ($embstyle eq 'ssi'
 8615: 		|| ($embstyle eq 'hdn')
 8616: 		|| ($embstyle eq 'rat')
 8617: 		|| ($embstyle eq 'prv')
 8618: 		|| ($embstyle eq 'ign')) {
 8619: 		#do nothing with these
 8620: 	    } elsif (($embstyle eq 'img') 
 8621: 		|| ($embstyle eq 'emb')
 8622: 		|| ($embstyle eq 'wrp')) {
 8623: 		$thisfn='/adm/wrapper'.$thisfn;
 8624: 	    } elsif ($embstyle eq 'unk'
 8625: 		     && $thisfn!~/\.(sequence|page)$/) {
 8626: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8627: 	    } else {
 8628: #		&logthis("Got a blank emb style");
 8629: 	    }
 8630: 	}
 8631:     }
 8632:     return $thisfn;
 8633: }
 8634: 
 8635: sub clutter_with_no_wrapper {
 8636:     my $uri = &clutter(shift);
 8637:     if ($uri =~ m-^/adm/-) {
 8638: 	$uri =~ s-^/adm/wrapper/-/-;
 8639: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8640:     }
 8641:     return $uri;
 8642: }
 8643: 
 8644: sub freeze_escape {
 8645:     my ($value)=@_;
 8646:     if (ref($value)) {
 8647: 	$value=&nfreeze($value);
 8648: 	return '__FROZEN__'.&escape($value);
 8649:     }
 8650:     return &escape($value);
 8651: }
 8652: 
 8653: 
 8654: sub thaw_unescape {
 8655:     my ($value)=@_;
 8656:     if ($value =~ /^__FROZEN__/) {
 8657: 	substr($value,0,10,undef);
 8658: 	$value=&unescape($value);
 8659: 	return &thaw($value);
 8660:     }
 8661:     return &unescape($value);
 8662: }
 8663: 
 8664: sub correct_line_ends {
 8665:     my ($result)=@_;
 8666:     $$result =~s/\r\n/\n/mg;
 8667:     $$result =~s/\r/\n/mg;
 8668: }
 8669: # ================================================================ Main Program
 8670: 
 8671: sub goodbye {
 8672:    &logthis("Starting Shut down");
 8673: #not converted to using infrastruture and probably shouldn't be
 8674:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8675: #converted
 8676: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8677:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8678: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8679: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8680: #1.1 only
 8681: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8682: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8683: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8684: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8685:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8686:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8687:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8688:    &flushcourselogs();
 8689:    &logthis("Shutting down");
 8690: }
 8691: 
 8692: sub get_dns {
 8693:     my ($url,$func,$ignore_cache) = @_;
 8694:     if (!$ignore_cache) {
 8695: 	my ($content,$cached)=
 8696: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8697: 	if ($cached) {
 8698: 	    &$func($content);
 8699: 	    return;
 8700: 	}
 8701:     }
 8702: 
 8703:     my %alldns;
 8704:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8705:     foreach my $dns (<$config>) {
 8706: 	next if ($dns !~ /^\^(\S*)/x);
 8707:         my $line = $1;
 8708:         my ($host,$protocol) = split(/:/,$line);
 8709:         if ($protocol ne 'https') {
 8710:             $protocol = 'http';
 8711:         }
 8712: 	$alldns{$host} = $protocol;
 8713:     }
 8714:     while (%alldns) {
 8715: 	my ($dns) = keys(%alldns);
 8716: 	my $ua=new LWP::UserAgent;
 8717: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8718: 	my $response=$ua->request($request);
 8719:         delete($alldns{$dns});
 8720: 	next if ($response->is_error());
 8721: 	my @content = split("\n",$response->content);
 8722: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8723: 	&$func(\@content);
 8724: 	return;
 8725:     }
 8726:     close($config);
 8727:     my $which = (split('/',$url))[3];
 8728:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8729:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8730:     my @content = <$config>;
 8731:     &$func(\@content);
 8732:     return;
 8733: }
 8734: # ------------------------------------------------------------ Read domain file
 8735: {
 8736:     my $loaded;
 8737:     my %domain;
 8738: 
 8739:     sub parse_domain_tab {
 8740: 	my ($lines) = @_;
 8741: 	foreach my $line (@$lines) {
 8742: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8743: 
 8744: 	    chomp($line);
 8745: 	    my ($name,@elements) = split(/:/,$line,9);
 8746: 	    my %this_domain;
 8747: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8748: 			       'lang_def', 'city', 'longi', 'lati',
 8749: 			       'primary') {
 8750: 		$this_domain{$field} = shift(@elements);
 8751: 	    }
 8752: 	    $domain{$name} = \%this_domain;
 8753: 	}
 8754:     }
 8755: 
 8756:     sub reset_domain_info {
 8757: 	undef($loaded);
 8758: 	undef(%domain);
 8759:     }
 8760: 
 8761:     sub load_domain_tab {
 8762: 	my ($ignore_cache) = @_;
 8763: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8764: 	my $fh;
 8765: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8766: 	    my @lines = <$fh>;
 8767: 	    &parse_domain_tab(\@lines);
 8768: 	}
 8769: 	close($fh);
 8770: 	$loaded = 1;
 8771:     }
 8772: 
 8773:     sub domain {
 8774: 	&load_domain_tab() if (!$loaded);
 8775: 
 8776: 	my ($name,$what) = @_;
 8777: 	return if ( !exists($domain{$name}) );
 8778: 
 8779: 	if (!$what) {
 8780: 	    return $domain{$name}{'description'};
 8781: 	}
 8782: 	return $domain{$name}{$what};
 8783:     }
 8784: 
 8785:     sub domain_info {
 8786:         &load_domain_tab() if (!$loaded);
 8787:         return %domain;
 8788:     }
 8789: 
 8790: }
 8791: 
 8792: 
 8793: # ------------------------------------------------------------- Read hosts file
 8794: {
 8795:     my %hostname;
 8796:     my %hostdom;
 8797:     my %libserv;
 8798:     my $loaded;
 8799:     my %name_to_host;
 8800: 
 8801:     sub parse_hosts_tab {
 8802: 	my ($file) = @_;
 8803: 	foreach my $configline (@$file) {
 8804: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8805: 	    next if ($configline =~ /^\^/);
 8806: 	    chomp($configline);
 8807: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8808: 	    $name=~s/\s//g;
 8809: 	    if ($id && $domain && $role && $name) {
 8810: 		$hostname{$id}=$name;
 8811: 		push(@{$name_to_host{$name}}, $id);
 8812: 		$hostdom{$id}=$domain;
 8813: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8814:                 if (defined($protocol)) {
 8815:                     if ($protocol eq 'https') {
 8816:                         $protocol{$id} = $protocol;
 8817:                     } else {
 8818:                         $protocol{$id} = 'http'; 
 8819:                     }
 8820:                 } else {
 8821:                     $protocol{$id} = 'http';
 8822:                 }
 8823: 	    }
 8824: 	}
 8825:     }
 8826:     
 8827:     sub reset_hosts_info {
 8828: 	&purge_remembered();
 8829: 	&reset_domain_info();
 8830: 	&reset_hosts_ip_info();
 8831: 	undef(%name_to_host);
 8832: 	undef(%hostname);
 8833: 	undef(%hostdom);
 8834: 	undef(%libserv);
 8835: 	undef($loaded);
 8836:     }
 8837: 
 8838:     sub load_hosts_tab {
 8839: 	my ($ignore_cache) = @_;
 8840: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8841: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8842: 	my @config = <$config>;
 8843: 	&parse_hosts_tab(\@config);
 8844: 	close($config);
 8845: 	$loaded=1;
 8846:     }
 8847: 
 8848:     sub hostname {
 8849: 	&load_hosts_tab() if (!$loaded);
 8850: 
 8851: 	my ($lonid) = @_;
 8852: 	return $hostname{$lonid};
 8853:     }
 8854: 
 8855:     sub all_hostnames {
 8856: 	&load_hosts_tab() if (!$loaded);
 8857: 
 8858: 	return %hostname;
 8859:     }
 8860: 
 8861:     sub all_names {
 8862: 	&load_hosts_tab() if (!$loaded);
 8863: 
 8864: 	return %name_to_host;
 8865:     }
 8866: 
 8867:     sub all_host_domain {
 8868:         &load_hosts_tab() if (!$loaded);
 8869:         return %hostdom;
 8870:     }
 8871: 
 8872:     sub is_library {
 8873: 	&load_hosts_tab() if (!$loaded);
 8874: 
 8875: 	return exists($libserv{$_[0]});
 8876:     }
 8877: 
 8878:     sub all_library {
 8879: 	&load_hosts_tab() if (!$loaded);
 8880: 
 8881: 	return %libserv;
 8882:     }
 8883: 
 8884:     sub get_servers {
 8885: 	&load_hosts_tab() if (!$loaded);
 8886: 
 8887: 	my ($domain,$type) = @_;
 8888: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8889: 	                                          : %hostname;
 8890: 	my %result;
 8891: 	if (ref($domain) eq 'ARRAY') {
 8892: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8893: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8894: 		    $result{$host} = $hostname;
 8895: 		}
 8896: 	    }
 8897: 	} else {
 8898: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8899: 		if ($hostdom{$host} eq $domain) {
 8900: 		    $result{$host} = $hostname;
 8901: 		}
 8902: 	    }
 8903: 	}
 8904: 	return %result;
 8905:     }
 8906: 
 8907:     sub host_domain {
 8908: 	&load_hosts_tab() if (!$loaded);
 8909: 
 8910: 	my ($lonid) = @_;
 8911: 	return $hostdom{$lonid};
 8912:     }
 8913: 
 8914:     sub all_domains {
 8915: 	&load_hosts_tab() if (!$loaded);
 8916: 
 8917: 	my %seen;
 8918: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8919: 	return @uniq;
 8920:     }
 8921: }
 8922: 
 8923: { 
 8924:     my %iphost;
 8925:     my %name_to_ip;
 8926:     my %lonid_to_ip;
 8927: 
 8928:     sub get_hosts_from_ip {
 8929: 	my ($ip) = @_;
 8930: 	my %iphosts = &get_iphost();
 8931: 	if (ref($iphosts{$ip})) {
 8932: 	    return @{$iphosts{$ip}};
 8933: 	}
 8934: 	return;
 8935:     }
 8936:     
 8937:     sub reset_hosts_ip_info {
 8938: 	undef(%iphost);
 8939: 	undef(%name_to_ip);
 8940: 	undef(%lonid_to_ip);
 8941:     }
 8942: 
 8943:     sub get_host_ip {
 8944: 	my ($lonid) = @_;
 8945: 	if (exists($lonid_to_ip{$lonid})) {
 8946: 	    return $lonid_to_ip{$lonid};
 8947: 	}
 8948: 	my $name=&hostname($lonid);
 8949:    	my $ip = gethostbyname($name);
 8950: 	return if (!$ip || length($ip) ne 4);
 8951: 	$ip=inet_ntoa($ip);
 8952: 	$name_to_ip{$name}   = $ip;
 8953: 	$lonid_to_ip{$lonid} = $ip;
 8954: 	return $ip;
 8955:     }
 8956:     
 8957:     sub get_iphost {
 8958: 	my ($ignore_cache) = @_;
 8959: 
 8960: 	if (!$ignore_cache) {
 8961: 	    if (%iphost) {
 8962: 		return %iphost;
 8963: 	    }
 8964: 	    my ($ip_info,$cached)=
 8965: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8966: 	    if ($cached) {
 8967: 		%iphost      = %{$ip_info->[0]};
 8968: 		%name_to_ip  = %{$ip_info->[1]};
 8969: 		%lonid_to_ip = %{$ip_info->[2]};
 8970: 		return %iphost;
 8971: 	    }
 8972: 	}
 8973: 
 8974: 	# get yesterday's info for fallback
 8975: 	my %old_name_to_ip;
 8976: 	my ($ip_info,$cached)=
 8977: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8978: 	if ($cached) {
 8979: 	    %old_name_to_ip = %{$ip_info->[1]};
 8980: 	}
 8981: 
 8982: 	my %name_to_host = &all_names();
 8983: 	foreach my $name (keys(%name_to_host)) {
 8984: 	    my $ip;
 8985: 	    if (!exists($name_to_ip{$name})) {
 8986: 		$ip = gethostbyname($name);
 8987: 		if (!$ip || length($ip) ne 4) {
 8988: 		    if (defined($old_name_to_ip{$name})) {
 8989: 			$ip = $old_name_to_ip{$name};
 8990: 			&logthis("Can't find $name defaulting to old $ip");
 8991: 		    } else {
 8992: 			&logthis("Name $name no IP found");
 8993: 			next;
 8994: 		    }
 8995: 		} else {
 8996: 		    $ip=inet_ntoa($ip);
 8997: 		}
 8998: 		$name_to_ip{$name} = $ip;
 8999: 	    } else {
 9000: 		$ip = $name_to_ip{$name};
 9001: 	    }
 9002: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9003: 		$lonid_to_ip{$id} = $ip;
 9004: 	    }
 9005: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9006: 	}
 9007: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9008: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9009: 				      48*60*60);
 9010: 
 9011: 	return %iphost;
 9012:     }
 9013: }
 9014: 
 9015: #
 9016: #  Given a DNS returns the loncapa host name for that DNS 
 9017: # 
 9018: sub host_from_dns {
 9019:     my ($dns) = @_;
 9020:     my @hosts;
 9021:     my $ip;
 9022: 
 9023:     $ip = gethostbyname($dns);	# Initial translation to IP is in net order.
 9024:     if (length($ip) == 4) { 
 9025: 	$ip   = &IO::Socket::inet_ntoa($ip);
 9026: 	@hosts = get_hosts_from_ip($ip);
 9027: 	return $hosts[0];
 9028:     }
 9029:     return undef;
 9030: }
 9031: 
 9032: BEGIN {
 9033: 
 9034: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9035:     unless ($readit) {
 9036: {
 9037:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9038:     %perlvar = (%perlvar,%{$configvars});
 9039: }
 9040: 
 9041: 
 9042: # ------------------------------------------------------ Read spare server file
 9043: {
 9044:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9045: 
 9046:     while (my $configline=<$config>) {
 9047:        chomp($configline);
 9048:        if ($configline) {
 9049: 	   my ($host,$type) = split(':',$configline,2);
 9050: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9051: 	   push(@{ $spareid{$type} }, $host);
 9052:        }
 9053:     }
 9054:     close($config);
 9055: }
 9056: # ------------------------------------------------------------ Read permissions
 9057: {
 9058:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9059: 
 9060:     while (my $configline=<$config>) {
 9061: 	chomp($configline);
 9062: 	if ($configline) {
 9063: 	    my ($role,$perm)=split(/ /,$configline);
 9064: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9065: 	}
 9066:     }
 9067:     close($config);
 9068: }
 9069: 
 9070: # -------------------------------------------- Read plain texts for permissions
 9071: {
 9072:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9073: 
 9074:     while (my $configline=<$config>) {
 9075: 	chomp($configline);
 9076: 	if ($configline) {
 9077: 	    my ($short,@plain)=split(/:/,$configline);
 9078:             %{$prp{$short}} = ();
 9079: 	    if (@plain > 0) {
 9080:                 $prp{$short}{'std'} = $plain[0];
 9081:                 for (my $i=1; $i<@plain; $i++) {
 9082:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9083:                 }
 9084:             }
 9085: 	}
 9086:     }
 9087:     close($config);
 9088: }
 9089: 
 9090: # ---------------------------------------------------------- Read package table
 9091: {
 9092:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9093: 
 9094:     while (my $configline=<$config>) {
 9095: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9096: 	chomp($configline);
 9097: 	my ($short,$plain)=split(/:/,$configline);
 9098: 	my ($pack,$name)=split(/\&/,$short);
 9099: 	if ($plain ne '') {
 9100: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9101: 	    $packagetab{$short}=$plain; 
 9102: 	}
 9103:     }
 9104:     close($config);
 9105: }
 9106: 
 9107: # ------------- set up temporary directory
 9108: {
 9109:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9110: 
 9111: }
 9112: 
 9113: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9114: 				'compress_threshold'=> 20_000,
 9115:  			        });
 9116: 
 9117: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9118: $dumpcount=0;
 9119: $locknum=0;
 9120: 
 9121: &logtouch();
 9122: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9123: $readit=1;
 9124:     {
 9125: 	use integer;
 9126: 	my $test=(2**32)+1;
 9127: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9128: 	&logthis(" Detected 64bit platform ($_64bit)");
 9129:     }
 9130: }
 9131: }
 9132: 
 9133: 1;
 9134: __END__
 9135: 
 9136: =pod
 9137: 
 9138: =head1 NAME
 9139: 
 9140: Apache::lonnet - Subroutines to ask questions about things in the network.
 9141: 
 9142: =head1 SYNOPSIS
 9143: 
 9144: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9145: 
 9146:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9147: 
 9148: Common parameters:
 9149: 
 9150: =over 4
 9151: 
 9152: =item *
 9153: 
 9154: $uname : an internal username (if $cname expecting a course Id specifically)
 9155: 
 9156: =item *
 9157: 
 9158: $udom : a domain (if $cdom expecting a course's domain specifically)
 9159: 
 9160: =item *
 9161: 
 9162: $symb : a resource instance identifier
 9163: 
 9164: =item *
 9165: 
 9166: $namespace : the name of a .db file that contains the data needed or
 9167: being set.
 9168: 
 9169: =back
 9170: 
 9171: =head1 OVERVIEW
 9172: 
 9173: lonnet provides subroutines which interact with the
 9174: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9175: about classes, users, and resources.
 9176: 
 9177: For many of these objects you can also use this to store data about
 9178: them or modify them in various ways.
 9179: 
 9180: =head2 Symbs
 9181: 
 9182: To identify a specific instance of a resource, LON-CAPA uses symbols
 9183: or "symbs"X<symb>. These identifiers are built from the URL of the
 9184: map, the resource number of the resource in the map, and the URL of
 9185: the resource itself. The latter is somewhat redundant, but might help
 9186: if maps change.
 9187: 
 9188: An example is
 9189: 
 9190:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9191: 
 9192: The respective map entry is
 9193: 
 9194:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9195:   title="Problem 2">
 9196:  </resource>
 9197: 
 9198: Symbs are used by the random number generator, as well as to store and
 9199: restore data specific to a certain instance of for example a problem.
 9200: 
 9201: =head2 Storing And Retrieving Data
 9202: 
 9203: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9204: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9205: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9206: is is the non-critical message twin of cstore. These functions are for
 9207: handlers to store a perl hash to a user's permanent data space in an
 9208: easy manner, and to retrieve it again on another call. It is expected
 9209: that a handler would use this once at the beginning to retrieve data,
 9210: and then again once at the end to send only the new data back.
 9211: 
 9212: The data is stored in the user's data directory on the user's
 9213: homeserver under the ID of the course.
 9214: 
 9215: The hash that is returned by restore will have all of the previous
 9216: value for all of the elements of the hash.
 9217: 
 9218: Example:
 9219: 
 9220:  #creating a hash
 9221:  my %hash;
 9222:  $hash{'foo'}='bar';
 9223: 
 9224:  #storing it
 9225:  &Apache::lonnet::cstore(\%hash);
 9226: 
 9227:  #changing a value
 9228:  $hash{'foo'}='notbar';
 9229: 
 9230:  #adding a new value
 9231:  $hash{'bar'}='foo';
 9232:  &Apache::lonnet::cstore(\%hash);
 9233: 
 9234:  #retrieving the hash
 9235:  my %history=&Apache::lonnet::restore();
 9236: 
 9237:  #print the hash
 9238:  foreach my $key (sort(keys(%history))) {
 9239:    print("\%history{$key} = $history{$key}");
 9240:  }
 9241: 
 9242: Will print out:
 9243: 
 9244:  %history{1:foo} = bar
 9245:  %history{1:keys} = foo:timestamp
 9246:  %history{1:timestamp} = 990455579
 9247:  %history{2:bar} = foo
 9248:  %history{2:foo} = notbar
 9249:  %history{2:keys} = foo:bar:timestamp
 9250:  %history{2:timestamp} = 990455580
 9251:  %history{bar} = foo
 9252:  %history{foo} = notbar
 9253:  %history{timestamp} = 990455580
 9254:  %history{version} = 2
 9255: 
 9256: Note that the special hash entries C<keys>, C<version> and
 9257: C<timestamp> were added to the hash. C<version> will be equal to the
 9258: total number of versions of the data that have been stored. The
 9259: C<timestamp> attribute will be the UNIX time the hash was
 9260: stored. C<keys> is available in every historical section to list which
 9261: keys were added or changed at a specific historical revision of a
 9262: hash.
 9263: 
 9264: B<Warning>: do not store the hash that restore returns directly. This
 9265: will cause a mess since it will restore the historical keys as if the
 9266: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9267: 
 9268: Calling convention:
 9269: 
 9270:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9271:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9272: 
 9273: For more detailed information, see lonnet specific documentation.
 9274: 
 9275: =head1 RETURN MESSAGES
 9276: 
 9277: =over 4
 9278: 
 9279: =item * B<con_lost>: unable to contact remote host
 9280: 
 9281: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9282: when the connection is brought back up
 9283: 
 9284: =item * B<con_failed>: unable to contact remote host and unable to save message
 9285: for later delivery
 9286: 
 9287: =item * B<error:>: an error a occurred, a description of the error follows the :
 9288: 
 9289: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9290: that was requested
 9291: 
 9292: =back
 9293: 
 9294: =head1 PUBLIC SUBROUTINES
 9295: 
 9296: =head2 Session Environment Functions
 9297: 
 9298: =over 4
 9299: 
 9300: =item * 
 9301: X<appenv()>
 9302: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9303: the user envirnoment file, and will be restored for each access this
 9304: user makes during this session, also modifies the %env for the current
 9305: process. Optional rolesarrayref - if defined contains a reference to an array
 9306: of roles which are exempt from the restriction on modifying user.role entries 
 9307: in the user's environment.db and in %env.    
 9308: 
 9309: =item *
 9310: X<delenv()>
 9311: B<delenv($regexp)>: removes all items from the session
 9312: environment file that matches the regular expression in $regexp. The
 9313: values are also delted from the current processes %env.
 9314: 
 9315: =item * get_env_multiple($name) 
 9316: 
 9317: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9318: values may be defined and end up as an array ref.
 9319: 
 9320: returns an array of values
 9321: 
 9322: =back
 9323: 
 9324: =head2 User Information
 9325: 
 9326: =over 4
 9327: 
 9328: =item *
 9329: X<queryauthenticate()>
 9330: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9331: authentication scheme
 9332: 
 9333: =item *
 9334: X<authenticate()>
 9335: B<authenticate($uname,$upass,$udom)>: try to
 9336: authenticate user from domain's lib servers (first use the current
 9337: one). C<$upass> should be the users password.
 9338: 
 9339: =item *
 9340: X<homeserver()>
 9341: B<homeserver($uname,$udom)>: find the server which has
 9342: the user's directory and files (there must be only one), this caches
 9343: the answer, and also caches if there is a borken connection.
 9344: 
 9345: =item *
 9346: X<idget()>
 9347: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9348: (IDs are a unique resource in a domain, there must be only 1 ID per
 9349: username, and only 1 username per ID in a specific domain) (returns
 9350: hash: id=>name,id=>name)
 9351: 
 9352: =item *
 9353: X<idrget()>
 9354: B<idrget($udom,@unames)>: find the IDs behind a list of
 9355: usernames (returns hash: name=>id,name=>id)
 9356: 
 9357: =item *
 9358: X<idput()>
 9359: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9360: 
 9361: =item *
 9362: X<rolesinit()>
 9363: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9364: 
 9365: =item *
 9366: X<getsection()>
 9367: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9368: course $cname, return section name/number or '' for "not in course"
 9369: and '-1' for "no section"
 9370: 
 9371: =item *
 9372: X<userenvironment()>
 9373: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9374: passed in @what from the requested user's environment, returns a hash
 9375: 
 9376: =item * 
 9377: X<userlog_query()>
 9378: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9379: activity.log file. %filters defines filters applied when parsing the
 9380: log file. These can be start or end timestamps, or the type of action
 9381: - log to look for Login or Logout events, check for Checkin or
 9382: Checkout, role for role selection. The response is in the form
 9383: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9384: escaped strings of the action recorded in the activity.log file.
 9385: 
 9386: =back
 9387: 
 9388: =head2 User Roles
 9389: 
 9390: =over 4
 9391: 
 9392: =item *
 9393: 
 9394: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9395:  F: full access
 9396:  U,I,K: authentication modes (cxx only)
 9397:  '': forbidden
 9398:  1: user needs to choose course
 9399:  2: browse allowed
 9400:  A: passphrase authentication needed
 9401: 
 9402: =item *
 9403: 
 9404: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9405: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9406: and course level
 9407: 
 9408: =item *
 9409: 
 9410: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9411: explanation of a user role term
 9412: 
 9413: =item *
 9414: 
 9415: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9416: All arguments are optional. Returns a hash of a roles, either for
 9417: co-author/assistant author roles for a user's Construction Space
 9418: (default), or if $context is 'userroles', roles for the user himself,
 9419: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9420: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9421: For each key, value is set to colon-separated start and end times for
 9422: the role.  If no username and domain are specified, will default to
 9423: current user/domain. Types, roles, and roledoms are references to arrays
 9424: of role statuses (active, future or previous), roles 
 9425: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9426: to restrict the list of roles reported. If no array ref is 
 9427: provided for types, will default to return only active roles.
 9428: 
 9429: =back
 9430: 
 9431: =head2 User Modification
 9432: 
 9433: =over 4
 9434: 
 9435: =item *
 9436: 
 9437: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9438: user for the level given by URL.  Optional start and end dates (leave empty
 9439: string or zero for "no date")
 9440: 
 9441: =item *
 9442: 
 9443: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9444: change a users, password, possible return values are: ok,
 9445: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9446: refused
 9447: 
 9448: =item *
 9449: 
 9450: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9451: 
 9452: =item *
 9453: 
 9454: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9455:            $forceid,$desiredhome,$email,$inststatus) : 
 9456: modify user
 9457: 
 9458: =item *
 9459: 
 9460: modifystudent
 9461: 
 9462: modify a student's enrollment and identification information.
 9463: The course id is resolved based on the current users environment.  
 9464: This means the envoking user must be a course coordinator or otherwise
 9465: associated with a course.
 9466: 
 9467: This call is essentially a wrapper for lonnet::modifyuser and
 9468: lonnet::modify_student_enrollment
 9469: 
 9470: Inputs: 
 9471: 
 9472: =over 4
 9473: 
 9474: =item B<$udom> Student's loncapa domain
 9475: 
 9476: =item B<$uname> Student's loncapa login name
 9477: 
 9478: =item B<$uid> Student/Employee ID
 9479: 
 9480: =item B<$umode> Student's authentication mode
 9481: 
 9482: =item B<$upass> Student's password
 9483: 
 9484: =item B<$first> Student's first name
 9485: 
 9486: =item B<$middle> Student's middle name
 9487: 
 9488: =item B<$last> Student's last name
 9489: 
 9490: =item B<$gene> Student's generation
 9491: 
 9492: =item B<$usec> Student's section in course
 9493: 
 9494: =item B<$end> Unix time of the roles expiration
 9495: 
 9496: =item B<$start> Unix time of the roles start date
 9497: 
 9498: =item B<$forceid> If defined, allow $uid to be changed
 9499: 
 9500: =item B<$desiredhome> server to use as home server for student
 9501: 
 9502: =item B<$email> Student's permanent e-mail address
 9503: 
 9504: =item B<$type> Type of enrollment (auto or manual)
 9505: 
 9506: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9507: 
 9508: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9509: 
 9510: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9511: 
 9512: =item B<$context> role change context (shown in User Management Logs display in a course)
 9513: 
 9514: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9515: 
 9516: =back
 9517: 
 9518: =item *
 9519: 
 9520: modify_student_enrollment
 9521: 
 9522: Change a students enrollment status in a class.  The environment variable
 9523: 'role.request.course' must be defined for this function to proceed.
 9524: 
 9525: Inputs:
 9526: 
 9527: =over 4
 9528: 
 9529: =item $udom, students domain
 9530: 
 9531: =item $uname, students name
 9532: 
 9533: =item $uid, students user id
 9534: 
 9535: =item $first, students first name
 9536: 
 9537: =item $middle
 9538: 
 9539: =item $last
 9540: 
 9541: =item $gene
 9542: 
 9543: =item $usec
 9544: 
 9545: =item $end
 9546: 
 9547: =item $start
 9548: 
 9549: =item $type
 9550: 
 9551: =item $locktype
 9552: 
 9553: =item $cid
 9554: 
 9555: =item $selfenroll
 9556: 
 9557: =item $context
 9558: 
 9559: =back
 9560: 
 9561: 
 9562: =item *
 9563: 
 9564: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9565: custom role; give a custom role to a user for the level given by URL.  Specify
 9566: name and domain of role author, and role name
 9567: 
 9568: =item *
 9569: 
 9570: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9571: 
 9572: =item *
 9573: 
 9574: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9575: 
 9576: =back
 9577: 
 9578: =head2 Course Infomation
 9579: 
 9580: =over 4
 9581: 
 9582: =item *
 9583: 
 9584: coursedescription($courseid) : returns a hash of information about the
 9585: specified course id, including all environment settings for the
 9586: course, the description of the course will be in the hash under the
 9587: key 'description'
 9588: 
 9589: =item *
 9590: 
 9591: resdata($name,$domain,$type,@which) : request for current parameter
 9592: setting for a specific $type, where $type is either 'course' or 'user',
 9593: @what should be a list of parameters to ask about. This routine caches
 9594: answers for 5 minutes.
 9595: 
 9596: =item *
 9597: 
 9598: get_courseresdata($courseid, $domain) : dump the entire course resource
 9599: data base, returning a hash that is keyed by the resource name and has
 9600: values that are the resource value.  I believe that the timestamps and
 9601: versions are also returned.
 9602: 
 9603: 
 9604: =back
 9605: 
 9606: =head2 Course Modification
 9607: 
 9608: =over 4
 9609: 
 9610: =item *
 9611: 
 9612: writecoursepref($courseid,%prefs) : write preferences (environment
 9613: database) for a course
 9614: 
 9615: =item *
 9616: 
 9617: createcourse($udom,$description,$url) : make/modify course
 9618: 
 9619: =back
 9620: 
 9621: =head2 Resource Subroutines
 9622: 
 9623: =over 4
 9624: 
 9625: =item *
 9626: 
 9627: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9628: 
 9629: =item *
 9630: 
 9631: repcopy($filename) : subscribes to the requested file, and attempts to
 9632: replicate from the owning library server, Might return
 9633: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9634: 'bad_request', also attempts to grab the metadata for the
 9635: resource. Expects the local filesystem pathname
 9636: (/home/httpd/html/res/....)
 9637: 
 9638: =back
 9639: 
 9640: =head2 Resource Information
 9641: 
 9642: =over 4
 9643: 
 9644: =item *
 9645: 
 9646: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9647: a vairety of different possible values, $varname should be a request
 9648: string, and the other parameters can be used to specify who and what
 9649: one is asking about.
 9650: 
 9651: Possible values for $varname are environment.lastname (or other item
 9652: from the envirnment hash), user.name (or someother aspect about the
 9653: user), resource.0.maxtries (or some other part and parameter of a
 9654: resource)
 9655: 
 9656: =item *
 9657: 
 9658: directcondval($number) : get current value of a condition; reads from a state
 9659: string
 9660: 
 9661: =item *
 9662: 
 9663: condval($condidx) : value of condition index based on state
 9664: 
 9665: =item *
 9666: 
 9667: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9668: resource's metadata, $what should be either a specific key, or either
 9669: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9670: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9671: 
 9672: this function automatically caches all requests
 9673: 
 9674: =item *
 9675: 
 9676: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9677: network of library servers; returns file handle of where SQL and regex results
 9678: will be stored for query
 9679: 
 9680: =item *
 9681: 
 9682: symbread($filename) : return symbolic list entry (filename argument optional);
 9683: returns the data handle
 9684: 
 9685: =item *
 9686: 
 9687: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9688: a possible symb for the URL in $thisfn, and if is an encryypted
 9689: resource that the user accessed using /enc/ returns a 1 on success, 0
 9690: on failure, user must be in a course, as it assumes the existance of
 9691: the course initial hash, and uses $env('request.course.id'}
 9692: 
 9693: 
 9694: =item *
 9695: 
 9696: symbclean($symb) : removes versions numbers from a symb, returns the
 9697: cleaned symb
 9698: 
 9699: =item *
 9700: 
 9701: is_on_map($uri) : checks if the $uri is somewhere on the current
 9702: course map, user must be in a course for it to work.
 9703: 
 9704: =item *
 9705: 
 9706: numval($salt) : return random seed value (addend for rndseed)
 9707: 
 9708: =item *
 9709: 
 9710: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9711: a random seed, all arguments are optional, if they aren't sent it uses the
 9712: environment to derive them. Note: if symb isn't sent and it can't get one
 9713: from &symbread it will use the current time as its return value
 9714: 
 9715: =item *
 9716: 
 9717: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9718: unfakeable, receipt
 9719: 
 9720: =item *
 9721: 
 9722: receipt() : API to ireceipt working off of env values; given out to users
 9723: 
 9724: =item *
 9725: 
 9726: countacc($url) : count the number of accesses to a given URL
 9727: 
 9728: =item *
 9729: 
 9730: 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
 9731: 
 9732: =item *
 9733: 
 9734: 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)
 9735: 
 9736: =item *
 9737: 
 9738: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9739: 
 9740: =item *
 9741: 
 9742: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9743: forcing spreadsheet to reevaluate the resource scores next time.
 9744: 
 9745: =back
 9746: 
 9747: =head2 Storing/Retreiving Data
 9748: 
 9749: =over 4
 9750: 
 9751: =item *
 9752: 
 9753: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9754: for this url; hashref needs to be given and should be a \%hashname; the
 9755: remaining args aren't required and if they aren't passed or are '' they will
 9756: be derived from the env
 9757: 
 9758: =item *
 9759: 
 9760: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9761: uses critical subroutine
 9762: 
 9763: =item *
 9764: 
 9765: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9766: all args are optional
 9767: 
 9768: =item *
 9769: 
 9770: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9771: dumps the complete (or key matching regexp) namespace into a hash
 9772: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9773: normally &store()ed into
 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: 
 9781: 
 9782: =item *
 9783: 
 9784: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9785: replaces a &store() version of data with a replacement set of data
 9786: for a particular resource in a namespace passed in the $storehash hash 
 9787: reference
 9788: 
 9789: =item *
 9790: 
 9791: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9792: works very similar to store/cstore, but all data is stored in a
 9793: temporary location and can be reset using tmpreset, $storehash should
 9794: be a hash reference, returns nothing on success
 9795: 
 9796: =item *
 9797: 
 9798: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9799: similar to restore, but all data is stored in a temporary location and
 9800: can be reset using tmpreset. Returns a hash of values on success,
 9801: error string otherwise.
 9802: 
 9803: =item *
 9804: 
 9805: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9806: deltes all keys for $symb form the temporary storage hash.
 9807: 
 9808: =item *
 9809: 
 9810: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9811: reference filled in from namesp ($udom and $uname are optional)
 9812: 
 9813: =item *
 9814: 
 9815: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9816: namesp ($udom and $uname are optional)
 9817: 
 9818: =item *
 9819: 
 9820: dump($namespace,$udom,$uname,$regexp,$range) : 
 9821: dumps the complete (or key matching regexp) namespace into a hash
 9822: ($udom, $uname, $regexp, $range are optional)
 9823: 
 9824: $range should be either an integer '100' (give me the first 100
 9825:                                            matching records)
 9826:               or be  two integers sperated by a - with no spaces
 9827:                  '30-50' (give me the 30th through the 50th matching
 9828:                           records)
 9829: =item *
 9830: 
 9831: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9832: $store can be a scalar, an array reference, or if the amount to be 
 9833: incremented is > 1, a hash reference.
 9834: 
 9835: ($udom and $uname are optional)
 9836: 
 9837: =item *
 9838: 
 9839: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9840: ($udom and $uname are optional)
 9841: 
 9842: =item *
 9843: 
 9844: cput($namespace,$storehash,$udom,$uname) : critical put
 9845: ($udom and $uname are optional)
 9846: 
 9847: =item *
 9848: 
 9849: newput($namespace,$storehash,$udom,$uname) :
 9850: 
 9851: Attempts to store the items in the $storehash, but only if they don't
 9852: currently exist, if this succeeds you can be certain that you have 
 9853: successfully created a new key value pair in the $namespace db.
 9854: 
 9855: 
 9856: Args:
 9857:  $namespace: name of database to store values to
 9858:  $storehash: hashref to store to the db
 9859:  $udom: (optional) domain of user containing the db
 9860:  $uname: (optional) name of user caontaining the db
 9861: 
 9862: Returns:
 9863:  'ok' -> succeeded in storing all keys of $storehash
 9864:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9865:                         least <key> already existed in the db (other
 9866:                         requested keys may also already exist)
 9867:  'error: <msg>' -> unable to tie the DB or other error occurred
 9868:  'con_lost' -> unable to contact request server
 9869:  'refused' -> action was not allowed by remote machine
 9870: 
 9871: 
 9872: =item *
 9873: 
 9874: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9875: reference filled in from namesp (encrypts the return communication)
 9876: ($udom and $uname are optional)
 9877: 
 9878: =item *
 9879: 
 9880: log($udom,$name,$home,$message) : write to permanent log for user; use
 9881: critical subroutine
 9882: 
 9883: =item *
 9884: 
 9885: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9886: array reference filled in from namespace found in domain level on either
 9887: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9888: 
 9889: =item *
 9890: 
 9891: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9892: domain level either on specified domain server ($uhome) or primary domain 
 9893: server ($udom and $uhome are optional)
 9894: 
 9895: =item * 
 9896: 
 9897: get_domain_defaults($target_domain) : returns hash with defaults for
 9898: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9899: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9900: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9901: Values are retrieved from cache (if current), or from domain's configuration.db
 9902: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9903: or lonTabs/domain.tab. 
 9904: 
 9905: %domdefaults = &get_auth_defaults($target_domain);
 9906: 
 9907: =back
 9908: 
 9909: =head2 Network Status Functions
 9910: 
 9911: =over 4
 9912: 
 9913: =item *
 9914: 
 9915: dirlist($uri) : return directory list based on URI
 9916: 
 9917: =item *
 9918: 
 9919: spareserver() : find server with least workload from spare.tab
 9920: 
 9921: 
 9922: =item *
 9923: 
 9924: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
 9925: if there is no corresponding loncapa host.
 9926: 
 9927: =back
 9928: 
 9929: 
 9930: =head2 Apache Request
 9931: 
 9932: =over 4
 9933: 
 9934: =item *
 9935: 
 9936: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9937: localhost, posts hash
 9938: 
 9939: =back
 9940: 
 9941: =head2 Data to String to Data
 9942: 
 9943: =over 4
 9944: 
 9945: =item *
 9946: 
 9947: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9948: and '&' separators, supports elements that are arrayrefs and hashrefs
 9949: 
 9950: =item *
 9951: 
 9952: hashref2str($hashref) : convert a hashref into a string complete with
 9953: escaping and '=' and '&' separators, supports elements that are
 9954: arrayrefs and hashrefs
 9955: 
 9956: =item *
 9957: 
 9958: arrayref2str($arrayref) : convert an arrayref into a string complete
 9959: with escaping and '&' separators, supports elements that are arrayrefs
 9960: and hashrefs
 9961: 
 9962: =item *
 9963: 
 9964: str2hash($string) : convert string to hash using unescaping and
 9965: splitting on '=' and '&', supports elements that are arrayrefs and
 9966: hashrefs
 9967: 
 9968: =item *
 9969: 
 9970: str2array($string) : convert string to hash using unescaping and
 9971: splitting on '&', supports elements that are arrayrefs and hashrefs
 9972: 
 9973: =back
 9974: 
 9975: =head2 Logging Routines
 9976: 
 9977: =over 4
 9978: 
 9979: These routines allow one to make log messages in the lonnet.log and
 9980: lonnet.perm logfiles.
 9981: 
 9982: =item *
 9983: 
 9984: logtouch() : make sure the logfile, lonnet.log, exists
 9985: 
 9986: =item *
 9987: 
 9988: logthis() : append message to the normal lonnet.log file, it gets
 9989: preiodically rolled over and deleted.
 9990: 
 9991: =item *
 9992: 
 9993: logperm() : append a permanent message to lonnet.perm.log, this log
 9994: file never gets deleted by any automated portion of the system, only
 9995: messages of critical importance should go in here.
 9996: 
 9997: =back
 9998: 
 9999: =head2 General File Helper Routines
10000: 
10001: =over 4
10002: 
10003: =item *
10004: 
10005: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10006: (a) files in /uploaded
10007:   (i) If a local copy of the file exists - 
10008:       compares modification date of local copy with last-modified date for 
10009:       definitive version stored on home server for course. If local copy is 
10010:       stale, requests a new version from the home server and stores it. 
10011:       If the original has been removed from the home server, then local copy 
10012:       is unlinked.
10013:   (ii) If local copy does not exist -
10014:       requests the file from the home server and stores it. 
10015:   
10016:   If $caller is 'uploadrep':  
10017:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10018:     for request for files originally uploaded via DOCS. 
10019:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10020:   
10021:   Otherwise:
10022:      This indicates a call from the content generation phase of the request.
10023:      -  returns the entire contents of the file or -1.
10024:      
10025: (b) files in /res
10026:    - returns the entire contents of a file or -1; 
10027:    it properly subscribes to and replicates the file if neccessary.
10028: 
10029: 
10030: =item *
10031: 
10032: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10033:                   reference
10034: 
10035: returns either a stat() list of data about the file or an empty list
10036: if the file doesn't exist or couldn't find out about it (connection
10037: problems or user unknown)
10038: 
10039: =item *
10040: 
10041: filelocation($dir,$file) : returns file system location of a file
10042: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10043: directory that relative $file lookups are to looked in ($dir of /a/dir
10044: and a file of ../bob will become /a/bob)
10045: 
10046: =item *
10047: 
10048: hreflocation($dir,$file) : returns file system location or a URL; same as
10049: filelocation except for hrefs
10050: 
10051: =item *
10052: 
10053: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10054: 
10055: =back
10056: 
10057: =head2 Usererfile file routines (/uploaded*)
10058: 
10059: =over 4
10060: 
10061: =item *
10062: 
10063: userfileupload(): main rotine for putting a file in a user or course's
10064:                   filespace, arguments are,
10065: 
10066:  formname - required - this is the name of the element in $env where the
10067:            filename, and the contents of the file to create/modifed exist
10068:            the filename is in $env{'form.'.$formname.'.filename'} and the
10069:            contents of the file is located in $env{'form.'.$formname}
10070:  coursedoc - if true, store the file in the course of the active role
10071:              of the current user
10072:  subdir - required - subdirectory to put the file in under ../userfiles/
10073:          if undefined, it will be placed in "unknown"
10074: 
10075:  (This routine calls clean_filename() to remove any dangerous
10076:  characters from the filename, and then calls finuserfileupload() to
10077:  complete the transaction)
10078: 
10079:  returns either the url of the uploaded file (/uploaded/....) if successful
10080:  and /adm/notfound.html if unsuccessful
10081: 
10082: =item *
10083: 
10084: clean_filename(): routine for cleaing a filename up for storage in
10085:                  userfile space, argument is:
10086: 
10087:  filename - proposed filename
10088: 
10089: returns: the new clean filename
10090: 
10091: =item *
10092: 
10093: finishuserfileupload(): routine that creaes and sends the file to
10094: userspace, probably shouldn't be called directly
10095: 
10096:   docuname: username or courseid of destination for the file
10097:   docudom: domain of user/course of destination for the file
10098:   formname: same as for userfileupload()
10099:   fname: filename (inculding subdirectories) for the file
10100: 
10101:  returns either the url of the uploaded file (/uploaded/....) if successful
10102:  and /adm/notfound.html if unsuccessful
10103: 
10104: =item *
10105: 
10106: renameuserfile(): renames an existing userfile to a new name
10107: 
10108:   Args:
10109:    docuname: username or courseid of destination for the file
10110:    docudom: domain of user/course of destination for the file
10111:    old: current file name (including any subdirs under userfiles)
10112:    new: desired file name (including any subdirs under userfiles)
10113: 
10114: =item *
10115: 
10116: mkdiruserfile(): creates a directory is a userfiles dir
10117: 
10118:   Args:
10119:    docuname: username or courseid of destination for the file
10120:    docudom: domain of user/course of destination for the file
10121:    dir: dir to create (including any subdirs under userfiles)
10122: 
10123: =item *
10124: 
10125: removeuserfile(): removes a file that exists in userfiles
10126: 
10127:   Args:
10128:    docuname: username or courseid of destination for the file
10129:    docudom: domain of user/course of destination for the file
10130:    fname: filname to delete (including any subdirs under userfiles)
10131: 
10132: =item *
10133: 
10134: removeuploadedurl(): convience function for removeuserfile()
10135: 
10136:   Args:
10137:    url:  a full /uploaded/... url to delete
10138: 
10139: =item * 
10140: 
10141: get_portfile_permissions():
10142:   Args:
10143:     domain: domain of user or course contain the portfolio files
10144:     user: name of user or num of course contain the portfolio files
10145:   Returns:
10146:     hashref of a dump of the proper file_permissions.db
10147:    
10148: 
10149: =item * 
10150: 
10151: get_access_controls():
10152: 
10153: Args:
10154:   current_permissions: the hash ref returned from get_portfile_permissions()
10155:   group: (optional) the group you want the files associated with
10156:   file: (optional) the file you want access info on
10157: 
10158: Returns:
10159:     a hash (keys are file names) of hashes containing
10160:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10161:         values are XML containing access control settings (see below) 
10162: 
10163: Internal notes:
10164: 
10165:  access controls are stored in file_permissions.db as key=value pairs.
10166:     key -> path to file/file_name\0uniqueID:scope_end_start
10167:         where scope -> public,guest,course,group,domains or users.
10168:               end -> UNIX time for end of access (0 -> no end date)
10169:               start -> UNIX time for start of access
10170: 
10171:     value -> XML description of access control
10172:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10173:             <start></start>
10174:             <end></end>
10175: 
10176:             <password></password>  for scope type = guest
10177: 
10178:             <domain></domain>     for scope type = course or group
10179:             <number></number>
10180:             <roles id="">
10181:              <role></role>
10182:              <access></access>
10183:              <section></section>
10184:              <group></group>
10185:             </roles>
10186: 
10187:             <dom></dom>         for scope type = domains
10188: 
10189:             <users>             for scope type = users
10190:              <user>
10191:               <uname></uname>
10192:               <udom></udom>
10193:              </user>
10194:             </users>
10195:            </scope> 
10196:               
10197:  Access data is also aggregated for each file in an additional key=value pair:
10198:  key -> path to file/file_name\0accesscontrol 
10199:  value -> reference to hash
10200:           hash contains key = value pairs
10201:           where key = uniqueID:scope_end_start
10202:                 value = UNIX time record was last updated
10203: 
10204:           Used to improve speed of look-ups of access controls for each file.  
10205:  
10206:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10207: 
10208: modify_access_controls():
10209: 
10210: Modifies access controls for a portfolio file
10211: Args
10212: 1. file name
10213: 2. reference to hash of required changes,
10214: 3. domain
10215: 4. username
10216:   where domain,username are the domain of the portfolio owner 
10217:   (either a user or a course) 
10218: 
10219: Returns:
10220: 1. result of additions or updates ('ok' or 'error', with error message). 
10221: 2. result of deletions ('ok' or 'error', with error message).
10222: 3. reference to hash of any new or updated access controls.
10223: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10224:    key = integer (inbound ID)
10225:    value = uniqueID  
10226: 
10227: =back
10228: 
10229: =head2 HTTP Helper Routines
10230: 
10231: =over 4
10232: 
10233: =item *
10234: 
10235: escape() : unpack non-word characters into CGI-compatible hex codes
10236: 
10237: =item *
10238: 
10239: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10240: 
10241: =back
10242: 
10243: =head1 PRIVATE SUBROUTINES
10244: 
10245: =head2 Underlying communication routines (Shouldn't call)
10246: 
10247: =over 4
10248: 
10249: =item *
10250: 
10251: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10252: 
10253: =item *
10254: 
10255: reply() : uses subreply to send a message to remote machine, logs all failures
10256: 
10257: =item *
10258: 
10259: critical() : passes a critical message to another server; if cannot
10260: get through then place message in connection buffer directory and
10261: returns con_delayed, if incapable of saving message, returns
10262: con_failed
10263: 
10264: =item *
10265: 
10266: reconlonc() : tries to reconnect lonc client processes.
10267: 
10268: =back
10269: 
10270: =head2 Resource Access Logging
10271: 
10272: =over 4
10273: 
10274: =item *
10275: 
10276: flushcourselogs() : flush (save) buffer logs and access logs
10277: 
10278: =item *
10279: 
10280: courselog($what) : save message for course in hash
10281: 
10282: =item *
10283: 
10284: courseacclog($what) : save message for course using &courselog().  Perform
10285: special processing for specific resource types (problems, exams, quizzes, etc).
10286: 
10287: =item *
10288: 
10289: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10290: as a PerlChildExitHandler
10291: 
10292: =back
10293: 
10294: =head2 Other
10295: 
10296: =over 4
10297: 
10298: =item *
10299: 
10300: symblist($mapname,%newhash) : update symbolic storage links
10301: 
10302: =back
10303: 
10304: =cut
10305: 

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