File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.987: download - view: text, annotated - select for diffs
Wed Feb 18 06:54:22 2009 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Allow lonnet::delenv() to treat $delthis string passed to it as a regexp, by adding second arg ($regexp - if evaluated to true do not use \Q escape).
- Default (second arg false) is to use \Q escape to avoid interpolating special characters in $delthis in regular expression (rev 1.981 behavior). All but one &lonnet::delenv() call use this default.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.987 2009/02/18 06:54:22 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 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,$regexp) = @_;
  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 ($regexp) {
  545:                 if ($key=~/^$delthis/) {
  546:                     delete($env{$key});
  547:                     delete($disk_env{$key});
  548:                 } 
  549:             } else {
  550:                 if ($key=~/^\Q$delthis\E/) {
  551: 		    delete($env{$key});
  552: 		    delete($disk_env{$key});
  553: 	        }
  554:             }
  555: 	}
  556: 	untie(%disk_env);
  557:     }
  558:     return 'ok';
  559: }
  560: 
  561: sub get_env_multiple {
  562:     my ($name) = @_;
  563:     my @values;
  564:     if (defined($env{$name})) {
  565:         # exists is it an array
  566:         if (ref($env{$name})) {
  567:             @values=@{ $env{$name} };
  568:         } else {
  569:             $values[0]=$env{$name};
  570:         }
  571:     }
  572:     return(@values);
  573: }
  574: 
  575: # ------------------------------------------------------------------- Locking
  576: 
  577: sub set_lock {
  578:     my ($text)=@_;
  579:     $locknum++;
  580:     my $id=$$.'-'.$locknum;
  581:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  582:              'session.lock.'.$id => $text});
  583:     return $id;
  584: }
  585: 
  586: sub get_locks {
  587:     my $num=0;
  588:     my %texts=();
  589:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  590:        if ($lock=~/\w/) {
  591:           $num++;
  592:           $texts{$lock}=$env{'session.lock.'.$lock};
  593:        }
  594:    }
  595:    return ($num,%texts);
  596: }
  597: 
  598: sub remove_lock {
  599:     my ($id)=@_;
  600:     my $newlocks='';
  601:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  602:        if (($lock=~/\w/) && ($lock ne $id)) {
  603:           $newlocks.=','.$lock;
  604:        }
  605:     }
  606:     &appenv({'session.locks' => $newlocks});
  607:     &delenv('session.lock.'.$id);
  608: }
  609: 
  610: sub remove_all_locks {
  611:     my $activelocks=$env{'session.locks'};
  612:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  613:        if ($lock=~/\w/) {
  614:           &remove_lock($lock);
  615:        }
  616:     }
  617: }
  618: 
  619: 
  620: # ------------------------------------------ Find out current server userload
  621: sub userload {
  622:     my $numusers=0;
  623:     {
  624: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  625: 	my $filename;
  626: 	my $curtime=time;
  627: 	while ($filename=readdir(LONIDS)) {
  628: 	    next if ($filename eq '.' || $filename eq '..');
  629: 	    next if ($filename =~ /publicuser_\d+\.id/);
  630: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  631: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  632: 	}
  633: 	closedir(LONIDS);
  634:     }
  635:     my $userloadpercent=0;
  636:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  637:     if ($maxuserload) {
  638: 	$userloadpercent=100*$numusers/$maxuserload;
  639:     }
  640:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  641:     return $userloadpercent;
  642: }
  643: 
  644: # ------------------------------------------ Fight off request when overloaded
  645: 
  646: sub overloaderror {
  647:     my ($r,$checkserver)=@_;
  648:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  649:     my $loadavg;
  650:     if ($checkserver eq $perlvar{'lonHostID'}) {
  651:        open(my $loadfile,'/proc/loadavg');
  652:        $loadavg=<$loadfile>;
  653:        $loadavg =~ s/\s.*//g;
  654:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  655:        close($loadfile);
  656:     } else {
  657:        $loadavg=&reply('load',$checkserver);
  658:     }
  659:     my $overload=$loadavg-100;
  660:     if ($overload>0) {
  661: 	$r->err_headers_out->{'Retry-After'}=$overload;
  662:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  663:         return 413;
  664:     }    
  665:     return '';
  666: }
  667: 
  668: # ------------------------------ Find server with least workload from spare.tab
  669: 
  670: sub spareserver {
  671:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  672:     my $spare_server;
  673:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  674:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  675:                                                      :  $userloadpercent;
  676:     
  677:     foreach my $try_server (@{ $spareid{'primary'} }) {
  678: 	($spare_server, $lowest_load) =
  679: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  680:     }
  681: 
  682:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  683: 
  684:     if (!$found_server) {
  685: 	foreach my $try_server (@{ $spareid{'default'} }) {
  686: 	    ($spare_server, $lowest_load) =
  687: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  688: 	}
  689:     }
  690: 
  691:     if (!$want_server_name) {
  692:         my $protocol = 'http';
  693:         if ($protocol{$spare_server} eq 'https') {
  694:             $protocol = $protocol{$spare_server};
  695:         }
  696: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  697:     }
  698:     return $spare_server;
  699: }
  700: 
  701: sub compare_server_load {
  702:     my ($try_server, $spare_server, $lowest_load) = @_;
  703: 
  704:     my $loadans     = &reply('load',    $try_server);
  705:     my $userloadans = &reply('userload',$try_server);
  706: 
  707:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  708: 	next; #didn't get a number from the server
  709:     }
  710: 
  711:     my $load;
  712:     if ($loadans =~ /\d/) {
  713: 	if ($userloadans =~ /\d/) {
  714: 	    #both are numbers, pick the bigger one
  715: 	    $load = ($loadans > $userloadans) ? $loadans 
  716: 		                              : $userloadans;
  717: 	} else {
  718: 	    $load = $loadans;
  719: 	}
  720:     } else {
  721: 	$load = $userloadans;
  722:     }
  723: 
  724:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  725: 	$spare_server = $try_server;
  726: 	$lowest_load  = $load;
  727:     }
  728:     return ($spare_server,$lowest_load);
  729: }
  730: 
  731: # --------------------------- ask offload servers if user already has a session
  732: sub find_existing_session {
  733:     my ($udom,$uname) = @_;
  734:     foreach my $try_server (@{ $spareid{'primary'} },
  735: 			    @{ $spareid{'default'} }) {
  736: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  737:     }
  738:     return;
  739: }
  740: 
  741: # -------------------------------- ask if server already has a session for user
  742: sub has_user_session {
  743:     my ($lonid,$udom,$uname) = @_;
  744:     my $result = &reply(join(':','userhassession',
  745: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  746:     return 1 if ($result eq 'ok');
  747: 
  748:     return 0;
  749: }
  750: 
  751: # --------------------------------------------- Try to change a user's password
  752: 
  753: sub changepass {
  754:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  755:     $currentpass = &escape($currentpass);
  756:     $newpass     = &escape($newpass);
  757:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  758: 		       $server);
  759:     if (! $answer) {
  760: 	&logthis("No reply on password change request to $server ".
  761: 		 "by $uname in domain $udom.");
  762:     } elsif ($answer =~ "^ok") {
  763:         &logthis("$uname in $udom successfully changed their password ".
  764: 		 "on $server.");
  765:     } elsif ($answer =~ "^pwchange_failure") {
  766: 	&logthis("$uname in $udom was unable to change their password ".
  767: 		 "on $server.  The action was blocked by either lcpasswd ".
  768: 		 "or pwchange");
  769:     } elsif ($answer =~ "^non_authorized") {
  770:         &logthis("$uname in $udom did not get their password correct when ".
  771: 		 "attempting to change it on $server.");
  772:     } elsif ($answer =~ "^auth_mode_error") {
  773:         &logthis("$uname in $udom attempted to change their password despite ".
  774: 		 "not being locally or internally authenticated on $server.");
  775:     } elsif ($answer =~ "^unknown_user") {
  776:         &logthis("$uname in $udom attempted to change their password ".
  777: 		 "on $server but were unable to because $server is not ".
  778: 		 "their home server.");
  779:     } elsif ($answer =~ "^refused") {
  780: 	&logthis("$server refused to change $uname in $udom password because ".
  781: 		 "it was sent an unencrypted request to change the password.");
  782:     }
  783:     return $answer;
  784: }
  785: 
  786: # ----------------------- Try to determine user's current authentication scheme
  787: 
  788: sub queryauthenticate {
  789:     my ($uname,$udom)=@_;
  790:     my $uhome=&homeserver($uname,$udom);
  791:     if (!$uhome) {
  792: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  793: 	return 'no_host';
  794:     }
  795:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  796:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  797: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  798:     }
  799:     return $answer;
  800: }
  801: 
  802: # --------- Try to authenticate user from domain's lib servers (first this one)
  803: 
  804: sub authenticate {
  805:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  806:     $upass=&escape($upass);
  807:     $uname= &LONCAPA::clean_username($uname);
  808:     my $uhome=&homeserver($uname,$udom,1);
  809:     my $newhome;
  810:     if ((!$uhome) || ($uhome eq 'no_host')) {
  811: # Maybe the machine was offline and only re-appeared again recently?
  812:         &reconlonc();
  813: # One more
  814: 	$uhome=&homeserver($uname,$udom,1);
  815:         if (($uhome eq 'no_host') && $checkdefauth) {
  816:             if (defined(&domain($udom,'primary'))) {
  817:                 $newhome=&domain($udom,'primary');
  818:             }
  819:             if ($newhome ne '') {
  820:                 $uhome = $newhome;
  821:             }
  822:         }
  823: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  824: 	    &logthis("User $uname at $udom is unknown in authenticate");
  825: 	    return 'no_host';
  826:         }
  827:     }
  828:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  829:     if ($answer eq 'authorized') {
  830:         if ($newhome) {
  831:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  832:             return 'no_account_on_host'; 
  833:         } else {
  834:             &logthis("User $uname at $udom authorized by $uhome");
  835:             return $uhome;
  836:         }
  837:     }
  838:     if ($answer eq 'non_authorized') {
  839: 	&logthis("User $uname at $udom rejected by $uhome");
  840: 	return 'no_host'; 
  841:     }
  842:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  843:     return 'no_host';
  844: }
  845: 
  846: # ---------------------- Find the homebase for a user from domain's lib servers
  847: 
  848: my %homecache;
  849: sub homeserver {
  850:     my ($uname,$udom,$ignoreBadCache)=@_;
  851:     my $index="$uname:$udom";
  852: 
  853:     if (exists($homecache{$index})) { return $homecache{$index}; }
  854: 
  855:     my %servers = &get_servers($udom,'library');
  856:     foreach my $tryserver (keys(%servers)) {
  857:         next if ($ignoreBadCache ne 'true' && 
  858: 		 exists($badServerCache{$tryserver}));
  859: 
  860: 	my $answer=reply("home:$udom:$uname",$tryserver);
  861: 	if ($answer eq 'found') {
  862: 	    delete($badServerCache{$tryserver}); 
  863: 	    return $homecache{$index}=$tryserver;
  864: 	} elsif ($answer eq 'no_host') {
  865: 	    $badServerCache{$tryserver}=1;
  866: 	}
  867:     }    
  868:     return 'no_host';
  869: }
  870: 
  871: # ------------------------------------- Find the usernames behind a list of IDs
  872: 
  873: sub idget {
  874:     my ($udom,@ids)=@_;
  875:     my %returnhash=();
  876:     
  877:     my %servers = &get_servers($udom,'library');
  878:     foreach my $tryserver (keys(%servers)) {
  879: 	my $idlist=join('&',@ids);
  880: 	$idlist=~tr/A-Z/a-z/; 
  881: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  882: 	my @answer=();
  883: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  884: 	    @answer=split(/\&/,$reply);
  885: 	}                    ;
  886: 	my $i;
  887: 	for ($i=0;$i<=$#ids;$i++) {
  888: 	    if ($answer[$i]) {
  889: 		$returnhash{$ids[$i]}=$answer[$i];
  890: 	    } 
  891: 	}
  892:     } 
  893:     return %returnhash;
  894: }
  895: 
  896: # ------------------------------------- Find the IDs behind a list of usernames
  897: 
  898: sub idrget {
  899:     my ($udom,@unames)=@_;
  900:     my %returnhash=();
  901:     foreach my $uname (@unames) {
  902:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  903:     }
  904:     return %returnhash;
  905: }
  906: 
  907: # ------------------------------- Store away a list of names and associated IDs
  908: 
  909: sub idput {
  910:     my ($udom,%ids)=@_;
  911:     my %servers=();
  912:     foreach my $uname (keys(%ids)) {
  913: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  914:         my $uhom=&homeserver($uname,$udom);
  915:         if ($uhom ne 'no_host') {
  916:             my $id=&escape($ids{$uname});
  917:             $id=~tr/A-Z/a-z/;
  918:             my $esc_unam=&escape($uname);
  919: 	    if ($servers{$uhom}) {
  920: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  921:             } else {
  922:                 $servers{$uhom}=$id.'='.$esc_unam;
  923:             }
  924:         }
  925:     }
  926:     foreach my $server (keys(%servers)) {
  927:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  928:     }
  929: }
  930: 
  931: # ------------------------------------------- get items from domain db files   
  932: 
  933: sub get_dom {
  934:     my ($namespace,$storearr,$udom,$uhome)=@_;
  935:     my $items='';
  936:     foreach my $item (@$storearr) {
  937:         $items.=&escape($item).'&';
  938:     }
  939:     $items=~s/\&$//;
  940:     if (!$udom) {
  941:         $udom=$env{'user.domain'};
  942:         if (defined(&domain($udom,'primary'))) {
  943:             $uhome=&domain($udom,'primary');
  944:         } else {
  945:             undef($uhome);
  946:         }
  947:     } else {
  948:         if (!$uhome) {
  949:             if (defined(&domain($udom,'primary'))) {
  950:                 $uhome=&domain($udom,'primary');
  951:             }
  952:         }
  953:     }
  954:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  955:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  956:         my %returnhash;
  957:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  958:             return %returnhash;
  959:         }
  960:         my @pairs=split(/\&/,$rep);
  961:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  962:             return @pairs;
  963:         }
  964:         my $i=0;
  965:         foreach my $item (@$storearr) {
  966:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  967:             $i++;
  968:         }
  969:         return %returnhash;
  970:     } else {
  971:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  972:     }
  973: }
  974: 
  975: # -------------------------------------------- put items in domain db files 
  976: 
  977: sub put_dom {
  978:     my ($namespace,$storehash,$udom,$uhome)=@_;
  979:     if (!$udom) {
  980:         $udom=$env{'user.domain'};
  981:         if (defined(&domain($udom,'primary'))) {
  982:             $uhome=&domain($udom,'primary');
  983:         } else {
  984:             undef($uhome);
  985:         }
  986:     } else {
  987:         if (!$uhome) {
  988:             if (defined(&domain($udom,'primary'))) {
  989:                 $uhome=&domain($udom,'primary');
  990:             }
  991:         }
  992:     } 
  993:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  994:         my $items='';
  995:         foreach my $item (keys(%$storehash)) {
  996:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  997:         }
  998:         $items=~s/\&$//;
  999:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1000:     } else {
 1001:         &logthis("put_dom failed - no homeserver and/or domain");
 1002:     }
 1003: }
 1004: 
 1005: sub retrieve_inst_usertypes {
 1006:     my ($udom) = @_;
 1007:     my (%returnhash,@order);
 1008:     if (defined(&domain($udom,'primary'))) {
 1009:         my $uhome=&domain($udom,'primary');
 1010:         my $rep=&reply("inst_usertypes:$udom",$uhome);
 1011:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1012:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1013:             return (\%returnhash,\@order);
 1014:         }
 1015:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1016:         my @pairs=split(/\&/,$hashitems);
 1017:         foreach my $item (@pairs) {
 1018:             my ($key,$value)=split(/=/,$item,2);
 1019:             $key = &unescape($key);
 1020:             next if ($key =~ /^error: 2 /);
 1021:             $returnhash{$key}=&thaw_unescape($value);
 1022:         }
 1023:         my @esc_order = split(/\&/,$orderitems);
 1024:         foreach my $item (@esc_order) {
 1025:             push(@order,&unescape($item));
 1026:         }
 1027:     } else {
 1028:         &logthis("get_dom failed - no primary domain server for $udom");
 1029:     }
 1030:     return (\%returnhash,\@order);
 1031: }
 1032: 
 1033: sub is_domainimage {
 1034:     my ($url) = @_;
 1035:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1036:         if (&domain($1) ne '') {
 1037:             return '1';
 1038:         }
 1039:     }
 1040:     return;
 1041: }
 1042: 
 1043: sub inst_directory_query {
 1044:     my ($srch) = @_;
 1045:     my $udom = $srch->{'srchdomain'};
 1046:     my %results;
 1047:     my $homeserver = &domain($udom,'primary');
 1048:     my $outcome;
 1049:     if ($homeserver ne '') {
 1050: 	my $queryid=&reply("querysend:instdirsearch:".
 1051: 			   &escape($srch->{'srchby'}).':'.
 1052: 			   &escape($srch->{'srchterm'}).':'.
 1053: 			   &escape($srch->{'srchtype'}),$homeserver);
 1054: 	my $host=&hostname($homeserver);
 1055: 	if ($queryid !~/^\Q$host\E\_/) {
 1056: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1057: 	    return;
 1058: 	}
 1059: 	my $response = &get_query_reply($queryid);
 1060: 	my $maxtries = 5;
 1061: 	my $tries = 1;
 1062: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1063: 	    $response = &get_query_reply($queryid);
 1064: 	    $tries ++;
 1065: 	}
 1066: 
 1067:         if (!&error($response) && $response ne 'refused') {
 1068:             if ($response eq 'unavailable') {
 1069:                 $outcome = $response;
 1070:             } else {
 1071:                 $outcome = 'ok';
 1072:                 my @matches = split(/\n/,$response);
 1073:                 foreach my $match (@matches) {
 1074:                     my ($key,$value) = split(/=/,$match);
 1075:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1076:                 }
 1077:             }
 1078:         }
 1079:     }
 1080:     return ($outcome,%results);
 1081: }
 1082: 
 1083: sub usersearch {
 1084:     my ($srch) = @_;
 1085:     my $dom = $srch->{'srchdomain'};
 1086:     my %results;
 1087:     my %libserv = &all_library();
 1088:     my $query = 'usersearch';
 1089:     foreach my $tryserver (keys(%libserv)) {
 1090:         if (&host_domain($tryserver) eq $dom) {
 1091:             my $host=&hostname($tryserver);
 1092:             my $queryid=
 1093:                 &reply("querysend:".&escape($query).':'.
 1094:                        &escape($srch->{'srchby'}).':'.
 1095:                        &escape($srch->{'srchtype'}).':'.
 1096:                        &escape($srch->{'srchterm'}),$tryserver);
 1097:             if ($queryid !~/^\Q$host\E\_/) {
 1098:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1099:                 next;
 1100:             }
 1101:             my $reply = &get_query_reply($queryid);
 1102:             my $maxtries = 1;
 1103:             my $tries = 1;
 1104:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1105:                 $reply = &get_query_reply($queryid);
 1106:                 $tries ++;
 1107:             }
 1108:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1109:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1110:             } else {
 1111:                 my @matches;
 1112:                 if ($reply =~ /\n/) {
 1113:                     @matches = split(/\n/,$reply);
 1114:                 } else {
 1115:                     @matches = split(/\&/,$reply);
 1116:                 }
 1117:                 foreach my $match (@matches) {
 1118:                     my ($uname,$udom,%userhash);
 1119:                     foreach my $entry (split(/:/,$match)) {
 1120:                         my ($key,$value) =
 1121:                             map {&unescape($_);} split(/=/,$entry);
 1122:                         $userhash{$key} = $value;
 1123:                         if ($key eq 'username') {
 1124:                             $uname = $value;
 1125:                         } elsif ($key eq 'domain') {
 1126:                             $udom = $value;
 1127:                         }
 1128:                     }
 1129:                     $results{$uname.':'.$udom} = \%userhash;
 1130:                 }
 1131:             }
 1132:         }
 1133:     }
 1134:     return %results;
 1135: }
 1136: 
 1137: sub get_instuser {
 1138:     my ($udom,$uname,$id) = @_;
 1139:     my $homeserver = &domain($udom,'primary');
 1140:     my ($outcome,%results);
 1141:     if ($homeserver ne '') {
 1142:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1143:                            &escape($id).':'.&escape($udom),$homeserver);
 1144:         my $host=&hostname($homeserver);
 1145:         if ($queryid !~/^\Q$host\E\_/) {
 1146:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1147:             return;
 1148:         }
 1149:         my $response = &get_query_reply($queryid);
 1150:         my $maxtries = 5;
 1151:         my $tries = 1;
 1152:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1153:             $response = &get_query_reply($queryid);
 1154:             $tries ++;
 1155:         }
 1156:         if (!&error($response) && $response ne 'refused') {
 1157:             if ($response eq 'unavailable') {
 1158:                 $outcome = $response;
 1159:             } else {
 1160:                 $outcome = 'ok';
 1161:                 my @matches = split(/\n/,$response);
 1162:                 foreach my $match (@matches) {
 1163:                     my ($key,$value) = split(/=/,$match);
 1164:                     $results{&unescape($key)} = &thaw_unescape($value);
 1165:                 }
 1166:             }
 1167:         }
 1168:     }
 1169:     my %userinfo;
 1170:     if (ref($results{$uname}) eq 'HASH') {
 1171:         %userinfo = %{$results{$uname}};
 1172:     } 
 1173:     return ($outcome,%userinfo);
 1174: }
 1175: 
 1176: sub inst_rulecheck {
 1177:     my ($udom,$uname,$id,$item,$rules) = @_;
 1178:     my %returnhash;
 1179:     if ($udom ne '') {
 1180:         if (ref($rules) eq 'ARRAY') {
 1181:             @{$rules} = map {&escape($_);} (@{$rules});
 1182:             my $rulestr = join(':',@{$rules});
 1183:             my $homeserver=&domain($udom,'primary');
 1184:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1185:                 my $response;
 1186:                 if ($item eq 'username') {                
 1187:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1188:                                               ':'.&escape($uname).':'.$rulestr,
 1189:                                               $homeserver));
 1190:                 } elsif ($item eq 'id') {
 1191:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1192:                                               ':'.&escape($id).':'.$rulestr,
 1193:                                               $homeserver));
 1194:                 } elsif ($item eq 'selfcreate') {
 1195:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1196:                                                &escape($udom).':'.&escape($uname).
 1197:                                               ':'.$rulestr,$homeserver));
 1198:                 }
 1199:                 if ($response ne 'refused') {
 1200:                     my @pairs=split(/\&/,$response);
 1201:                     foreach my $item (@pairs) {
 1202:                         my ($key,$value)=split(/=/,$item,2);
 1203:                         $key = &unescape($key);
 1204:                         next if ($key =~ /^error: 2 /);
 1205:                         $returnhash{$key}=&thaw_unescape($value);
 1206:                     }
 1207:                 }
 1208:             }
 1209:         }
 1210:     }
 1211:     return %returnhash;
 1212: }
 1213: 
 1214: sub inst_userrules {
 1215:     my ($udom,$check) = @_;
 1216:     my (%ruleshash,@ruleorder);
 1217:     if ($udom ne '') {
 1218:         my $homeserver=&domain($udom,'primary');
 1219:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1220:             my $response;
 1221:             if ($check eq 'id') {
 1222:                 $response=&reply('instidrules:'.&escape($udom),
 1223:                                  $homeserver);
 1224:             } elsif ($check eq 'email') {
 1225:                 $response=&reply('instemailrules:'.&escape($udom),
 1226:                                  $homeserver);
 1227:             } else {
 1228:                 $response=&reply('instuserrules:'.&escape($udom),
 1229:                                  $homeserver);
 1230:             }
 1231:             if (($response ne 'refused') && ($response ne 'error') && 
 1232:                 ($response ne 'unknown_cmd') && 
 1233:                 ($response ne 'no_such_host')) {
 1234:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1235:                 my @pairs=split(/\&/,$hashitems);
 1236:                 foreach my $item (@pairs) {
 1237:                     my ($key,$value)=split(/=/,$item,2);
 1238:                     $key = &unescape($key);
 1239:                     next if ($key =~ /^error: 2 /);
 1240:                     $ruleshash{$key}=&thaw_unescape($value);
 1241:                 }
 1242:                 my @esc_order = split(/\&/,$orderitems);
 1243:                 foreach my $item (@esc_order) {
 1244:                     push(@ruleorder,&unescape($item));
 1245:                 }
 1246:             }
 1247:         }
 1248:     }
 1249:     return (\%ruleshash,\@ruleorder);
 1250: }
 1251: 
 1252: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1253: 
 1254: sub get_domain_defaults {
 1255:     my ($domain) = @_;
 1256:     my $cachetime = 60*60*24;
 1257:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1258:     if (defined($cached)) {
 1259:         if (ref($result) eq 'HASH') {
 1260:             return %{$result};
 1261:         }
 1262:     }
 1263:     my %domdefaults;
 1264:     my %domconfig =
 1265:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1266:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1267:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1268:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1269:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1270:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1271:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1272:     } else {
 1273:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1274:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1275:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1276:     }
 1277:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1278:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1279:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1280:         } else {
 1281:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1282:         } 
 1283:         my @usertools = ('aboutme','blog','portfolio');
 1284:         foreach my $item (@usertools) {
 1285:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1286:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1287:             }
 1288:         }
 1289:     }
 1290:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1291:         foreach my $item ('official','unofficial') {
 1292:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1293:         }
 1294:     }
 1295:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1296:                                   $cachetime);
 1297:     return %domdefaults;
 1298: }
 1299: 
 1300: # --------------------------------------------------- Assign a key to a student
 1301: 
 1302: sub assign_access_key {
 1303: #
 1304: # a valid key looks like uname:udom#comments
 1305: # comments are being appended
 1306: #
 1307:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1308:     $kdom=
 1309:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1310:     $knum=
 1311:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1312:     $cdom=
 1313:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1314:     $cnum=
 1315:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1316:     $udom=$env{'user.name'} unless (defined($udom));
 1317:     $uname=$env{'user.domain'} unless (defined($uname));
 1318:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1319:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1320:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1321:                                                   # assigned to this person
 1322:                                                   # - this should not happen,
 1323:                                                   # unless something went wrong
 1324:                                                   # the first time around
 1325: # ready to assign
 1326:         $logentry=$1.'; '.$logentry;
 1327:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1328:                                                  $kdom,$knum) eq 'ok') {
 1329: # key now belongs to user
 1330: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1331:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1332:                 &appenv({'environment.'.$envkey => $ckey});
 1333:                 return 'ok';
 1334:             } else {
 1335:                 return 
 1336:   'error: Count not permanently assign key, will need to be re-entered later.';
 1337: 	    }
 1338:         } else {
 1339:             return 'error: Could not assign key, try again later.';
 1340:         }
 1341:     } elsif (!$existing{$ckey}) {
 1342: # the key does not exist
 1343: 	return 'error: The key does not exist';
 1344:     } else {
 1345: # the key is somebody else's
 1346: 	return 'error: The key is already in use';
 1347:     }
 1348: }
 1349: 
 1350: # ------------------------------------------ put an additional comment on a key
 1351: 
 1352: sub comment_access_key {
 1353: #
 1354: # a valid key looks like uname:udom#comments
 1355: # comments are being appended
 1356: #
 1357:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1358:     $cdom=
 1359:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1360:     $cnum=
 1361:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1362:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1363:     if ($existing{$ckey}) {
 1364:         $existing{$ckey}.='; '.$logentry;
 1365: # ready to assign
 1366:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1367:                                                  $cdom,$cnum) eq 'ok') {
 1368: 	    return 'ok';
 1369:         } else {
 1370: 	    return 'error: Count not store comment.';
 1371:         }
 1372:     } else {
 1373: # the key does not exist
 1374: 	return 'error: The key does not exist';
 1375:     }
 1376: }
 1377: 
 1378: # ------------------------------------------------------ Generate a set of keys
 1379: 
 1380: sub generate_access_keys {
 1381:     my ($number,$cdom,$cnum,$logentry)=@_;
 1382:     $cdom=
 1383:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1384:     $cnum=
 1385:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1386:     unless (&allowed('mky',$cdom)) { return 0; }
 1387:     unless (($cdom) && ($cnum)) { return 0; }
 1388:     if ($number>10000) { return 0; }
 1389:     sleep(2); # make sure don't get same seed twice
 1390:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1391:     my $total=0;
 1392:     for (my $i=1;$i<=$number;$i++) {
 1393:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1394:                   sprintf("%lx",int(100000*rand)).'-'.
 1395:                   sprintf("%lx",int(100000*rand));
 1396:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1397:        $newkey=~s/0/h/g; # and also 0 and O
 1398:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1399:        if ($existing{$newkey}) {
 1400:            $i--;
 1401:        } else {
 1402: 	  if (&put('accesskeys',
 1403:               { $newkey => '# generated '.localtime().
 1404:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1405:                            '; '.$logentry },
 1406: 		   $cdom,$cnum) eq 'ok') {
 1407:               $total++;
 1408: 	  }
 1409:        }
 1410:     }
 1411:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1412:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1413:     return $total;
 1414: }
 1415: 
 1416: # ------------------------------------------------------- Validate an accesskey
 1417: 
 1418: sub validate_access_key {
 1419:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1420:     $cdom=
 1421:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1422:     $cnum=
 1423:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1424:     $udom=$env{'user.domain'} unless (defined($udom));
 1425:     $uname=$env{'user.name'} unless (defined($uname));
 1426:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1427:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1428: }
 1429: 
 1430: # ------------------------------------- Find the section of student in a course
 1431: sub devalidate_getsection_cache {
 1432:     my ($udom,$unam,$courseid)=@_;
 1433:     my $hashid="$udom:$unam:$courseid";
 1434:     &devalidate_cache_new('getsection',$hashid);
 1435: }
 1436: 
 1437: sub courseid_to_courseurl {
 1438:     my ($courseid) = @_;
 1439:     #already url style courseid
 1440:     return $courseid if ($courseid =~ m{^/});
 1441: 
 1442:     if (exists($env{'course.'.$courseid.'.num'})) {
 1443: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1444: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1445: 	return "/$cdom/$cnum";
 1446:     }
 1447: 
 1448:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1449:     if (exists($courseinfo{'num'})) {
 1450: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1451:     }
 1452: 
 1453:     return undef;
 1454: }
 1455: 
 1456: sub getsection {
 1457:     my ($udom,$unam,$courseid)=@_;
 1458:     my $cachetime=1800;
 1459: 
 1460:     my $hashid="$udom:$unam:$courseid";
 1461:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1462:     if (defined($cached)) { return $result; }
 1463: 
 1464:     my %Pending; 
 1465:     my %Expired;
 1466:     #
 1467:     # Each role can either have not started yet (pending), be active, 
 1468:     #    or have expired.
 1469:     #
 1470:     # If there is an active role, we are done.
 1471:     #
 1472:     # If there is more than one role which has not started yet, 
 1473:     #     choose the one which will start sooner
 1474:     # If there is one role which has not started yet, return it.
 1475:     #
 1476:     # If there is more than one expired role, choose the one which ended last.
 1477:     # If there is a role which has expired, return it.
 1478:     #
 1479:     $courseid = &courseid_to_courseurl($courseid);
 1480:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1481:     foreach my $key (keys(%roleshash)) {
 1482:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1483:         my $section=$1;
 1484:         if ($key eq $courseid.'_st') { $section=''; }
 1485:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1486:         my $now=time;
 1487:         if (defined($end) && $end && ($now > $end)) {
 1488:             $Expired{$end}=$section;
 1489:             next;
 1490:         }
 1491:         if (defined($start) && $start && ($now < $start)) {
 1492:             $Pending{$start}=$section;
 1493:             next;
 1494:         }
 1495:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1496:     }
 1497:     #
 1498:     # Presumedly there will be few matching roles from the above
 1499:     # loop and the sorting time will be negligible.
 1500:     if (scalar(keys(%Pending))) {
 1501:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1502:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1503:     } 
 1504:     if (scalar(keys(%Expired))) {
 1505:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1506:         my $time = pop(@sorted);
 1507:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1508:     }
 1509:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1510: }
 1511: 
 1512: sub save_cache {
 1513:     &purge_remembered();
 1514:     #&Apache::loncommon::validate_page();
 1515:     undef(%env);
 1516:     undef($env_loaded);
 1517: }
 1518: 
 1519: my $to_remember=-1;
 1520: my %remembered;
 1521: my %accessed;
 1522: my $kicks=0;
 1523: my $hits=0;
 1524: sub make_key {
 1525:     my ($name,$id) = @_;
 1526:     if (length($id) > 65 
 1527: 	&& length(&escape($id)) > 200) {
 1528: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1529:     }
 1530:     return &escape($name.':'.$id);
 1531: }
 1532: 
 1533: sub devalidate_cache_new {
 1534:     my ($name,$id,$debug) = @_;
 1535:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1536:     $id=&make_key($name,$id);
 1537:     $memcache->delete($id);
 1538:     delete($remembered{$id});
 1539:     delete($accessed{$id});
 1540: }
 1541: 
 1542: sub is_cached_new {
 1543:     my ($name,$id,$debug) = @_;
 1544:     $id=&make_key($name,$id);
 1545:     if (exists($remembered{$id})) {
 1546: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1547: 	$accessed{$id}=[&gettimeofday()];
 1548: 	$hits++;
 1549: 	return ($remembered{$id},1);
 1550:     }
 1551:     my $value = $memcache->get($id);
 1552:     if (!(defined($value))) {
 1553: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1554: 	return (undef,undef);
 1555:     }
 1556:     if ($value eq '__undef__') {
 1557: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1558: 	$value=undef;
 1559:     }
 1560:     &make_room($id,$value,$debug);
 1561:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1562:     return ($value,1);
 1563: }
 1564: 
 1565: sub do_cache_new {
 1566:     my ($name,$id,$value,$time,$debug) = @_;
 1567:     $id=&make_key($name,$id);
 1568:     my $setvalue=$value;
 1569:     if (!defined($setvalue)) {
 1570: 	$setvalue='__undef__';
 1571:     }
 1572:     if (!defined($time) ) {
 1573: 	$time=600;
 1574:     }
 1575:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1576:     my $result = $memcache->set($id,$setvalue,$time);
 1577:     if (! $result) {
 1578: 	&logthis("caching of id -> $id  failed");
 1579: 	$memcache->disconnect_all();
 1580:     }
 1581:     # need to make a copy of $value
 1582:     &make_room($id,$value,$debug);
 1583:     return $value;
 1584: }
 1585: 
 1586: sub make_room {
 1587:     my ($id,$value,$debug)=@_;
 1588: 
 1589:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1590:                                     : $value;
 1591:     if ($to_remember<0) { return; }
 1592:     $accessed{$id}=[&gettimeofday()];
 1593:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1594:     my $to_kick;
 1595:     my $max_time=0;
 1596:     foreach my $other (keys(%accessed)) {
 1597: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1598: 	    $to_kick=$other;
 1599: 	    $max_time=&tv_interval($accessed{$other});
 1600: 	}
 1601:     }
 1602:     delete($remembered{$to_kick});
 1603:     delete($accessed{$to_kick});
 1604:     $kicks++;
 1605:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1606:     return;
 1607: }
 1608: 
 1609: sub purge_remembered {
 1610:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1611:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1612:     undef(%remembered);
 1613:     undef(%accessed);
 1614: }
 1615: # ------------------------------------- Read an entry from a user's environment
 1616: 
 1617: sub userenvironment {
 1618:     my ($udom,$unam,@what)=@_;
 1619:     my $items;
 1620:     foreach my $item (@what) {
 1621:         $items.=&escape($item).'&';
 1622:     }
 1623:     $items=~s/\&$//;
 1624:     my %returnhash=();
 1625:     my @answer=split(/\&/,
 1626:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1627:                       &homeserver($unam,$udom)));
 1628:     my $i;
 1629:     for ($i=0;$i<=$#what;$i++) {
 1630: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1631:     }
 1632:     return %returnhash;
 1633: }
 1634: 
 1635: # ---------------------------------------------------------- Get a studentphoto
 1636: sub studentphoto {
 1637:     my ($udom,$unam,$ext) = @_;
 1638:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1639:     if (defined($env{'request.course.id'})) {
 1640:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1641:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1642:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1643:             } else {
 1644:                 my ($result,$perm_reqd)=
 1645: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1646:                 if ($result eq 'ok') {
 1647:                     if (!($perm_reqd eq 'yes')) {
 1648:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1649:                     }
 1650:                 }
 1651:             }
 1652:         }
 1653:     } else {
 1654:         my ($result,$perm_reqd) = 
 1655: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1656:         if ($result eq 'ok') {
 1657:             if (!($perm_reqd eq 'yes')) {
 1658:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1659:             }
 1660:         }
 1661:     }
 1662:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1663: }
 1664: 
 1665: sub retrievestudentphoto {
 1666:     my ($udom,$unam,$ext,$type) = @_;
 1667:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1668:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1669:     if ($ret eq 'ok') {
 1670:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1671:         if ($type eq 'thumbnail') {
 1672:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1673:         }
 1674:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1675:         return $tokenurl;
 1676:     } else {
 1677:         if ($type eq 'thumbnail') {
 1678:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1679:         } else { 
 1680:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1681:         }
 1682:     }
 1683: }
 1684: 
 1685: # -------------------------------------------------------------------- New chat
 1686: 
 1687: sub chatsend {
 1688:     my ($newentry,$anon,$group)=@_;
 1689:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1690:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1691:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1692:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1693: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1694: 		   &escape($newentry)).':'.$group,$chome);
 1695: }
 1696: 
 1697: # ------------------------------------------ Find current version of a resource
 1698: 
 1699: sub getversion {
 1700:     my $fname=&clutter(shift);
 1701:     unless ($fname=~/^\/res\//) { return -1; }
 1702:     return &currentversion(&filelocation('',$fname));
 1703: }
 1704: 
 1705: sub currentversion {
 1706:     my $fname=shift;
 1707:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1708:     if (defined($cached)) { return $result; }
 1709:     my $author=$fname;
 1710:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1711:     my ($udom,$uname)=split(/\//,$author);
 1712:     my $home=homeserver($uname,$udom);
 1713:     if ($home eq 'no_host') { 
 1714:         return -1; 
 1715:     }
 1716:     my $answer=reply("currentversion:$fname",$home);
 1717:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1718: 	return -1;
 1719:     }
 1720:     return &do_cache_new('resversion',$fname,$answer,600);
 1721: }
 1722: 
 1723: # ----------------------------- Subscribe to a resource, return URL if possible
 1724: 
 1725: sub subscribe {
 1726:     my $fname=shift;
 1727:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1728:     $fname=~s/[\n\r]//g;
 1729:     my $author=$fname;
 1730:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1731:     my ($udom,$uname)=split(/\//,$author);
 1732:     my $home=homeserver($uname,$udom);
 1733:     if ($home eq 'no_host') {
 1734:         return 'not_found';
 1735:     }
 1736:     my $answer=reply("sub:$fname",$home);
 1737:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1738: 	$answer.=' by '.$home;
 1739:     }
 1740:     return $answer;
 1741: }
 1742:     
 1743: # -------------------------------------------------------------- Replicate file
 1744: 
 1745: sub repcopy {
 1746:     my $filename=shift;
 1747:     $filename=~s/\/+/\//g;
 1748:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1749:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1750:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1751: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1752: 	return &repcopy_userfile($filename);
 1753:     }
 1754:     $filename=~s/[\n\r]//g;
 1755:     my $transname="$filename.in.transfer";
 1756: # FIXME: this should flock
 1757:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1758:     my $remoteurl=subscribe($filename);
 1759:     if ($remoteurl =~ /^con_lost by/) {
 1760: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1761:            return 'unavailable';
 1762:     } elsif ($remoteurl eq 'not_found') {
 1763: 	   #&logthis("Subscribe returned not_found: $filename");
 1764: 	   return 'not_found';
 1765:     } elsif ($remoteurl =~ /^rejected by/) {
 1766: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1767:            return 'forbidden';
 1768:     } elsif ($remoteurl eq 'directory') {
 1769:            return 'ok';
 1770:     } else {
 1771:         my $author=$filename;
 1772:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1773:         my ($udom,$uname)=split(/\//,$author);
 1774:         my $home=homeserver($uname,$udom);
 1775:         unless ($home eq $perlvar{'lonHostID'}) {
 1776:            my @parts=split(/\//,$filename);
 1777:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1778:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1779:                &logthis("Malconfiguration for replication: $filename");
 1780: 	       return 'bad_request';
 1781:            }
 1782:            my $count;
 1783:            for ($count=5;$count<$#parts;$count++) {
 1784:                $path.="/$parts[$count]";
 1785:                if ((-e $path)!=1) {
 1786: 		   mkdir($path,0777);
 1787:                }
 1788:            }
 1789:            my $ua=new LWP::UserAgent;
 1790:            my $request=new HTTP::Request('GET',"$remoteurl");
 1791:            my $response=$ua->request($request,$transname);
 1792:            if ($response->is_error()) {
 1793: 	       unlink($transname);
 1794:                my $message=$response->status_line;
 1795:                &logthis("<font color=\"blue\">WARNING:"
 1796:                        ." LWP get: $message: $filename</font>");
 1797:                return 'unavailable';
 1798:            } else {
 1799: 	       if ($remoteurl!~/\.meta$/) {
 1800:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1801:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1802:                   if ($mresponse->is_error()) {
 1803: 		      unlink($filename.'.meta');
 1804:                       &logthis(
 1805:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1806:                   }
 1807: 	       }
 1808:                rename($transname,$filename);
 1809:                return 'ok';
 1810:            }
 1811:        }
 1812:     }
 1813: }
 1814: 
 1815: # ------------------------------------------------ Get server side include body
 1816: sub ssi_body {
 1817:     my ($filelink,%form)=@_;
 1818:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1819:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1820:     }
 1821:     my $output='';
 1822:     my $response;
 1823:     if ($filelink=~/^https?\:/) {
 1824:        ($output,$response)=&externalssi($filelink);
 1825:     } else {
 1826:        ($output,$response)=&ssi($filelink,%form);
 1827:     }
 1828:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1829:     $output=~s/^.*?\<body[^\>]*\>//si;
 1830:     $output=~s/\<\/body\s*\>.*?$//si;
 1831:     if (wantarray) {
 1832:         return ($output, $response);
 1833:     } else {
 1834:         return $output;
 1835:     }
 1836: }
 1837: 
 1838: # --------------------------------------------------------- Server Side Include
 1839: 
 1840: sub absolute_url {
 1841:     my ($host_name) = @_;
 1842:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1843:     if ($host_name eq '') {
 1844: 	$host_name = $ENV{'SERVER_NAME'};
 1845:     }
 1846:     return $protocol.$host_name;
 1847: }
 1848: 
 1849: #
 1850: #   Server side include.
 1851: # Parameters:
 1852: #  fn     Possibly encrypted resource name/id.
 1853: #  form   Hash that describes how the rendering should be done
 1854: #         and other things.
 1855: # Returns:
 1856: #   Scalar context: The content of the response.
 1857: #   Array context:  2 element list of the content and the full response object.
 1858: #     
 1859: sub ssi {
 1860: 
 1861:     my ($fn,%form)=@_;
 1862:     my $ua=new LWP::UserAgent;
 1863:     my $request;
 1864: 
 1865:     $form{'no_update_last_known'}=1;
 1866:     &Apache::lonenc::check_encrypt(\$fn);
 1867:     if (%form) {
 1868:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1869:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1870:     } else {
 1871:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1872:     }
 1873: 
 1874:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1875:     my $response=$ua->request($request);
 1876: 
 1877:     if (wantarray) {
 1878: 	return ($response->content, $response);
 1879:     } else {
 1880: 	return $response->content;
 1881:     }
 1882: }
 1883: 
 1884: sub externalssi {
 1885:     my ($url)=@_;
 1886:     my $ua=new LWP::UserAgent;
 1887:     my $request=new HTTP::Request('GET',$url);
 1888:     my $response=$ua->request($request);
 1889:     if (wantarray) {
 1890:         return ($response->content, $response);
 1891:     } else {
 1892:         return $response->content;
 1893:     }
 1894: }
 1895: 
 1896: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1897: 
 1898: sub allowuploaded {
 1899:     my ($srcurl,$url)=@_;
 1900:     $url=&clutter(&declutter($url));
 1901:     my $dir=$url;
 1902:     $dir=~s/\/[^\/]+$//;
 1903:     my %httpref=();
 1904:     my $httpurl=&hreflocation('',$url);
 1905:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1906:     &Apache::lonnet::appenv(\%httpref);
 1907: }
 1908: 
 1909: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1910: # input: action, courseID, current domain, intended
 1911: #        path to file, source of file, instruction to parse file for objects,
 1912: #        ref to hash for embedded objects,
 1913: #        ref to hash for codebase of java objects.
 1914: #
 1915: # output: url to file (if action was uploaddoc), 
 1916: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1917: #
 1918: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1919: # course.
 1920: #
 1921: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1922: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1923: #          course's home server.
 1924: #
 1925: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1926: #          be copied from $source (current location) to 
 1927: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1928: #         and will then be copied to
 1929: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1930: #         course's home server.
 1931: #
 1932: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1933: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1934: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1935: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1936: #         in course's home server.
 1937: #
 1938: 
 1939: sub process_coursefile {
 1940:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1941:     my $fetchresult;
 1942:     my $home=&homeserver($docuname,$docudom);
 1943:     if ($action eq 'propagate') {
 1944:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1945: 			     $home);
 1946:     } else {
 1947:         my $fpath = '';
 1948:         my $fname = $file;
 1949:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1950:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1951:         my $filepath = &build_filepath($fpath);
 1952:         if ($action eq 'copy') {
 1953:             if ($source eq '') {
 1954:                 $fetchresult = 'no source file';
 1955:                 return $fetchresult;
 1956:             } else {
 1957:                 my $destination = $filepath.'/'.$fname;
 1958:                 rename($source,$destination);
 1959:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1960:                                  $home);
 1961:             }
 1962:         } elsif ($action eq 'uploaddoc') {
 1963:             open(my $fh,'>'.$filepath.'/'.$fname);
 1964:             print $fh $env{'form.'.$source};
 1965:             close($fh);
 1966:             if ($parser eq 'parse') {
 1967:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1968:                 unless ($parse_result eq 'ok') {
 1969:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1970:                 }
 1971:             }
 1972:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1973:                                  $home);
 1974:             if ($fetchresult eq 'ok') {
 1975:                 return '/uploaded/'.$fpath.'/'.$fname;
 1976:             } else {
 1977:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1978:                         ' to host '.$home.': '.$fetchresult);
 1979:                 return '/adm/notfound.html';
 1980:             }
 1981:         }
 1982:     }
 1983:     unless ( $fetchresult eq 'ok') {
 1984:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1985:              ' to host '.$home.': '.$fetchresult);
 1986:     }
 1987:     return $fetchresult;
 1988: }
 1989: 
 1990: sub build_filepath {
 1991:     my ($fpath) = @_;
 1992:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1993:     unless ($fpath eq '') {
 1994:         my @parts=split('/',$fpath);
 1995:         foreach my $part (@parts) {
 1996:             $filepath.= '/'.$part;
 1997:             if ((-e $filepath)!=1) {
 1998:                 mkdir($filepath,0777);
 1999:             }
 2000:         }
 2001:     }
 2002:     return $filepath;
 2003: }
 2004: 
 2005: sub store_edited_file {
 2006:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2007:     my $file = $primary_url;
 2008:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2009:     my $fpath = '';
 2010:     my $fname = $file;
 2011:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2012:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2013:     my $filepath = &build_filepath($fpath);
 2014:     open(my $fh,'>'.$filepath.'/'.$fname);
 2015:     print $fh $content;
 2016:     close($fh);
 2017:     my $home=&homeserver($docuname,$docudom);
 2018:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2019: 			  $home);
 2020:     if ($$fetchresult eq 'ok') {
 2021:         return '/uploaded/'.$fpath.'/'.$fname;
 2022:     } else {
 2023:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2024: 		 ' to host '.$home.': '.$$fetchresult);
 2025:         return '/adm/notfound.html';
 2026:     }
 2027: }
 2028: 
 2029: sub clean_filename {
 2030:     my ($fname,$args)=@_;
 2031: # Replace Windows backslashes by forward slashes
 2032:     $fname=~s/\\/\//g;
 2033:     if (!$args->{'keep_path'}) {
 2034:         # Get rid of everything but the actual filename
 2035: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2036:     }
 2037: # Replace spaces by underscores
 2038:     $fname=~s/\s+/\_/g;
 2039: # Replace all other weird characters by nothing
 2040:     $fname=~s{[^/\w\.\-]}{}g;
 2041: # Replace all .\d. sequences with _\d. so they no longer look like version
 2042: # numbers
 2043:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2044:     return $fname;
 2045: }
 2046: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2047: sub resizeImage {
 2048: 	my($img_url) = @_;	
 2049: 	my $ima = Image::Magick->new;                       
 2050:         $ima->Read($img_url);
 2051: 	if($ima->Get('width') > 400)
 2052: 	{
 2053: 		my $factor = $ima->Get('width')/400;
 2054:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2055: 	}
 2056: 	if($ima->Get('height') > 500)
 2057:         {
 2058:         	my $factor = $ima->Get('height')/500;
 2059:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2060:         } 
 2061: 		
 2062: 	$ima->Write($img_url);
 2063: }
 2064: 
 2065: #Wrapper function for userphotoupload
 2066: sub userphotoupload
 2067: {
 2068: 	my($formname,$subdir) = @_;
 2069: 	$upload_photo_form = 1;
 2070: 	return &userfileupload($formname,undef,$subdir);
 2071: }
 2072: 
 2073: # --------------- Take an uploaded file and put it into the userfiles directory
 2074: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2075: #                    the desired filenam is in $env{"form.$formname.filename"}
 2076: #        $coursedoc - if true up to the current course
 2077: #                     if false
 2078: #        $subdir - directory in userfile to store the file into
 2079: #        $parser - instruction to parse file for objects ($parser = parse)    
 2080: #        $allfiles - reference to hash for embedded objects
 2081: #        $codebase - reference to hash for codebase of java objects
 2082: #        $desuname - username for permanent storage of uploaded file
 2083: #        $dsetudom - domain for permanaent storage of uploaded file
 2084: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2085: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2086: # 
 2087: # output: url of file in userspace, or error: <message> 
 2088: #             or /adm/notfound.html if failure to upload occurse
 2089: 
 2090: 
 2091: sub userfileupload {
 2092:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2093:         $destudom,$thumbwidth,$thumbheight)=@_;
 2094:     if (!defined($subdir)) { $subdir='unknown'; }
 2095:     my $fname=$env{'form.'.$formname.'.filename'};
 2096:     $fname=&clean_filename($fname);
 2097: # See if there is anything left
 2098:     unless ($fname) { return 'error: no uploaded file'; }
 2099:     chop($env{'form.'.$formname});
 2100:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2101:         my $now = time;
 2102:         my $filepath = 'tmp/helprequests/'.$now;
 2103:         my @parts=split(/\//,$filepath);
 2104:         my $fullpath = $perlvar{'lonDaemons'};
 2105:         for (my $i=0;$i<@parts;$i++) {
 2106:             $fullpath .= '/'.$parts[$i];
 2107:             if ((-e $fullpath)!=1) {
 2108:                 mkdir($fullpath,0777);
 2109:             }
 2110:         }
 2111:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2112:         print $fh $env{'form.'.$formname};
 2113:         close($fh);
 2114:         return $fullpath.'/'.$fname;
 2115:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2116:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2117:                        '_'.$env{'user.domain'}.'/pending';
 2118:         my @parts=split(/\//,$filepath);
 2119:         my $fullpath = $perlvar{'lonDaemons'};
 2120:         for (my $i=0;$i<@parts;$i++) {
 2121:             $fullpath .= '/'.$parts[$i];
 2122:             if ((-e $fullpath)!=1) {
 2123:                 mkdir($fullpath,0777);
 2124:             }
 2125:         }
 2126:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2127:         print $fh $env{'form.'.$formname};
 2128:         close($fh);
 2129:         return $fullpath.'/'.$fname;
 2130:     }
 2131:     
 2132: # Create the directory if not present
 2133:     $fname="$subdir/$fname";
 2134:     if ($coursedoc) {
 2135: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2136: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2137:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2138:             return &finishuserfileupload($docuname,$docudom,
 2139: 					 $formname,$fname,$parser,$allfiles,
 2140: 					 $codebase,$thumbwidth,$thumbheight);
 2141:         } else {
 2142:             $fname=$env{'form.folder'}.'/'.$fname;
 2143:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2144: 				       $fname,$formname,$parser,
 2145: 				       $allfiles,$codebase);
 2146:         }
 2147:     } elsif (defined($destuname)) {
 2148:         my $docuname=$destuname;
 2149:         my $docudom=$destudom;
 2150: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2151: 				     $parser,$allfiles,$codebase,
 2152:                                      $thumbwidth,$thumbheight);
 2153:         
 2154:     } else {
 2155:         my $docuname=$env{'user.name'};
 2156:         my $docudom=$env{'user.domain'};
 2157:         if (exists($env{'form.group'})) {
 2158:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2159:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2160:         }
 2161: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2162: 				     $parser,$allfiles,$codebase,
 2163:                                      $thumbwidth,$thumbheight);
 2164:     }
 2165: }
 2166: 
 2167: sub finishuserfileupload {
 2168:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2169:         $thumbwidth,$thumbheight) = @_;
 2170:     my $path=$docudom.'/'.$docuname.'/';
 2171:     my $filepath=$perlvar{'lonDocRoot'};
 2172:   
 2173:     my ($fnamepath,$file,$fetchthumb);
 2174:     $file=$fname;
 2175:     if ($fname=~m|/|) {
 2176:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2177: 	$path.=$fnamepath.'/';
 2178:     }
 2179:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2180:     my $count;
 2181:     for ($count=4;$count<=$#parts;$count++) {
 2182:         $filepath.="/$parts[$count]";
 2183:         if ((-e $filepath)!=1) {
 2184: 	    mkdir($filepath,0777);
 2185:         }
 2186:     }
 2187: 
 2188: # Save the file
 2189:     {
 2190: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2191: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2192: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2193: 	    return '/adm/notfound.html';
 2194: 	}
 2195: 	if (!print FH ($env{'form.'.$formname})) {
 2196: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2197: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2198: 	    return '/adm/notfound.html';
 2199: 	}
 2200: 	close(FH);
 2201: 	if($upload_photo_form==1)
 2202: 	{
 2203: 		resizeImage($filepath.'/'.$file);		
 2204: 		$upload_photo_form = 0;
 2205: 	}
 2206:     }
 2207:     if ($parser eq 'parse') {
 2208:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2209: 						   $codebase);
 2210:         unless ($parse_result eq 'ok') {
 2211:             &logthis('Failed to parse '.$filepath.$file.
 2212: 		     ' for embedded media: '.$parse_result); 
 2213:         }
 2214:     }
 2215:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2216:         my $input = $filepath.'/'.$file;
 2217:         my $output = $filepath.'/'.'tn-'.$file;
 2218:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2219:         system("convert -sample $thumbsize $input $output");
 2220:         if (-e $filepath.'/'.'tn-'.$file) {
 2221:             $fetchthumb  = 1; 
 2222:         }
 2223:     }
 2224:  
 2225: # Notify homeserver to grep it
 2226: #
 2227:     my $docuhome=&homeserver($docuname,$docudom);	
 2228:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2229:     if ($fetchresult eq 'ok') {
 2230:         if ($fetchthumb) {
 2231:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2232:             if ($thumbresult ne 'ok') {
 2233:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2234:                          $docuhome.': '.$thumbresult);
 2235:             }
 2236:         }
 2237: #
 2238: # Return the URL to it
 2239:         return '/uploaded/'.$path.$file;
 2240:     } else {
 2241:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2242: 		 ': '.$fetchresult);
 2243:         return '/adm/notfound.html';
 2244:     }
 2245: }
 2246: 
 2247: sub extract_embedded_items {
 2248:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2249:     my @state = ();
 2250:     my %javafiles = (
 2251:                       codebase => '',
 2252:                       code => '',
 2253:                       archive => ''
 2254:                     );
 2255:     my %mediafiles = (
 2256:                       src => '',
 2257:                       movie => '',
 2258:                      );
 2259:     my $p;
 2260:     if ($content) {
 2261:         $p = HTML::LCParser->new($content);
 2262:     } else {
 2263:         $p = HTML::LCParser->new($fullpath);
 2264:     }
 2265:     while (my $t=$p->get_token()) {
 2266: 	if ($t->[0] eq 'S') {
 2267: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2268: 	    push(@state, $tagname);
 2269:             if (lc($tagname) eq 'allow') {
 2270:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2271:             }
 2272: 	    if (lc($tagname) eq 'img') {
 2273: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2274: 	    }
 2275: 	    if (lc($tagname) eq 'a') {
 2276: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2277: 	    }
 2278:             if (lc($tagname) eq 'script') {
 2279:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2280:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2281:                 } else {
 2282:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2283:                 }
 2284:             }
 2285:             if (lc($tagname) eq 'link') {
 2286:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2287:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2288:                 }
 2289:             }
 2290: 	    if (lc($tagname) eq 'object' ||
 2291: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2292: 		foreach my $item (keys(%javafiles)) {
 2293: 		    $javafiles{$item} = '';
 2294: 		}
 2295: 	    }
 2296: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2297: 		my $name = lc($attr->{'name'});
 2298: 		foreach my $item (keys(%javafiles)) {
 2299: 		    if ($name eq $item) {
 2300: 			$javafiles{$item} = $attr->{'value'};
 2301: 			last;
 2302: 		    }
 2303: 		}
 2304: 		foreach my $item (keys(%mediafiles)) {
 2305: 		    if ($name eq $item) {
 2306: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2307: 			last;
 2308: 		    }
 2309: 		}
 2310: 	    }
 2311: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2312: 		foreach my $item (keys(%javafiles)) {
 2313: 		    if ($attr->{$item}) {
 2314: 			$javafiles{$item} = $attr->{$item};
 2315: 			last;
 2316: 		    }
 2317: 		}
 2318: 		foreach my $item (keys(%mediafiles)) {
 2319: 		    if ($attr->{$item}) {
 2320: 			&add_filetype($allfiles,$attr->{$item},$item);
 2321: 			last;
 2322: 		    }
 2323: 		}
 2324: 	    }
 2325: 	} elsif ($t->[0] eq 'E') {
 2326: 	    my ($tagname) = ($t->[1]);
 2327: 	    if ($javafiles{'codebase'} ne '') {
 2328: 		$javafiles{'codebase'} .= '/';
 2329: 	    }  
 2330: 	    if (lc($tagname) eq 'applet' ||
 2331: 		lc($tagname) eq 'object' ||
 2332: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2333: 		) {
 2334: 		foreach my $item (keys(%javafiles)) {
 2335: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2336: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2337: 			&add_filetype($allfiles,$file,$item);
 2338: 		    }
 2339: 		}
 2340: 	    } 
 2341: 	    pop @state;
 2342: 	}
 2343:     }
 2344:     return 'ok';
 2345: }
 2346: 
 2347: sub add_filetype {
 2348:     my ($allfiles,$file,$type)=@_;
 2349:     if (exists($allfiles->{$file})) {
 2350: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2351: 	    push(@{$allfiles->{$file}}, &escape($type));
 2352: 	}
 2353:     } else {
 2354: 	@{$allfiles->{$file}} = (&escape($type));
 2355:     }
 2356: }
 2357: 
 2358: sub removeuploadedurl {
 2359:     my ($url)=@_;	
 2360:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2361:     return &removeuserfile($uname,$udom,$fname);
 2362: }
 2363: 
 2364: sub removeuserfile {
 2365:     my ($docuname,$docudom,$fname)=@_;
 2366:     my $home=&homeserver($docuname,$docudom);    
 2367:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2368:     if ($result eq 'ok') {	
 2369:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2370:             my $metafile = $fname.'.meta';
 2371:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2372: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2373:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2374:             my $sqlresult = 
 2375:                 &update_portfolio_table($docuname,$docudom,$file,
 2376:                                         'portfolio_metadata',$group,
 2377:                                         'delete');
 2378:         }
 2379:     }
 2380:     return $result;
 2381: }
 2382: 
 2383: sub mkdiruserfile {
 2384:     my ($docuname,$docudom,$dir)=@_;
 2385:     my $home=&homeserver($docuname,$docudom);
 2386:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2387: }
 2388: 
 2389: sub renameuserfile {
 2390:     my ($docuname,$docudom,$old,$new)=@_;
 2391:     my $home=&homeserver($docuname,$docudom);
 2392:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2393:                         &escape("$old").':'.&escape("$new"),$home);
 2394:     if ($result eq 'ok') {
 2395:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2396:             my $oldmeta = $old.'.meta';
 2397:             my $newmeta = $new.'.meta';
 2398:             my $metaresult = 
 2399:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2400: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2401:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2402:             my $sqlresult = 
 2403:                 &update_portfolio_table($docuname,$docudom,$file,
 2404:                                         'portfolio_metadata',$group,
 2405:                                         'delete');
 2406:         }
 2407:     }
 2408:     return $result;
 2409: }
 2410: 
 2411: # ------------------------------------------------------------------------- Log
 2412: 
 2413: sub log {
 2414:     my ($dom,$nam,$hom,$what)=@_;
 2415:     return critical("log:$dom:$nam:$what",$hom);
 2416: }
 2417: 
 2418: # ------------------------------------------------------------------ Course Log
 2419: #
 2420: # This routine flushes several buffers of non-mission-critical nature
 2421: #
 2422: 
 2423: sub flushcourselogs {
 2424:     &logthis('Flushing log buffers');
 2425: #
 2426: # course logs
 2427: # This is a log of all transactions in a course, which can be used
 2428: # for data mining purposes
 2429: #
 2430: # It also collects the courseid database, which lists last transaction
 2431: # times and course titles for all courseids
 2432: #
 2433:     my %courseidbuffer=();
 2434:     foreach my $crsid (keys(%courselogs)) {
 2435:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2436: 		          &escape($courselogs{$crsid}),
 2437: 		          $coursehombuf{$crsid}) eq 'ok') {
 2438: 	    delete $courselogs{$crsid};
 2439:         } else {
 2440:             &logthis('Failed to flush log buffer for '.$crsid);
 2441:             if (length($courselogs{$crsid})>40000) {
 2442:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2443:                         " exceeded maximum size, deleting.</font>");
 2444:                delete $courselogs{$crsid};
 2445:             }
 2446:         }
 2447:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2448:             'description' => $coursedescrbuf{$crsid},
 2449:             'inst_code'    => $courseinstcodebuf{$crsid},
 2450:             'type'        => $coursetypebuf{$crsid},
 2451:             'owner'       => $courseownerbuf{$crsid},
 2452:         };
 2453:     }
 2454: #
 2455: # Write course id database (reverse lookup) to homeserver of courses 
 2456: # Is used in pickcourse
 2457: #
 2458:     foreach my $crs_home (keys(%courseidbuffer)) {
 2459:         my $response = &courseidput(&host_domain($crs_home),
 2460:                                     $courseidbuffer{$crs_home},
 2461:                                     $crs_home,'timeonly');
 2462:     }
 2463: #
 2464: # File accesses
 2465: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2466: #
 2467:     foreach my $entry (keys(%accesshash)) {
 2468:         if ($entry =~ /___count$/) {
 2469:             my ($dom,$name);
 2470:             ($dom,$name,undef)=
 2471: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2472:             if (! defined($dom) || $dom eq '' || 
 2473:                 ! defined($name) || $name eq '') {
 2474:                 my $cid = $env{'request.course.id'};
 2475:                 $dom  = $env{'request.'.$cid.'.domain'};
 2476:                 $name = $env{'request.'.$cid.'.num'};
 2477:             }
 2478:             my $value = $accesshash{$entry};
 2479:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2480:             my %temphash=($url => $value);
 2481:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2482:             if ($result eq 'ok') {
 2483:                 delete $accesshash{$entry};
 2484:             } elsif ($result eq 'unknown_cmd') {
 2485:                 # Target server has old code running on it.
 2486:                 my %temphash=($entry => $value);
 2487:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2488:                     delete $accesshash{$entry};
 2489:                 }
 2490:             }
 2491:         } else {
 2492:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2493:             my %temphash=($entry => $accesshash{$entry});
 2494:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2495:                 delete $accesshash{$entry};
 2496:             }
 2497:         }
 2498:     }
 2499: #
 2500: # Roles
 2501: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2502: #
 2503:     foreach my $entry (keys(%userrolehash)) {
 2504:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2505: 	    split(/\:/,$entry);
 2506:         if (&Apache::lonnet::put('nohist_userroles',
 2507:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2508:                 $rudom,$runame) eq 'ok') {
 2509: 	    delete $userrolehash{$entry};
 2510:         }
 2511:     }
 2512: #
 2513: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2514: #
 2515:     my %domrolebuffer = ();
 2516:     foreach my $entry (keys %domainrolehash) {
 2517:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2518:         if ($domrolebuffer{$rudom}) {
 2519:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2520:                       '='.&escape($domainrolehash{$entry});
 2521:         } else {
 2522:             $domrolebuffer{$rudom}.=&escape($entry).
 2523:                       '='.&escape($domainrolehash{$entry});
 2524:         }
 2525:         delete $domainrolehash{$entry};
 2526:     }
 2527:     foreach my $dom (keys(%domrolebuffer)) {
 2528: 	my %servers = &get_servers($dom,'library');
 2529: 	foreach my $tryserver (keys(%servers)) {
 2530: 	    unless (&reply('domroleput:'.$dom.':'.
 2531: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2532: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2533: 	    }
 2534:         }
 2535:     }
 2536:     $dumpcount++;
 2537: }
 2538: 
 2539: sub courselog {
 2540:     my $what=shift;
 2541:     $what=time.':'.$what;
 2542:     unless ($env{'request.course.id'}) { return ''; }
 2543:     $coursedombuf{$env{'request.course.id'}}=
 2544:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2545:     $coursenumbuf{$env{'request.course.id'}}=
 2546:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2547:     $coursehombuf{$env{'request.course.id'}}=
 2548:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2549:     $coursedescrbuf{$env{'request.course.id'}}=
 2550:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2551:     $courseinstcodebuf{$env{'request.course.id'}}=
 2552:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2553:     $courseownerbuf{$env{'request.course.id'}}=
 2554:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2555:     $coursetypebuf{$env{'request.course.id'}}=
 2556:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2557:     if (defined $courselogs{$env{'request.course.id'}}) {
 2558: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2559:     } else {
 2560: 	$courselogs{$env{'request.course.id'}}.=$what;
 2561:     }
 2562:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2563: 	&flushcourselogs();
 2564:     }
 2565: }
 2566: 
 2567: sub courseacclog {
 2568:     my $fnsymb=shift;
 2569:     unless ($env{'request.course.id'}) { return ''; }
 2570:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2571:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2572:         $what.=':POST';
 2573:         # FIXME: Probably ought to escape things....
 2574: 	foreach my $key (keys(%env)) {
 2575:             if ($key=~/^form\.(.*)/) {
 2576:                 my $formitem = $1;
 2577:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2578:                     $what.=':'.$formitem.'='.$env{$key};
 2579:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2580:                     $what.=':'.$formitem.'='.$env{$key};
 2581:                 }
 2582:             }
 2583:         }
 2584:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2585:         # FIXME: We should not be depending on a form parameter that someone
 2586:         # editing lonsearchcat.pm might change in the future.
 2587:         if ($env{'form.phase'} eq 'course_search') {
 2588:             $what.= ':POST';
 2589:             # FIXME: Probably ought to escape things....
 2590:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2591:                                  'crsdiscuss') {
 2592:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2593:             }
 2594:         }
 2595:     }
 2596:     &courselog($what);
 2597: }
 2598: 
 2599: sub countacc {
 2600:     my $url=&declutter(shift);
 2601:     return if (! defined($url) || $url eq '');
 2602:     unless ($env{'request.course.id'}) { return ''; }
 2603:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2604:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2605:     $accesshash{$key}++;
 2606: }
 2607: 
 2608: sub linklog {
 2609:     my ($from,$to)=@_;
 2610:     $from=&declutter($from);
 2611:     $to=&declutter($to);
 2612:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2613:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2614: }
 2615:   
 2616: sub userrolelog {
 2617:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2618:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2619:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2620:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2621:         ($trole=~/^ta/)) {
 2622:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2623:        $userrolehash
 2624:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2625:                     =$tend.':'.$tstart;
 2626:     }
 2627:     if (($env{'request.role'} =~ /dc\./) &&
 2628: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2629: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2630: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2631:        $userrolehash
 2632:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2633:                     =$tend.':'.$tstart;
 2634:     }
 2635:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2636:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2637:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2638:         ($trole=~/^sc/)) {
 2639:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2640:        $domainrolehash
 2641:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2642:                     = $tend.':'.$tstart;
 2643:     }
 2644: }
 2645: 
 2646: sub courserolelog {
 2647:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2648:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2649:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2650:         ($trole eq 'ta') || ($trole eq 'st') ||
 2651:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2652:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2653:             my $cdom = $1;
 2654:             my $cnum = $2;
 2655:             my $sec = $3;
 2656:             my $namespace = 'rolelog';
 2657:             my %storehash = (
 2658:                                role    => $trole,
 2659:                                start   => $tstart,
 2660:                                end     => $tend,
 2661:                                selfenroll => $selfenroll,
 2662:                                context    => $context,
 2663:                             );
 2664:             if ($trole eq 'gr') {
 2665:                 $namespace = 'groupslog';
 2666:                 $storehash{'group'} = $sec;
 2667:             } else {
 2668:                 $storehash{'section'} = $sec;
 2669:             }
 2670:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2671:         }
 2672:     }
 2673:     return;
 2674: }
 2675: 
 2676: sub get_course_adv_roles {
 2677:     my ($cid,$codes) = @_;
 2678:     $cid=$env{'request.course.id'} unless (defined($cid));
 2679:     my %coursehash=&coursedescription($cid);
 2680:     my %nothide=();
 2681:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2682:         if ($user !~ /:/) {
 2683: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2684:         } else {
 2685:             $nothide{$user}=1;
 2686:         }
 2687:     }
 2688:     my %returnhash=();
 2689:     my %dumphash=
 2690:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2691:     my $now=time;
 2692:     foreach my $entry (keys %dumphash) {
 2693: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2694:         if (($tstart) && ($tstart<0)) { next; }
 2695:         if (($tend) && ($tend<$now)) { next; }
 2696:         if (($tstart) && ($now<$tstart)) { next; }
 2697:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2698: 	if ($username eq '' || $domain eq '') { next; }
 2699: 	if ((&privileged($username,$domain)) && 
 2700: 	    (!$nothide{$username.':'.$domain})) { next; }
 2701: 	if ($role eq 'cr') { next; }
 2702:         if ($codes) {
 2703:             if ($section) { $role .= ':'.$section; }
 2704:             if ($returnhash{$role}) {
 2705:                 $returnhash{$role}.=','.$username.':'.$domain;
 2706:             } else {
 2707:                 $returnhash{$role}=$username.':'.$domain;
 2708:             }
 2709:         } else {
 2710:             my $key=&plaintext($role);
 2711:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2712:             if ($returnhash{$key}) {
 2713: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2714:             } else {
 2715:                 $returnhash{$key}=$username.':'.$domain;
 2716:             }
 2717:         }
 2718:     }
 2719:     return %returnhash;
 2720: }
 2721: 
 2722: sub get_my_roles {
 2723:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2724:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2725:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2726:     my (%dumphash,%nothide);
 2727:     if ($context eq 'userroles') { 
 2728:         %dumphash = &dump('roles',$udom,$uname);
 2729:     } else {
 2730:         %dumphash=
 2731:             &dump('nohist_userroles',$udom,$uname);
 2732:         if ($hidepriv) {
 2733:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2734:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2735:                 if ($user !~ /:/) {
 2736:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2737:                 } else {
 2738:                     $nothide{$user} = 1;
 2739:                 }
 2740:             }
 2741:         }
 2742:     }
 2743:     my %returnhash=();
 2744:     my $now=time;
 2745:     foreach my $entry (keys(%dumphash)) {
 2746:         my ($role,$tend,$tstart);
 2747:         if ($context eq 'userroles') {
 2748: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2749:         } else {
 2750:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2751:         }
 2752:         if (($tstart) && ($tstart<0)) { next; }
 2753:         my $status = 'active';
 2754:         if (($tend) && ($tend<=$now)) {
 2755:             $status = 'previous';
 2756:         } 
 2757:         if (($tstart) && ($now<$tstart)) {
 2758:             $status = 'future';
 2759:         }
 2760:         if (ref($types) eq 'ARRAY') {
 2761:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2762:                 next;
 2763:             } 
 2764:         } else {
 2765:             if ($status ne 'active') {
 2766:                 next;
 2767:             }
 2768:         }
 2769:         my ($rolecode,$username,$domain,$section,$area);
 2770:         if ($context eq 'userroles') {
 2771:             ($area,$rolecode) = split(/_/,$entry);
 2772:             (undef,$domain,$username,$section) = split(/\//,$area);
 2773:         } else {
 2774:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2775:         }
 2776:         if (ref($roledoms) eq 'ARRAY') {
 2777:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2778:                 next;
 2779:             }
 2780:         }
 2781:         if (ref($roles) eq 'ARRAY') {
 2782:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2783:                 if ($role =~ /^cr\//) {
 2784:                     if (!grep(/^cr$/,@{$roles})) {
 2785:                         next;
 2786:                     }
 2787:                 } else {
 2788:                     next;
 2789:                 }
 2790:             }
 2791:         }
 2792:         if ($hidepriv) {
 2793:             if ((&privileged($username,$domain)) &&
 2794:                 (!$nothide{$username.':'.$domain})) { 
 2795:                 next;
 2796:             }
 2797:         }
 2798:         if ($withsec) {
 2799:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2800:                 $tstart.':'.$tend;
 2801:         } else {
 2802:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2803:         }
 2804:     }
 2805:     return %returnhash;
 2806: }
 2807: 
 2808: # ----------------------------------------------------- Frontpage Announcements
 2809: #
 2810: #
 2811: 
 2812: sub postannounce {
 2813:     my ($server,$text)=@_;
 2814:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2815:     unless ($text=~/\w/) { $text=''; }
 2816:     return &reply('setannounce:'.&escape($text),$server);
 2817: }
 2818: 
 2819: sub getannounce {
 2820: 
 2821:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2822: 	my $announcement='';
 2823: 	while (my $line = <$fh>) { $announcement .= $line; }
 2824: 	close($fh);
 2825: 	if ($announcement=~/\w/) { 
 2826: 	    return 
 2827:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2828:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2829: 	} else {
 2830: 	    return '';
 2831: 	}
 2832:     } else {
 2833: 	return '';
 2834:     }
 2835: }
 2836: 
 2837: # ---------------------------------------------------------- Course ID routines
 2838: # Deal with domain's nohist_courseid.db files
 2839: #
 2840: 
 2841: sub courseidput {
 2842:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2843:     my $outcome;
 2844:     if ($caller eq 'timeonly') {
 2845:         my $cids = '';
 2846:         foreach my $item (keys(%$storehash)) {
 2847:             $cids.=&escape($item).'&';
 2848:         }
 2849:         $cids=~s/\&$//;
 2850:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2851:                           $coursehome);       
 2852:     } else {
 2853:         my $items = '';
 2854:         foreach my $item (keys(%$storehash)) {
 2855:             $items.= &escape($item).'='.
 2856:                      &freeze_escape($$storehash{$item}).'&';
 2857:         }
 2858:         $items=~s/\&$//;
 2859:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2860:                           $coursehome);
 2861:     }
 2862:     if ($outcome eq 'unknown_cmd') {
 2863:         my $what;
 2864:         foreach my $cid (keys(%$storehash)) {
 2865:             $what .= &escape($cid).'=';
 2866:             foreach my $item ('description','inst_code','owner','type') {
 2867:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2868:             }
 2869:             $what =~ s/\:$/&/;
 2870:         }
 2871:         $what =~ s/\&$//;  
 2872:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2873:     } else {
 2874:         return $outcome;
 2875:     }
 2876: }
 2877: 
 2878: sub courseiddump {
 2879:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2880:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2881:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2882:     my $as_hash = 1;
 2883:     my %returnhash;
 2884:     if (!$domfilter) { $domfilter=''; }
 2885:     my %libserv = &all_library();
 2886:     foreach my $tryserver (keys(%libserv)) {
 2887:         if ( (  $hostidflag == 1 
 2888: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2889: 	     || (!defined($hostidflag)) ) {
 2890: 
 2891: 	    if (($domfilter eq '') ||
 2892: 		(&host_domain($tryserver) eq $domfilter)) {
 2893:                 my $rep = 
 2894:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2895:                          $sincefilter.':'.&escape($descfilter).':'.
 2896:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2897:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2898:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2899:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2900:                          $showhidden.':'.$caller,$tryserver);
 2901:                 my @pairs=split(/\&/,$rep);
 2902:                 foreach my $item (@pairs) {
 2903:                     my ($key,$value)=split(/\=/,$item,2);
 2904:                     $key = &unescape($key);
 2905:                     next if ($key =~ /^error: 2 /);
 2906:                     my $result = &thaw_unescape($value);
 2907:                     if (ref($result) eq 'HASH') {
 2908:                         $returnhash{$key}=$result;
 2909:                     } else {
 2910:                         my @responses = split(/:/,$value);
 2911:                         my @items = ('description','inst_code','owner','type');
 2912:                         for (my $i=0; $i<@responses; $i++) {
 2913:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2914:                         }
 2915:                     } 
 2916:                 }
 2917:             }
 2918:         }
 2919:     }
 2920:     return %returnhash;
 2921: }
 2922: 
 2923: # ---------------------------------------------------------- DC e-mail
 2924: 
 2925: sub dcmailput {
 2926:     my ($domain,$msgid,$message,$server)=@_;
 2927:     my $status = &Apache::lonnet::critical(
 2928:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2929:        &escape($message),$server);
 2930:     return $status;
 2931: }
 2932: 
 2933: sub dcmaildump {
 2934:     my ($dom,$startdate,$enddate,$senders) = @_;
 2935:     my %returnhash=();
 2936: 
 2937:     if (defined(&domain($dom,'primary'))) {
 2938:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2939:                                                          &escape($enddate).':';
 2940: 	my @esc_senders=map { &escape($_)} @$senders;
 2941: 	$cmd.=&escape(join('&',@esc_senders));
 2942: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2943:             my ($key,$value) = split(/\=/,$line,2);
 2944:             if (($key) && ($value)) {
 2945:                 $returnhash{&unescape($key)} = &unescape($value);
 2946:             }
 2947:         }
 2948:     }
 2949:     return %returnhash;
 2950: }
 2951: # ---------------------------------------------------------- Domain roles
 2952: 
 2953: sub get_domain_roles {
 2954:     my ($dom,$roles,$startdate,$enddate)=@_;
 2955:     if (undef($startdate) || $startdate eq '') {
 2956:         $startdate = '.';
 2957:     }
 2958:     if (undef($enddate) || $enddate eq '') {
 2959:         $enddate = '.';
 2960:     }
 2961:     my $rolelist;
 2962:     if (ref($roles) eq 'ARRAY') {
 2963:         $rolelist = join(':',@{$roles});
 2964:     }
 2965:     my %personnel = ();
 2966: 
 2967:     my %servers = &get_servers($dom,'library');
 2968:     foreach my $tryserver (keys(%servers)) {
 2969: 	%{$personnel{$tryserver}}=();
 2970: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2971: 					    &escape($startdate).':'.
 2972: 					    &escape($enddate).':'.
 2973: 					    &escape($rolelist), $tryserver))) {
 2974: 	    my ($key,$value) = split(/\=/,$line,2);
 2975: 	    if (($key) && ($value)) {
 2976: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2977: 	    }
 2978: 	}
 2979:     }
 2980:     return %personnel;
 2981: }
 2982: 
 2983: # ----------------------------------------------------------- Check out an item
 2984: 
 2985: sub get_first_access {
 2986:     my ($type,$argsymb)=@_;
 2987:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2988:     if ($argsymb) { $symb=$argsymb; }
 2989:     my ($map,$id,$res)=&decode_symb($symb);
 2990:     if ($type eq 'course') {
 2991: 	$res='course';
 2992:     } elsif ($type eq 'map') {
 2993: 	$res=&symbread($map);
 2994:     } else {
 2995: 	$res=$symb;
 2996:     }
 2997:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2998:     return $times{"$courseid\0$res"};
 2999: }
 3000: 
 3001: sub set_first_access {
 3002:     my ($type)=@_;
 3003:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3004:     my ($map,$id,$res)=&decode_symb($symb);
 3005:     if ($type eq 'course') {
 3006: 	$res='course';
 3007:     } elsif ($type eq 'map') {
 3008: 	$res=&symbread($map);
 3009:     } else {
 3010: 	$res=$symb;
 3011:     }
 3012:     my $firstaccess=&get_first_access($type,$symb);
 3013:     if (!$firstaccess) {
 3014: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3015:     }
 3016:     return 'already_set';
 3017: }
 3018: 
 3019: sub checkout {
 3020:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3021:     my $now=time;
 3022:     my $lonhost=$perlvar{'lonHostID'};
 3023:     my $infostr=&escape(
 3024:                  'CHECKOUTTOKEN&'.
 3025:                  $tuname.'&'.
 3026:                  $tudom.'&'.
 3027:                  $tcrsid.'&'.
 3028:                  $symb.'&'.
 3029: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3030:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3031:     if ($token=~/^error\:/) { 
 3032:         &logthis("<font color=\"blue\">WARNING: ".
 3033:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3034:                  "</font>");
 3035:         return ''; 
 3036:     }
 3037: 
 3038:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3039:     $token=~tr/a-z/A-Z/;
 3040: 
 3041:     my %infohash=('resource.0.outtoken' => $token,
 3042:                   'resource.0.checkouttime' => $now,
 3043:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3044: 
 3045:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3046:        return '';
 3047:     } else {
 3048:         &logthis("<font color=\"blue\">WARNING: ".
 3049:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3050:                  "</font>");
 3051:     }    
 3052: 
 3053:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3054:                          &escape('Checkout '.$infostr.' - '.
 3055:                                                  $token)) ne 'ok') {
 3056: 	return '';
 3057:     } else {
 3058:         &logthis("<font color=\"blue\">WARNING: ".
 3059:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3060:                  "</font>");
 3061:     }
 3062:     return $token;
 3063: }
 3064: 
 3065: # ------------------------------------------------------------ Check in an item
 3066: 
 3067: sub checkin {
 3068:     my $token=shift;
 3069:     my $now=time;
 3070:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3071:     $lonhost=~tr/A-Z/a-z/;
 3072:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3073:     $dtoken=~s/\W/\_/g;
 3074:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3075:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3076: 
 3077:     unless (($tuname) && ($tudom)) {
 3078:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3079:         return '';
 3080:     }
 3081:     
 3082:     unless (&allowed('mgr',$tcrsid)) {
 3083:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3084:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3085:         return '';
 3086:     }
 3087: 
 3088:     my %infohash=('resource.0.intoken' => $token,
 3089:                   'resource.0.checkintime' => $now,
 3090:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3091: 
 3092:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3093:        return '';
 3094:     }    
 3095: 
 3096:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3097:                          &escape('Checkin - '.$token)) ne 'ok') {
 3098: 	return '';
 3099:     }
 3100: 
 3101:     return ($symb,$tuname,$tudom,$tcrsid);    
 3102: }
 3103: 
 3104: # --------------------------------------------- Set Expire Date for Spreadsheet
 3105: 
 3106: sub expirespread {
 3107:     my ($uname,$udom,$stype,$usymb)=@_;
 3108:     my $cid=$env{'request.course.id'}; 
 3109:     if ($cid) {
 3110:        my $now=time;
 3111:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3112:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3113:                             $env{'course.'.$cid.'.num'}.
 3114: 	        	    ':nohist_expirationdates:'.
 3115:                             &escape($key).'='.$now,
 3116:                             $env{'course.'.$cid.'.home'})
 3117:     }
 3118:     return 'ok';
 3119: }
 3120: 
 3121: # ----------------------------------------------------- Devalidate Spreadsheets
 3122: 
 3123: sub devalidate {
 3124:     my ($symb,$uname,$udom)=@_;
 3125:     my $cid=$env{'request.course.id'}; 
 3126:     if ($cid) {
 3127:         # delete the stored spreadsheets for
 3128:         # - the student level sheet of this user in course's homespace
 3129:         # - the assessment level sheet for this resource 
 3130:         #   for this user in user's homespace
 3131: 	# - current conditional state info
 3132: 	my $key=$uname.':'.$udom.':';
 3133:         my $status=
 3134: 	    &del('nohist_calculatedsheets',
 3135: 		 [$key.'studentcalc:'],
 3136: 		 $env{'course.'.$cid.'.domain'},
 3137: 		 $env{'course.'.$cid.'.num'})
 3138: 		.' '.
 3139: 	    &del('nohist_calculatedsheets_'.$cid,
 3140: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3141:         unless ($status eq 'ok ok') {
 3142:            &logthis('Could not devalidate spreadsheet '.
 3143:                     $uname.' at '.$udom.' for '.
 3144: 		    $symb.': '.$status);
 3145:         }
 3146: 	&delenv('user.state.'.$cid);
 3147:     }
 3148: }
 3149: 
 3150: sub get_scalar {
 3151:     my ($string,$end) = @_;
 3152:     my $value;
 3153:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3154: 	$value = $1;
 3155:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3156: 	$value = $1;
 3157:     }
 3158:     return &unescape($value);
 3159: }
 3160: 
 3161: sub array2str {
 3162:   my (@array) = @_;
 3163:   my $result=&arrayref2str(\@array);
 3164:   $result=~s/^__ARRAY_REF__//;
 3165:   $result=~s/__END_ARRAY_REF__$//;
 3166:   return $result;
 3167: }
 3168: 
 3169: sub arrayref2str {
 3170:   my ($arrayref) = @_;
 3171:   my $result='__ARRAY_REF__';
 3172:   foreach my $elem (@$arrayref) {
 3173:     if(ref($elem) eq 'ARRAY') {
 3174:       $result.=&arrayref2str($elem).'&';
 3175:     } elsif(ref($elem) eq 'HASH') {
 3176:       $result.=&hashref2str($elem).'&';
 3177:     } elsif(ref($elem)) {
 3178:       #print("Got a ref of ".(ref($elem))." skipping.");
 3179:     } else {
 3180:       $result.=&escape($elem).'&';
 3181:     }
 3182:   }
 3183:   $result=~s/\&$//;
 3184:   $result .= '__END_ARRAY_REF__';
 3185:   return $result;
 3186: }
 3187: 
 3188: sub hash2str {
 3189:   my (%hash) = @_;
 3190:   my $result=&hashref2str(\%hash);
 3191:   $result=~s/^__HASH_REF__//;
 3192:   $result=~s/__END_HASH_REF__$//;
 3193:   return $result;
 3194: }
 3195: 
 3196: sub hashref2str {
 3197:   my ($hashref)=@_;
 3198:   my $result='__HASH_REF__';
 3199:   foreach my $key (sort(keys(%$hashref))) {
 3200:     if (ref($key) eq 'ARRAY') {
 3201:       $result.=&arrayref2str($key).'=';
 3202:     } elsif (ref($key) eq 'HASH') {
 3203:       $result.=&hashref2str($key).'=';
 3204:     } elsif (ref($key)) {
 3205:       $result.='=';
 3206:       #print("Got a ref of ".(ref($key))." skipping.");
 3207:     } else {
 3208: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3209:     }
 3210: 
 3211:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3212:       $result.=&arrayref2str($hashref->{$key}).'&';
 3213:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3214:       $result.=&hashref2str($hashref->{$key}).'&';
 3215:     } elsif(ref($hashref->{$key})) {
 3216:        $result.='&';
 3217:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3218:     } else {
 3219:       $result.=&escape($hashref->{$key}).'&';
 3220:     }
 3221:   }
 3222:   $result=~s/\&$//;
 3223:   $result .= '__END_HASH_REF__';
 3224:   return $result;
 3225: }
 3226: 
 3227: sub str2hash {
 3228:     my ($string)=@_;
 3229:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3230:     return %$hash;
 3231: }
 3232: 
 3233: sub str2hashref {
 3234:   my ($string) = @_;
 3235: 
 3236:   my %hash;
 3237: 
 3238:   if($string !~ /^__HASH_REF__/) {
 3239:       if (! ($string eq '' || !defined($string))) {
 3240: 	  $hash{'error'}='Not hash reference';
 3241:       }
 3242:       return (\%hash, $string);
 3243:   }
 3244: 
 3245:   $string =~ s/^__HASH_REF__//;
 3246: 
 3247:   while($string !~ /^__END_HASH_REF__/) {
 3248:       #key
 3249:       my $key='';
 3250:       if($string =~ /^__HASH_REF__/) {
 3251:           ($key, $string)=&str2hashref($string);
 3252:           if(defined($key->{'error'})) {
 3253:               $hash{'error'}='Bad data';
 3254:               return (\%hash, $string);
 3255:           }
 3256:       } elsif($string =~ /^__ARRAY_REF__/) {
 3257:           ($key, $string)=&str2arrayref($string);
 3258:           if($key->[0] eq 'Array reference error') {
 3259:               $hash{'error'}='Bad data';
 3260:               return (\%hash, $string);
 3261:           }
 3262:       } else {
 3263:           $string =~ s/^(.*?)=//;
 3264: 	  $key=&unescape($1);
 3265:       }
 3266:       $string =~ s/^=//;
 3267: 
 3268:       #value
 3269:       my $value='';
 3270:       if($string =~ /^__HASH_REF__/) {
 3271:           ($value, $string)=&str2hashref($string);
 3272:           if(defined($value->{'error'})) {
 3273:               $hash{'error'}='Bad data';
 3274:               return (\%hash, $string);
 3275:           }
 3276:       } elsif($string =~ /^__ARRAY_REF__/) {
 3277:           ($value, $string)=&str2arrayref($string);
 3278:           if($value->[0] eq 'Array reference error') {
 3279:               $hash{'error'}='Bad data';
 3280:               return (\%hash, $string);
 3281:           }
 3282:       } else {
 3283: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3284:       }
 3285:       $string =~ s/^&//;
 3286: 
 3287:       $hash{$key}=$value;
 3288:   }
 3289: 
 3290:   $string =~ s/^__END_HASH_REF__//;
 3291: 
 3292:   return (\%hash, $string);
 3293: }
 3294: 
 3295: sub str2array {
 3296:     my ($string)=@_;
 3297:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3298:     return @$array;
 3299: }
 3300: 
 3301: sub str2arrayref {
 3302:   my ($string) = @_;
 3303:   my @array;
 3304: 
 3305:   if($string !~ /^__ARRAY_REF__/) {
 3306:       if (! ($string eq '' || !defined($string))) {
 3307: 	  $array[0]='Array reference error';
 3308:       }
 3309:       return (\@array, $string);
 3310:   }
 3311: 
 3312:   $string =~ s/^__ARRAY_REF__//;
 3313: 
 3314:   while($string !~ /^__END_ARRAY_REF__/) {
 3315:       my $value='';
 3316:       if($string =~ /^__HASH_REF__/) {
 3317:           ($value, $string)=&str2hashref($string);
 3318:           if(defined($value->{'error'})) {
 3319:               $array[0] ='Array reference error';
 3320:               return (\@array, $string);
 3321:           }
 3322:       } elsif($string =~ /^__ARRAY_REF__/) {
 3323:           ($value, $string)=&str2arrayref($string);
 3324:           if($value->[0] eq 'Array reference error') {
 3325:               $array[0] ='Array reference error';
 3326:               return (\@array, $string);
 3327:           }
 3328:       } else {
 3329: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3330:       }
 3331:       $string =~ s/^&//;
 3332: 
 3333:       push(@array, $value);
 3334:   }
 3335: 
 3336:   $string =~ s/^__END_ARRAY_REF__//;
 3337: 
 3338:   return (\@array, $string);
 3339: }
 3340: 
 3341: # -------------------------------------------------------------------Temp Store
 3342: 
 3343: sub tmpreset {
 3344:   my ($symb,$namespace,$domain,$stuname) = @_;
 3345:   if (!$symb) {
 3346:     $symb=&symbread();
 3347:     if (!$symb) { $symb= $env{'request.url'}; }
 3348:   }
 3349:   $symb=escape($symb);
 3350: 
 3351:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3352:   $namespace=~s/\//\_/g;
 3353:   $namespace=~s/\W//g;
 3354: 
 3355:   if (!$domain) { $domain=$env{'user.domain'}; }
 3356:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3357:   if ($domain eq 'public' && $stuname eq 'public') {
 3358:       $stuname=$ENV{'REMOTE_ADDR'};
 3359:   }
 3360:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3361:   my %hash;
 3362:   if (tie(%hash,'GDBM_File',
 3363: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3364: 	  &GDBM_WRCREAT(),0640)) {
 3365:     foreach my $key (keys %hash) {
 3366:       if ($key=~ /:$symb/) {
 3367: 	delete($hash{$key});
 3368:       }
 3369:     }
 3370:   }
 3371: }
 3372: 
 3373: sub tmpstore {
 3374:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3375: 
 3376:   if (!$symb) {
 3377:     $symb=&symbread();
 3378:     if (!$symb) { $symb= $env{'request.url'}; }
 3379:   }
 3380:   $symb=escape($symb);
 3381: 
 3382:   if (!$namespace) {
 3383:     # I don't think we would ever want to store this for a course.
 3384:     # it seems this will only be used if we don't have a course.
 3385:     #$namespace=$env{'request.course.id'};
 3386:     #if (!$namespace) {
 3387:       $namespace=$env{'request.state'};
 3388:     #}
 3389:   }
 3390:   $namespace=~s/\//\_/g;
 3391:   $namespace=~s/\W//g;
 3392:   if (!$domain) { $domain=$env{'user.domain'}; }
 3393:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3394:   if ($domain eq 'public' && $stuname eq 'public') {
 3395:       $stuname=$ENV{'REMOTE_ADDR'};
 3396:   }
 3397:   my $now=time;
 3398:   my %hash;
 3399:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3400:   if (tie(%hash,'GDBM_File',
 3401: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3402: 	  &GDBM_WRCREAT(),0640)) {
 3403:     $hash{"version:$symb"}++;
 3404:     my $version=$hash{"version:$symb"};
 3405:     my $allkeys=''; 
 3406:     foreach my $key (keys(%$storehash)) {
 3407:       $allkeys.=$key.':';
 3408:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3409:     }
 3410:     $hash{"$version:$symb:timestamp"}=$now;
 3411:     $allkeys.='timestamp';
 3412:     $hash{"$version:keys:$symb"}=$allkeys;
 3413:     if (untie(%hash)) {
 3414:       return 'ok';
 3415:     } else {
 3416:       return "error:$!";
 3417:     }
 3418:   } else {
 3419:     return "error:$!";
 3420:   }
 3421: }
 3422: 
 3423: # -----------------------------------------------------------------Temp Restore
 3424: 
 3425: sub tmprestore {
 3426:   my ($symb,$namespace,$domain,$stuname) = @_;
 3427: 
 3428:   if (!$symb) {
 3429:     $symb=&symbread();
 3430:     if (!$symb) { $symb= $env{'request.url'}; }
 3431:   }
 3432:   $symb=escape($symb);
 3433: 
 3434:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3435: 
 3436:   if (!$domain) { $domain=$env{'user.domain'}; }
 3437:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3438:   if ($domain eq 'public' && $stuname eq 'public') {
 3439:       $stuname=$ENV{'REMOTE_ADDR'};
 3440:   }
 3441:   my %returnhash;
 3442:   $namespace=~s/\//\_/g;
 3443:   $namespace=~s/\W//g;
 3444:   my %hash;
 3445:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3446:   if (tie(%hash,'GDBM_File',
 3447: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3448: 	  &GDBM_READER(),0640)) {
 3449:     my $version=$hash{"version:$symb"};
 3450:     $returnhash{'version'}=$version;
 3451:     my $scope;
 3452:     for ($scope=1;$scope<=$version;$scope++) {
 3453:       my $vkeys=$hash{"$scope:keys:$symb"};
 3454:       my @keys=split(/:/,$vkeys);
 3455:       my $key;
 3456:       $returnhash{"$scope:keys"}=$vkeys;
 3457:       foreach $key (@keys) {
 3458: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3459: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3460:       }
 3461:     }
 3462:     if (!(untie(%hash))) {
 3463:       return "error:$!";
 3464:     }
 3465:   } else {
 3466:     return "error:$!";
 3467:   }
 3468:   return %returnhash;
 3469: }
 3470: 
 3471: # ----------------------------------------------------------------------- Store
 3472: 
 3473: sub store {
 3474:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3475:     my $home='';
 3476: 
 3477:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3478: 
 3479:     $symb=&symbclean($symb);
 3480:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3481: 
 3482:     if (!$domain) { $domain=$env{'user.domain'}; }
 3483:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3484: 
 3485:     &devalidate($symb,$stuname,$domain);
 3486: 
 3487:     $symb=escape($symb);
 3488:     if (!$namespace) { 
 3489:        unless ($namespace=$env{'request.course.id'}) { 
 3490:           return ''; 
 3491:        } 
 3492:     }
 3493:     if (!$home) { $home=$env{'user.home'}; }
 3494: 
 3495:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3496:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3497: 
 3498:     my $namevalue='';
 3499:     foreach my $key (keys(%$storehash)) {
 3500:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3501:     }
 3502:     $namevalue=~s/\&$//;
 3503:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3504:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3505: }
 3506: 
 3507: # -------------------------------------------------------------- Critical Store
 3508: 
 3509: sub cstore {
 3510:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3511:     my $home='';
 3512: 
 3513:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3514: 
 3515:     $symb=&symbclean($symb);
 3516:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3517: 
 3518:     if (!$domain) { $domain=$env{'user.domain'}; }
 3519:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3520: 
 3521:     &devalidate($symb,$stuname,$domain);
 3522: 
 3523:     $symb=escape($symb);
 3524:     if (!$namespace) { 
 3525:        unless ($namespace=$env{'request.course.id'}) { 
 3526:           return ''; 
 3527:        } 
 3528:     }
 3529:     if (!$home) { $home=$env{'user.home'}; }
 3530: 
 3531:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3532:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3533: 
 3534:     my $namevalue='';
 3535:     foreach my $key (keys(%$storehash)) {
 3536:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3537:     }
 3538:     $namevalue=~s/\&$//;
 3539:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3540:     return critical
 3541:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3542: }
 3543: 
 3544: # --------------------------------------------------------------------- Restore
 3545: 
 3546: sub restore {
 3547:     my ($symb,$namespace,$domain,$stuname) = @_;
 3548:     my $home='';
 3549: 
 3550:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3551: 
 3552:     if (!$symb) {
 3553:       unless ($symb=escape(&symbread())) { return ''; }
 3554:     } else {
 3555:       $symb=&escape(&symbclean($symb));
 3556:     }
 3557:     if (!$namespace) { 
 3558:        unless ($namespace=$env{'request.course.id'}) { 
 3559:           return ''; 
 3560:        } 
 3561:     }
 3562:     if (!$domain) { $domain=$env{'user.domain'}; }
 3563:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3564:     if (!$home) { $home=$env{'user.home'}; }
 3565:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3566: 
 3567:     my %returnhash=();
 3568:     foreach my $line (split(/\&/,$answer)) {
 3569: 	my ($name,$value)=split(/\=/,$line);
 3570:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3571:     }
 3572:     my $version;
 3573:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3574:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3575:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3576:        }
 3577:     }
 3578:     return %returnhash;
 3579: }
 3580: 
 3581: # ---------------------------------------------------------- Course Description
 3582: 
 3583: sub coursedescription {
 3584:     my ($courseid,$args)=@_;
 3585:     $courseid=~s/^\///;
 3586:     $courseid=~s/\_/\//g;
 3587:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3588:     my $chome=&homeserver($cnum,$cdomain);
 3589:     my $normalid=$cdomain.'_'.$cnum;
 3590:     # need to always cache even if we get errors otherwise we keep 
 3591:     # trying and trying and trying to get the course description.
 3592:     my %envhash=();
 3593:     my %returnhash=();
 3594:     
 3595:     my $expiretime=600;
 3596:     if ($env{'request.course.id'} eq $normalid) {
 3597: 	$expiretime=120;
 3598:     }
 3599: 
 3600:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3601:     if (!$args->{'freshen_cache'}
 3602: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3603: 	foreach my $key (keys(%env)) {
 3604: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3605: 	    my ($setting) = $1;
 3606: 	    $returnhash{$setting} = $env{$key};
 3607: 	}
 3608: 	return %returnhash;
 3609:     }
 3610: 
 3611:     # get the data agin
 3612:     if (!$args->{'one_time'}) {
 3613: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3614:     }
 3615: 
 3616:     if ($chome ne 'no_host') {
 3617:        %returnhash=&dump('environment',$cdomain,$cnum);
 3618:        if (!exists($returnhash{'con_lost'})) {
 3619:            $returnhash{'home'}= $chome;
 3620: 	   $returnhash{'domain'} = $cdomain;
 3621: 	   $returnhash{'num'} = $cnum;
 3622:            if (!defined($returnhash{'type'})) {
 3623:                $returnhash{'type'} = 'Course';
 3624:            }
 3625:            while (my ($name,$value) = each %returnhash) {
 3626:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3627:            }
 3628:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3629:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3630: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3631:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3632:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3633:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3634:        }
 3635:     }
 3636:     if (!$args->{'one_time'}) {
 3637: 	&appenv(\%envhash);
 3638:     }
 3639:     return %returnhash;
 3640: }
 3641: 
 3642: # -------------------------------------------------See if a user is privileged
 3643: 
 3644: sub privileged {
 3645:     my ($username,$domain)=@_;
 3646:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3647: 			&homeserver($username,$domain));
 3648:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3649:     my $now=time;
 3650:     if ($rolesdump ne '') {
 3651:         foreach my $entry (split(/&/,$rolesdump)) {
 3652: 	    if ($entry!~/^rolesdef_/) {
 3653: 		my ($area,$role)=split(/=/,$entry);
 3654: 		$area=~s/\_\w\w$//;
 3655: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3656: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3657: 		    my $active=1;
 3658: 		    if ($tend) {
 3659: 			if ($tend<$now) { $active=0; }
 3660: 		    }
 3661: 		    if ($tstart) {
 3662: 			if ($tstart>$now) { $active=0; }
 3663: 		    }
 3664: 		    if ($active) { return 1; }
 3665: 		}
 3666: 	    }
 3667: 	}
 3668:     }
 3669:     return 0;
 3670: }
 3671: 
 3672: # -------------------------------------------------------- Get user privileges
 3673: 
 3674: sub rolesinit {
 3675:     my ($domain,$username,$authhost)=@_;
 3676:     my %userroles;
 3677:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3678:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3679:     my %allroles=();
 3680:     my %allgroups=();   
 3681:     my $now=time;
 3682:     %userroles = ('user.login.time' => $now);
 3683:     my $group_privs;
 3684: 
 3685:     if ($rolesdump ne '') {
 3686:         foreach my $entry (split(/&/,$rolesdump)) {
 3687: 	  if ($entry!~/^rolesdef_/) {
 3688:             my ($area,$role)=split(/=/,$entry);
 3689: 	    $area=~s/\_\w\w$//;
 3690:             my ($trole,$tend,$tstart,$group_privs);
 3691: 	    if ($role=~/^cr/) { 
 3692: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3693: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3694: 		    ($tend,$tstart)=split('_',$trest);
 3695: 		} else {
 3696: 		    $trole=$role;
 3697: 		}
 3698:             } elsif ($role =~ m|^gr/|) {
 3699:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3700:                 ($trole,$group_privs) = split(/\//,$trole);
 3701:                 $group_privs = &unescape($group_privs);
 3702: 	    } else {
 3703: 		($trole,$tend,$tstart)=split(/_/,$role);
 3704: 	    }
 3705: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3706: 					 $username);
 3707: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3708:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3709:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3710:             if (($area ne '') && ($trole ne '')) {
 3711: 		my $spec=$trole.'.'.$area;
 3712: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3713: 		if ($trole =~ /^cr\//) {
 3714:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3715:                 } elsif ($trole eq 'gr') {
 3716:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3717: 		} else {
 3718:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3719: 		}
 3720:             }
 3721:           }
 3722:         }
 3723:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3724:         $userroles{'user.adv'}    = $adv;
 3725: 	$userroles{'user.author'} = $author;
 3726:         $env{'user.adv'}=$adv;
 3727:     }
 3728:     return \%userroles;  
 3729: }
 3730: 
 3731: sub set_arearole {
 3732:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3733: # log the associated role with the area
 3734:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3735:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3736: }
 3737: 
 3738: sub custom_roleprivs {
 3739:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3740:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3741:     my $homsvr=homeserver($rauthor,$rdomain);
 3742:     if (&hostname($homsvr) ne '') {
 3743:         my ($rdummy,$roledef)=
 3744:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3745:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3746:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3747:             if (defined($syspriv)) {
 3748:                 $$allroles{'cm./'}.=':'.$syspriv;
 3749:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3750:             }
 3751:             if ($tdomain ne '') {
 3752:                 if (defined($dompriv)) {
 3753:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3754:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3755:                 }
 3756:                 if (($trest ne '') && (defined($coursepriv))) {
 3757:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3758:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3759:                 }
 3760:             }
 3761:         }
 3762:     }
 3763: }
 3764: 
 3765: sub group_roleprivs {
 3766:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3767:     my $access = 1;
 3768:     my $now = time;
 3769:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3770:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3771:     if ($access) {
 3772:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3773:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3774:     }
 3775: }
 3776: 
 3777: sub standard_roleprivs {
 3778:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3779:     if (defined($pr{$trole.':s'})) {
 3780:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3781:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3782:     }
 3783:     if ($tdomain ne '') {
 3784:         if (defined($pr{$trole.':d'})) {
 3785:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3786:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3787:         }
 3788:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3789:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3790:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3791:         }
 3792:     }
 3793: }
 3794: 
 3795: sub set_userprivs {
 3796:     my ($userroles,$allroles,$allgroups) = @_; 
 3797:     my $author=0;
 3798:     my $adv=0;
 3799:     my %grouproles = ();
 3800:     if (keys(%{$allgroups}) > 0) {
 3801:         foreach my $role (keys %{$allroles}) {
 3802:             my ($trole,$area,$sec,$extendedarea);
 3803:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3804:                 $trole = $1;
 3805:                 $area = $2;
 3806:                 $sec = $3;
 3807:                 $extendedarea = $area.$sec;
 3808:                 if (exists($$allgroups{$area})) {
 3809:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3810:                         my $spec = $trole.'.'.$extendedarea;
 3811:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3812:                                                 $$allgroups{$area}{$group};
 3813:                     }
 3814:                 }
 3815:             }
 3816:         }
 3817:     }
 3818:     foreach my $group (keys(%grouproles)) {
 3819:         $$allroles{$group} = $grouproles{$group};
 3820:     }
 3821:     foreach my $role (keys(%{$allroles})) {
 3822:         my %thesepriv;
 3823:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3824:         foreach my $item (split(/:/,$$allroles{$role})) {
 3825:             if ($item ne '') {
 3826:                 my ($privilege,$restrictions)=split(/&/,$item);
 3827:                 if ($restrictions eq '') {
 3828:                     $thesepriv{$privilege}='F';
 3829:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3830:                     $thesepriv{$privilege}.=$restrictions;
 3831:                 }
 3832:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3833:             }
 3834:         }
 3835:         my $thesestr='';
 3836:         foreach my $priv (keys(%thesepriv)) {
 3837: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3838: 	}
 3839:         $userroles->{'user.priv.'.$role} = $thesestr;
 3840:     }
 3841:     return ($author,$adv);
 3842: }
 3843: 
 3844: # --------------------------------------------------------------- get interface
 3845: 
 3846: sub get {
 3847:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3848:    my $items='';
 3849:    foreach my $item (@$storearr) {
 3850:        $items.=&escape($item).'&';
 3851:    }
 3852:    $items=~s/\&$//;
 3853:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3854:    if (!$uname) { $uname=$env{'user.name'}; }
 3855:    my $uhome=&homeserver($uname,$udomain);
 3856: 
 3857:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3858:    my @pairs=split(/\&/,$rep);
 3859:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3860:      return @pairs;
 3861:    }
 3862:    my %returnhash=();
 3863:    my $i=0;
 3864:    foreach my $item (@$storearr) {
 3865:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3866:       $i++;
 3867:    }
 3868:    return %returnhash;
 3869: }
 3870: 
 3871: # --------------------------------------------------------------- del interface
 3872: 
 3873: sub del {
 3874:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3875:    my $items='';
 3876:    foreach my $item (@$storearr) {
 3877:        $items.=&escape($item).'&';
 3878:    }
 3879: 
 3880:    $items=~s/\&$//;
 3881:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3882:    if (!$uname) { $uname=$env{'user.name'}; }
 3883:    my $uhome=&homeserver($uname,$udomain);
 3884:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3885: }
 3886: 
 3887: # -------------------------------------------------------------- dump interface
 3888: 
 3889: sub dump {
 3890:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3891:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3892:     if (!$uname) { $uname=$env{'user.name'}; }
 3893:     my $uhome=&homeserver($uname,$udomain);
 3894:     if ($regexp) {
 3895: 	$regexp=&escape($regexp);
 3896:     } else {
 3897: 	$regexp='.';
 3898:     }
 3899:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3900:     my @pairs=split(/\&/,$rep);
 3901:     my %returnhash=();
 3902:     foreach my $item (@pairs) {
 3903: 	my ($key,$value)=split(/=/,$item,2);
 3904: 	$key = &unescape($key);
 3905: 	next if ($key =~ /^error: 2 /);
 3906: 	$returnhash{$key}=&thaw_unescape($value);
 3907:     }
 3908:     return %returnhash;
 3909: }
 3910: 
 3911: # --------------------------------------------------------- dumpstore interface
 3912: 
 3913: sub dumpstore {
 3914:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3916:    if (!$uname) { $uname=$env{'user.name'}; }
 3917:    my $uhome=&homeserver($uname,$udomain);
 3918:    if ($regexp) {
 3919:        $regexp=&escape($regexp);
 3920:    } else {
 3921:        $regexp='.';
 3922:    }
 3923:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3924:    my @pairs=split(/\&/,$rep);
 3925:    my %returnhash=();
 3926:    foreach my $item (@pairs) {
 3927:        my ($key,$value)=split(/=/,$item,2);
 3928:        next if ($key =~ /^error: 2 /);
 3929:        $returnhash{$key}=&thaw_unescape($value);
 3930:    }
 3931:    return %returnhash;
 3932: }
 3933: 
 3934: # -------------------------------------------------------------- keys interface
 3935: 
 3936: sub getkeys {
 3937:    my ($namespace,$udomain,$uname)=@_;
 3938:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3939:    if (!$uname) { $uname=$env{'user.name'}; }
 3940:    my $uhome=&homeserver($uname,$udomain);
 3941:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3942:    my @keyarray=();
 3943:    foreach my $key (split(/\&/,$rep)) {
 3944:       next if ($key =~ /^error: 2 /);
 3945:       push(@keyarray,&unescape($key));
 3946:    }
 3947:    return @keyarray;
 3948: }
 3949: 
 3950: # --------------------------------------------------------------- currentdump
 3951: sub currentdump {
 3952:    my ($courseid,$sdom,$sname)=@_;
 3953:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3954:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3955:    $sname    = $env{'user.name'}         if (! defined($sname));
 3956:    my $uhome = &homeserver($sname,$sdom);
 3957:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3958:    return if ($rep =~ /^(error:|no_such_host)/);
 3959:    #
 3960:    my %returnhash=();
 3961:    #
 3962:    if ($rep eq "unknown_cmd") { 
 3963:        # an old lond will not know currentdump
 3964:        # Do a dump and make it look like a currentdump
 3965:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3966:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3967:        my %hash = @tmp;
 3968:        @tmp=();
 3969:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3970:    } else {
 3971:        my @pairs=split(/\&/,$rep);
 3972:        foreach my $pair (@pairs) {
 3973:            my ($key,$value)=split(/=/,$pair,2);
 3974:            my ($symb,$param) = split(/:/,$key);
 3975:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3976:                                                         &thaw_unescape($value);
 3977:        }
 3978:    }
 3979:    return %returnhash;
 3980: }
 3981: 
 3982: sub convert_dump_to_currentdump{
 3983:     my %hash = %{shift()};
 3984:     my %returnhash;
 3985:     # Code ripped from lond, essentially.  The only difference
 3986:     # here is the unescaping done by lonnet::dump().  Conceivably
 3987:     # we might run in to problems with parameter names =~ /^v\./
 3988:     while (my ($key,$value) = each(%hash)) {
 3989:         my ($v,$symb,$param) = split(/:/,$key);
 3990: 	$symb  = &unescape($symb);
 3991: 	$param = &unescape($param);
 3992:         next if ($v eq 'version' || $symb eq 'keys');
 3993:         next if (exists($returnhash{$symb}) &&
 3994:                  exists($returnhash{$symb}->{$param}) &&
 3995:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3996:         $returnhash{$symb}->{$param}=$value;
 3997:         $returnhash{$symb}->{'v.'.$param}=$v;
 3998:     }
 3999:     #
 4000:     # Remove all of the keys in the hashes which keep track of
 4001:     # the version of the parameter.
 4002:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4003:         # use a foreach because we are going to delete from the hash.
 4004:         foreach my $key (keys(%$param_hash)) {
 4005:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4006:         }
 4007:     }
 4008:     return \%returnhash;
 4009: }
 4010: 
 4011: # ------------------------------------------------------ critical inc interface
 4012: 
 4013: sub cinc {
 4014:     return &inc(@_,'critical');
 4015: }
 4016: 
 4017: # --------------------------------------------------------------- inc interface
 4018: 
 4019: sub inc {
 4020:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4021:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4022:     if (!$uname) { $uname=$env{'user.name'}; }
 4023:     my $uhome=&homeserver($uname,$udomain);
 4024:     my $items='';
 4025:     if (! ref($store)) {
 4026:         # got a single value, so use that instead
 4027:         $items = &escape($store).'=&';
 4028:     } elsif (ref($store) eq 'SCALAR') {
 4029:         $items = &escape($$store).'=&';        
 4030:     } elsif (ref($store) eq 'ARRAY') {
 4031:         $items = join('=&',map {&escape($_);} @{$store});
 4032:     } elsif (ref($store) eq 'HASH') {
 4033:         while (my($key,$value) = each(%{$store})) {
 4034:             $items.= &escape($key).'='.&escape($value).'&';
 4035:         }
 4036:     }
 4037:     $items=~s/\&$//;
 4038:     if ($critical) {
 4039: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4040:     } else {
 4041: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4042:     }
 4043: }
 4044: 
 4045: # --------------------------------------------------------------- put interface
 4046: 
 4047: sub put {
 4048:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4049:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4050:    if (!$uname) { $uname=$env{'user.name'}; }
 4051:    my $uhome=&homeserver($uname,$udomain);
 4052:    my $items='';
 4053:    foreach my $item (keys(%$storehash)) {
 4054:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4055:    }
 4056:    $items=~s/\&$//;
 4057:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4058: }
 4059: 
 4060: # ------------------------------------------------------------ newput interface
 4061: 
 4062: sub newput {
 4063:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4065:    if (!$uname) { $uname=$env{'user.name'}; }
 4066:    my $uhome=&homeserver($uname,$udomain);
 4067:    my $items='';
 4068:    foreach my $key (keys(%$storehash)) {
 4069:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4070:    }
 4071:    $items=~s/\&$//;
 4072:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4073: }
 4074: 
 4075: # ---------------------------------------------------------  putstore interface
 4076: 
 4077: sub putstore {
 4078:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4079:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4080:    if (!$uname) { $uname=$env{'user.name'}; }
 4081:    my $uhome=&homeserver($uname,$udomain);
 4082:    my $items='';
 4083:    foreach my $key (keys(%$storehash)) {
 4084:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4085:    }
 4086:    $items=~s/\&$//;
 4087:    my $esc_symb=&escape($symb);
 4088:    my $esc_v=&escape($version);
 4089:    my $reply =
 4090:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4091: 	      $uhome);
 4092:    if ($reply eq 'unknown_cmd') {
 4093:        # gfall back to way things use to be done
 4094:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4095: 			    $uname);
 4096:    }
 4097:    return $reply;
 4098: }
 4099: 
 4100: sub old_putstore {
 4101:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4102:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4103:     if (!$uname) { $uname=$env{'user.name'}; }
 4104:     my $uhome=&homeserver($uname,$udomain);
 4105:     my %newstorehash;
 4106:     foreach my $item (keys(%$storehash)) {
 4107: 	my $key = $version.':'.&escape($symb).':'.$item;
 4108: 	$newstorehash{$key} = $storehash->{$item};
 4109:     }
 4110:     my $items='';
 4111:     my %allitems = ();
 4112:     foreach my $item (keys(%newstorehash)) {
 4113: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4114: 	    my $key = $1.':keys:'.$2;
 4115: 	    $allitems{$key} .= $3.':';
 4116: 	}
 4117: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4118:     }
 4119:     foreach my $item (keys(%allitems)) {
 4120: 	$allitems{$item} =~ s/\:$//;
 4121: 	$items.= $item.'='.$allitems{$item}.'&';
 4122:     }
 4123:     $items=~s/\&$//;
 4124:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4125: }
 4126: 
 4127: # ------------------------------------------------------ critical put interface
 4128: 
 4129: sub cput {
 4130:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4132:    if (!$uname) { $uname=$env{'user.name'}; }
 4133:    my $uhome=&homeserver($uname,$udomain);
 4134:    my $items='';
 4135:    foreach my $item (keys(%$storehash)) {
 4136:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4137:    }
 4138:    $items=~s/\&$//;
 4139:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4140: }
 4141: 
 4142: # -------------------------------------------------------------- eget interface
 4143: 
 4144: sub eget {
 4145:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4146:    my $items='';
 4147:    foreach my $item (@$storearr) {
 4148:        $items.=&escape($item).'&';
 4149:    }
 4150:    $items=~s/\&$//;
 4151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4152:    if (!$uname) { $uname=$env{'user.name'}; }
 4153:    my $uhome=&homeserver($uname,$udomain);
 4154:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4155:    my @pairs=split(/\&/,$rep);
 4156:    my %returnhash=();
 4157:    my $i=0;
 4158:    foreach my $item (@$storearr) {
 4159:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4160:       $i++;
 4161:    }
 4162:    return %returnhash;
 4163: }
 4164: 
 4165: # ------------------------------------------------------------ tmpput interface
 4166: sub tmpput {
 4167:     my ($storehash,$server,$context)=@_;
 4168:     my $items='';
 4169:     foreach my $item (keys(%$storehash)) {
 4170: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4171:     }
 4172:     $items=~s/\&$//;
 4173:     if (defined($context)) {
 4174:         $items .= ':'.&escape($context);
 4175:     }
 4176:     return &reply("tmpput:$items",$server);
 4177: }
 4178: 
 4179: # ------------------------------------------------------------ tmpget interface
 4180: sub tmpget {
 4181:     my ($token,$server)=@_;
 4182:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4183:     my $rep=&reply("tmpget:$token",$server);
 4184:     my %returnhash;
 4185:     foreach my $item (split(/\&/,$rep)) {
 4186: 	my ($key,$value)=split(/=/,$item);
 4187:         next if ($key =~ /^error: 2 /);
 4188: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4189:     }
 4190:     return %returnhash;
 4191: }
 4192: 
 4193: # ------------------------------------------------------------ tmpget interface
 4194: sub tmpdel {
 4195:     my ($token,$server)=@_;
 4196:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4197:     return &reply("tmpdel:$token",$server);
 4198: }
 4199: 
 4200: # -------------------------------------------------- portfolio access checking
 4201: 
 4202: sub portfolio_access {
 4203:     my ($requrl) = @_;
 4204:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4205:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4206:     if ($result) {
 4207:         my %setters;
 4208:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4209:             my ($startblock,$endblock) =
 4210:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4211:             if ($startblock && $endblock) {
 4212:                 return 'B';
 4213:             }
 4214:         } else {
 4215:             my ($startblock,$endblock) =
 4216:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4217:             if ($startblock && $endblock) {
 4218:                 return 'B';
 4219:             }
 4220:         }
 4221:     }
 4222:     if ($result eq 'ok') {
 4223:        return 'F';
 4224:     } elsif ($result =~ /^[^:]+:guest_/) {
 4225:        return 'A';
 4226:     }
 4227:     return '';
 4228: }
 4229: 
 4230: sub get_portfolio_access {
 4231:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4232: 
 4233:     if (!ref($access_hash)) {
 4234: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4235: 	my %access_controls = &get_access_controls($current_perms,$group,
 4236: 						   $file_name);
 4237: 	$access_hash = $access_controls{$file_name};
 4238:     }
 4239: 
 4240:     my ($public,$guest,@domains,@users,@courses,@groups);
 4241:     my $now = time;
 4242:     if (ref($access_hash) eq 'HASH') {
 4243:         foreach my $key (keys(%{$access_hash})) {
 4244:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4245:             if ($start > $now) {
 4246:                 next;
 4247:             }
 4248:             if ($end && $end<$now) {
 4249:                 next;
 4250:             }
 4251:             if ($scope eq 'public') {
 4252:                 $public = $key;
 4253:                 last;
 4254:             } elsif ($scope eq 'guest') {
 4255:                 $guest = $key;
 4256:             } elsif ($scope eq 'domains') {
 4257:                 push(@domains,$key);
 4258:             } elsif ($scope eq 'users') {
 4259:                 push(@users,$key);
 4260:             } elsif ($scope eq 'course') {
 4261:                 push(@courses,$key);
 4262:             } elsif ($scope eq 'group') {
 4263:                 push(@groups,$key);
 4264:             }
 4265:         }
 4266:         if ($public) {
 4267:             return 'ok';
 4268:         }
 4269:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4270:             if ($guest) {
 4271:                 return $guest;
 4272:             }
 4273:         } else {
 4274:             if (@domains > 0) {
 4275:                 foreach my $domkey (@domains) {
 4276:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4277:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4278:                             return 'ok';
 4279:                         }
 4280:                     }
 4281:                 }
 4282:             }
 4283:             if (@users > 0) {
 4284:                 foreach my $userkey (@users) {
 4285:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4286:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4287:                             if (ref($item) eq 'HASH') {
 4288:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4289:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4290:                                     return 'ok';
 4291:                                 }
 4292:                             }
 4293:                         }
 4294:                     } 
 4295:                 }
 4296:             }
 4297:             my %roleshash;
 4298:             my @courses_and_groups = @courses;
 4299:             push(@courses_and_groups,@groups); 
 4300:             if (@courses_and_groups > 0) {
 4301:                 my (%allgroups,%allroles); 
 4302:                 my ($start,$end,$role,$sec,$group);
 4303:                 foreach my $envkey (%env) {
 4304:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4305:                         my $cid = $2.'_'.$3; 
 4306:                         if ($1 eq 'gr') {
 4307:                             $group = $4;
 4308:                             $allgroups{$cid}{$group} = $env{$envkey};
 4309:                         } else {
 4310:                             if ($4 eq '') {
 4311:                                 $sec = 'none';
 4312:                             } else {
 4313:                                 $sec = $4;
 4314:                             }
 4315:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4316:                         }
 4317:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4318:                         my $cid = $2.'_'.$3;
 4319:                         if ($4 eq '') {
 4320:                             $sec = 'none';
 4321:                         } else {
 4322:                             $sec = $4;
 4323:                         }
 4324:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4325:                     }
 4326:                 }
 4327:                 if (keys(%allroles) == 0) {
 4328:                     return;
 4329:                 }
 4330:                 foreach my $key (@courses_and_groups) {
 4331:                     my %content = %{$$access_hash{$key}};
 4332:                     my $cnum = $content{'number'};
 4333:                     my $cdom = $content{'domain'};
 4334:                     my $cid = $cdom.'_'.$cnum;
 4335:                     if (!exists($allroles{$cid})) {
 4336:                         next;
 4337:                     }    
 4338:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4339:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4340:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4341:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4342:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4343:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4344:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4345:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4346:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4347:                                         if (grep/^all$/,@sections) {
 4348:                                             return 'ok';
 4349:                                         } else {
 4350:                                             if (grep/^$sec$/,@sections) {
 4351:                                                 return 'ok';
 4352:                                             }
 4353:                                         }
 4354:                                     }
 4355:                                 }
 4356:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4357:                                     if (grep/^none$/,@groups) {
 4358:                                         return 'ok';
 4359:                                     }
 4360:                                 } else {
 4361:                                     if (grep/^all$/,@groups) {
 4362:                                         return 'ok';
 4363:                                     } 
 4364:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4365:                                         if (grep/^$group$/,@groups) {
 4366:                                             return 'ok';
 4367:                                         }
 4368:                                     }
 4369:                                 } 
 4370:                             }
 4371:                         }
 4372:                     }
 4373:                 }
 4374:             }
 4375:             if ($guest) {
 4376:                 return $guest;
 4377:             }
 4378:         }
 4379:     }
 4380:     return;
 4381: }
 4382: 
 4383: sub course_group_datechecker {
 4384:     my ($dates,$now,$status) = @_;
 4385:     my ($start,$end) = split(/\./,$dates);
 4386:     if (!$start && !$end) {
 4387:         return 'ok';
 4388:     }
 4389:     if (grep/^active$/,@{$status}) {
 4390:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4391:             return 'ok';
 4392:         }
 4393:     }
 4394:     if (grep/^previous$/,@{$status}) {
 4395:         if ($end > $now ) {
 4396:             return 'ok';
 4397:         }
 4398:     }
 4399:     if (grep/^future$/,@{$status}) {
 4400:         if ($start > $now) {
 4401:             return 'ok';
 4402:         }
 4403:     }
 4404:     return; 
 4405: }
 4406: 
 4407: sub parse_portfolio_url {
 4408:     my ($url) = @_;
 4409: 
 4410:     my ($type,$udom,$unum,$group,$file_name);
 4411:     
 4412:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4413: 	$type = 1;
 4414:         $udom = $1;
 4415:         $unum = $2;
 4416:         $file_name = $3;
 4417:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4418: 	$type = 2;
 4419:         $udom = $1;
 4420:         $unum = $2;
 4421:         $group = $3;
 4422:         $file_name = $3.'/'.$4;
 4423:     }
 4424:     if (wantarray) {
 4425: 	return ($type,$udom,$unum,$file_name,$group);
 4426:     }
 4427:     return $type;
 4428: }
 4429: 
 4430: sub is_portfolio_url {
 4431:     my ($url) = @_;
 4432:     return scalar(&parse_portfolio_url($url));
 4433: }
 4434: 
 4435: sub is_portfolio_file {
 4436:     my ($file) = @_;
 4437:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4438:         return 1;
 4439:     }
 4440:     return;
 4441: }
 4442: 
 4443: sub usertools_access {
 4444:     my ($uname,$udom,$tool,$action,$context) = @_;
 4445:     my ($access,%tools);
 4446:     if ($context eq '') {
 4447:         $context = 'tools';
 4448:     }
 4449:     if ($context eq 'requestcourses') {
 4450:         %tools = (
 4451:                       official   => 1,
 4452:                       unofficial => 1,
 4453:                  );
 4454:     } else {
 4455:         %tools = (
 4456:                       aboutme   => 1,
 4457:                       blog      => 1,
 4458:                       portfolio => 1,
 4459:                  );
 4460:     }
 4461:     return if (!defined($tools{$tool}));
 4462: 
 4463:     if ((!defined($udom)) || (!defined($uname))) {
 4464:         $udom = $env{'user.domain'};
 4465:         $uname = $env{'user.name'};
 4466:     }
 4467: 
 4468:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4469:         if ($action ne 'reload') {
 4470:             if ($context eq 'requestcourses') {
 4471:                 return $env{'environment.canrequest.'.$tool};
 4472:             } else {
 4473:                 return $env{'environment.availabletools.'.$tool};
 4474:             }
 4475:         }
 4476:     }
 4477: 
 4478:     my ($toolstatus,$inststatus);
 4479: 
 4480:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4481:          ($action ne 'reload')) {
 4482:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4483:         $inststatus = $env{'environment.inststatus'};
 4484:     } else {
 4485:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4486:         $toolstatus = $userenv{$context.'.'.$tool};
 4487:         $inststatus = $userenv{'inststatus'};
 4488:     }
 4489: 
 4490:     if ($toolstatus ne '') {
 4491:         if ($toolstatus) {
 4492:             $access = 1;
 4493:         } else {
 4494:             $access = 0;
 4495:         }
 4496:         return $access;
 4497:     }
 4498: 
 4499:     my $is_adv = &is_advanced_user($udom,$uname);
 4500:     my %domdef = &get_domain_defaults($udom);
 4501:     if (ref($domdef{$tool}) eq 'HASH') {
 4502:         if ($is_adv) {
 4503:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4504:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4505:                     $access = 1;
 4506:                 } else {
 4507:                     $access = 0;
 4508:                 }
 4509:                 return $access;
 4510:             }
 4511:         }
 4512:         if ($inststatus ne '') {
 4513:             my ($hasaccess,$hasnoaccess);
 4514:             foreach my $affiliation (split(/:/,$inststatus)) {
 4515:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4516:                     if ($domdef{$tool}{$affiliation}) {
 4517:                         $hasaccess = 1;
 4518:                     } else {
 4519:                         $hasnoaccess = 1;
 4520:                     }
 4521:                 }
 4522:             }
 4523:             if ($hasaccess || $hasnoaccess) {
 4524:                 if ($hasaccess) {
 4525:                     $access = 1;
 4526:                 } elsif ($hasnoaccess) {
 4527:                     $access = 0; 
 4528:                 }
 4529:                 return $access;
 4530:             }
 4531:         } else {
 4532:             if ($domdef{$tool}{'default'} ne '') {
 4533:                 if ($domdef{$tool}{'default'}) {
 4534:                     $access = 1;
 4535:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4536:                     $access = 0;
 4537:                 }
 4538:                 return $access;
 4539:             }
 4540:         }
 4541:     } else {
 4542:         if ($context eq 'tools') {
 4543:             $access = 1;
 4544:         } else {
 4545:             $access = 0;
 4546:         }
 4547:         return $access;
 4548:     }
 4549: }
 4550: 
 4551: sub is_advanced_user {
 4552:     my ($udom,$uname) = @_;
 4553:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4554:     my %allroles;
 4555:     my $is_adv;
 4556:     foreach my $role (keys(%roleshash)) {
 4557:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4558:         my $area = '/'.$tdomain.'/'.$trest;
 4559:         if ($sec ne '') {
 4560:             $area .= '/'.$sec;
 4561:         }
 4562:         if (($area ne '') && ($trole ne '')) {
 4563:             my $spec=$trole.'.'.$area;
 4564:             if ($trole =~ /^cr\//) {
 4565:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4566:             } elsif ($trole ne 'gr') {
 4567:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4568:             }
 4569:         }
 4570:     }
 4571:     foreach my $role (keys(%allroles)) {
 4572:         last if ($is_adv);
 4573:         foreach my $item (split(/:/,$allroles{$role})) {
 4574:             if ($item ne '') {
 4575:                 my ($privilege,$restrictions)=split(/&/,$item);
 4576:                 if ($privilege eq 'adv') {
 4577:                     $is_adv = 1;
 4578:                     last;
 4579:                 }
 4580:             }
 4581:         }
 4582:     }
 4583:     return $is_adv;
 4584: }
 4585: 
 4586: # ---------------------------------------------- Custom access rule evaluation
 4587: 
 4588: sub customaccess {
 4589:     my ($priv,$uri)=@_;
 4590:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4591:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4592:     $udom = &LONCAPA::clean_domain($udom);
 4593:     $ucrs = &LONCAPA::clean_username($ucrs);
 4594:     my $access=0;
 4595:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4596: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4597: 	if ($type eq 'user') {
 4598: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4599: 		my ($tdom,$tuname)=split(m{/},$scope);
 4600: 		if ($tdom) {
 4601: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4602: 		}
 4603: 		if ($tuname) {
 4604: 		    if ($tuname ne $env{'user.name'}) { next; }
 4605: 		}
 4606: 		$access=($effect eq 'allow');
 4607: 		last;
 4608: 	    }
 4609: 	} else {
 4610: 	    if ($role) {
 4611: 		if ($role ne $urole) { next; }
 4612: 	    }
 4613: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4614: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4615: 		if ($tdom) {
 4616: 		    if ($tdom ne $udom) { next; }
 4617: 		}
 4618: 		if ($tcrs) {
 4619: 		    if ($tcrs ne $ucrs) { next; }
 4620: 		}
 4621: 		if ($tsec) {
 4622: 		    if ($tsec ne $usec) { next; }
 4623: 		}
 4624: 		$access=($effect eq 'allow');
 4625: 		last;
 4626: 	    }
 4627: 	    if ($realm eq '' && $role eq '') {
 4628: 		$access=($effect eq 'allow');
 4629: 	    }
 4630: 	}
 4631:     }
 4632:     return $access;
 4633: }
 4634: 
 4635: # ------------------------------------------------- Check for a user privilege
 4636: 
 4637: sub allowed {
 4638:     my ($priv,$uri,$symb,$role)=@_;
 4639:     my $ver_orguri=$uri;
 4640:     $uri=&deversion($uri);
 4641:     my $orguri=$uri;
 4642:     $uri=&declutter($uri);
 4643: 
 4644:     if ($priv eq 'evb') {
 4645: # Evade communication block restrictions for specified role in a course
 4646:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4647:             return $1;
 4648:         } else {
 4649:             return;
 4650:         }
 4651:     }
 4652: 
 4653:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4654: # Free bre access to adm and meta resources
 4655:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4656: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4657: 	&& ($priv eq 'bre')) {
 4658: 	return 'F';
 4659:     }
 4660: 
 4661: # Free bre access to user's own portfolio contents
 4662:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4663:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4664: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4665:         my %setters;
 4666:         my ($startblock,$endblock) = 
 4667:             &Apache::loncommon::blockcheck(\%setters,'port');
 4668:         if ($startblock && $endblock) {
 4669:             return 'B';
 4670:         } else {
 4671:             return 'F';
 4672:         }
 4673:     }
 4674: 
 4675: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4676:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4677:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4678:         if (exists($env{'request.course.id'})) {
 4679:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4680:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4681:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4682:                 my $courseprivid=$env{'request.course.id'};
 4683:                 $courseprivid=~s/\_/\//;
 4684:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4685:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4686:                     return $1; 
 4687:                 } else {
 4688:                     if ($env{'request.course.sec'}) {
 4689:                         $courseprivid.='/'.$env{'request.course.sec'};
 4690:                     }
 4691:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4692:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4693:                         return $2;
 4694:                     }
 4695:                 }
 4696:             }
 4697:         }
 4698:     }
 4699: 
 4700: # Free bre to public access
 4701: 
 4702:     if ($priv eq 'bre') {
 4703:         my $copyright=&metadata($uri,'copyright');
 4704: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4705:            return 'F'; 
 4706:         }
 4707:         if ($copyright eq 'priv') {
 4708:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4709: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4710: 		return '';
 4711:             }
 4712:         }
 4713:         if ($copyright eq 'domain') {
 4714:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4715: 	    unless (($env{'user.domain'} eq $1) ||
 4716:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4717: 		return '';
 4718:             }
 4719:         }
 4720:         if ($env{'request.role'}=~ /li\.\//) {
 4721:             # Library role, so allow browsing of resources in this domain.
 4722:             return 'F';
 4723:         }
 4724:         if ($copyright eq 'custom') {
 4725: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4726:         }
 4727:     }
 4728:     # Domain coordinator is trying to create a course
 4729:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4730:         # uri is the requested domain in this case.
 4731:         # comparison to 'request.role.domain' shows if the user has selected
 4732:         # a role of dc for the domain in question.
 4733:         return 'F' if ($uri eq $env{'request.role.domain'});
 4734:     }
 4735: 
 4736:     my $thisallowed='';
 4737:     my $statecond=0;
 4738:     my $courseprivid='';
 4739: 
 4740: # Course
 4741: 
 4742:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4743:        $thisallowed.=$1;
 4744:     }
 4745: 
 4746: # Domain
 4747: 
 4748:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4749:        =~/\Q$priv\E\&([^\:]*)/) {
 4750:        $thisallowed.=$1;
 4751:     }
 4752: 
 4753: # Course: uri itself is a course
 4754:     my $courseuri=$uri;
 4755:     $courseuri=~s/\_(\d)/\/$1/;
 4756:     $courseuri=~s/^([^\/])/\/$1/;
 4757: 
 4758:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4759:        =~/\Q$priv\E\&([^\:]*)/) {
 4760:        $thisallowed.=$1;
 4761:     }
 4762: 
 4763: # URI is an uploaded document for this course, default permissions don't matter
 4764: # not allowing 'edit' access (editupload) to uploaded course docs
 4765:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4766: 	$thisallowed='';
 4767:         my ($match)=&is_on_map($uri);
 4768:         if ($match) {
 4769:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4770:                   =~/\Q$priv\E\&([^\:]*)/) {
 4771:                 $thisallowed.=$1;
 4772:             }
 4773:         } else {
 4774:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4775:             if ($refuri) {
 4776:                 if ($refuri =~ m|^/adm/|) {
 4777:                     $thisallowed='F';
 4778:                 } else {
 4779:                     $refuri=&declutter($refuri);
 4780:                     my ($match) = &is_on_map($refuri);
 4781:                     if ($match) {
 4782:                         $thisallowed='F';
 4783:                     }
 4784:                 }
 4785:             }
 4786:         }
 4787:     }
 4788: 
 4789:     if ($priv eq 'bre'
 4790: 	&& $thisallowed ne 'F' 
 4791: 	&& $thisallowed ne '2'
 4792: 	&& &is_portfolio_url($uri)) {
 4793: 	$thisallowed = &portfolio_access($uri);
 4794:     }
 4795:     
 4796: # Full access at system, domain or course-wide level? Exit.
 4797:     if ($thisallowed=~/F/) {
 4798: 	return 'F';
 4799:     }
 4800: 
 4801: # If this is generating or modifying users, exit with special codes
 4802: 
 4803:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4804: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4805: 	    my ($audom,$auname)=split('/',$uri);
 4806: # no author name given, so this just checks on the general right to make a co-author in this domain
 4807: 	    unless ($auname) { return $thisallowed; }
 4808: # an author name is given, so we are about to actually make a co-author for a certain account
 4809: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4810: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4811: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4812: 	}
 4813: 	return $thisallowed;
 4814:     }
 4815: #
 4816: # Gathered so far: system, domain and course wide privileges
 4817: #
 4818: # Course: See if uri or referer is an individual resource that is part of 
 4819: # the course
 4820: 
 4821:     if ($env{'request.course.id'}) {
 4822: 
 4823:        $courseprivid=$env{'request.course.id'};
 4824:        if ($env{'request.course.sec'}) {
 4825:           $courseprivid.='/'.$env{'request.course.sec'};
 4826:        }
 4827:        $courseprivid=~s/\_/\//;
 4828:        my $checkreferer=1;
 4829:        my ($match,$cond)=&is_on_map($uri);
 4830:        if ($match) {
 4831:            $statecond=$cond;
 4832:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4833:                =~/\Q$priv\E\&([^\:]*)/) {
 4834:                $thisallowed.=$1;
 4835:                $checkreferer=0;
 4836:            }
 4837:        }
 4838:        
 4839:        if ($checkreferer) {
 4840: 	  my $refuri=$env{'httpref.'.$orguri};
 4841:             unless ($refuri) {
 4842:                 foreach my $key (keys(%env)) {
 4843: 		    if ($key=~/^httpref\..*\*/) {
 4844: 			my $pattern=$key;
 4845:                         $pattern=~s/^httpref\.\/res\///;
 4846:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4847:                         $pattern=~s/\//\\\//g;
 4848:                         if ($orguri=~/$pattern/) {
 4849: 			    $refuri=$env{$key};
 4850:                         }
 4851:                     }
 4852:                 }
 4853:             }
 4854: 
 4855:          if ($refuri) { 
 4856: 	  $refuri=&declutter($refuri);
 4857:           my ($match,$cond)=&is_on_map($refuri);
 4858:             if ($match) {
 4859:               my $refstatecond=$cond;
 4860:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4861:                   =~/\Q$priv\E\&([^\:]*)/) {
 4862:                   $thisallowed.=$1;
 4863:                   $uri=$refuri;
 4864:                   $statecond=$refstatecond;
 4865:               }
 4866:           }
 4867:         }
 4868:        }
 4869:    }
 4870: 
 4871: #
 4872: # Gathered now: all privileges that could apply, and condition number
 4873: # 
 4874: #
 4875: # Full or no access?
 4876: #
 4877: 
 4878:     if ($thisallowed=~/F/) {
 4879: 	return 'F';
 4880:     }
 4881: 
 4882:     unless ($thisallowed) {
 4883:         return '';
 4884:     }
 4885: 
 4886: # Restrictions exist, deal with them
 4887: #
 4888: #   C:according to course preferences
 4889: #   R:according to resource settings
 4890: #   L:unless locked
 4891: #   X:according to user session state
 4892: #
 4893: 
 4894: # Possibly locked functionality, check all courses
 4895: # Locks might take effect only after 10 minutes cache expiration for other
 4896: # courses, and 2 minutes for current course
 4897: 
 4898:     my $envkey;
 4899:     if ($thisallowed=~/L/) {
 4900:         foreach $envkey (keys %env) {
 4901:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4902:                my $courseid=$2;
 4903:                my $roleid=$1.'.'.$2;
 4904:                $courseid=~s/^\///;
 4905:                my $expiretime=600;
 4906:                if ($env{'request.role'} eq $roleid) {
 4907: 		  $expiretime=120;
 4908:                }
 4909: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4910:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4911:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4912: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4913:                }
 4914:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4915:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4916: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4917:                        &log($env{'user.domain'},$env{'user.name'},
 4918:                             $env{'user.home'},
 4919:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4920:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4921:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4922: 		       return '';
 4923:                    }
 4924:                }
 4925:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4926:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4927: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4928:                        &log($env{'user.domain'},$env{'user.name'},
 4929:                             $env{'user.home'},
 4930:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4931:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4932:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4933: 		       return '';
 4934:                    }
 4935:                }
 4936: 	   }
 4937:        }
 4938:     }
 4939:    
 4940: #
 4941: # Rest of the restrictions depend on selected course
 4942: #
 4943: 
 4944:     unless ($env{'request.course.id'}) {
 4945: 	if ($thisallowed eq 'A') {
 4946: 	    return 'A';
 4947:         } elsif ($thisallowed eq 'B') {
 4948:             return 'B';
 4949: 	} else {
 4950: 	    return '1';
 4951: 	}
 4952:     }
 4953: 
 4954: #
 4955: # Now user is definitely in a course
 4956: #
 4957: 
 4958: 
 4959: # Course preferences
 4960: 
 4961:    if ($thisallowed=~/C/) {
 4962:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4963:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4964:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4965: 	   =~/\Q$rolecode\E/) {
 4966: 	   if ($priv ne 'pch') { 
 4967: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4968: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4969: 			$env{'request.course.id'});
 4970: 	   }
 4971:            return '';
 4972:        }
 4973: 
 4974:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4975: 	   =~/\Q$unamedom\E/) {
 4976: 	   if ($priv ne 'pch') { 
 4977: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4978: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4979: 			$env{'request.course.id'});
 4980: 	   }
 4981:            return '';
 4982:        }
 4983:    }
 4984: 
 4985: # Resource preferences
 4986: 
 4987:    if ($thisallowed=~/R/) {
 4988:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4989:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4990: 	   if ($priv ne 'pch') { 
 4991: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4992: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4993: 	   }
 4994: 	   return '';
 4995:        }
 4996:    }
 4997: 
 4998: # Restricted by state or randomout?
 4999: 
 5000:    if ($thisallowed=~/X/) {
 5001:       if ($env{'acc.randomout'}) {
 5002: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5003:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5004:             return ''; 
 5005:          }
 5006:       }
 5007:       if (&condval($statecond)) {
 5008: 	 return '2';
 5009:       } else {
 5010:          return '';
 5011:       }
 5012:    }
 5013: 
 5014:     if ($thisallowed eq 'A') {
 5015: 	return 'A';
 5016:     } elsif ($thisallowed eq 'B') {
 5017:         return 'B';
 5018:     }
 5019:    return 'F';
 5020: }
 5021: 
 5022: sub split_uri_for_cond {
 5023:     my $uri=&deversion(&declutter(shift));
 5024:     my @uriparts=split(/\//,$uri);
 5025:     my $filename=pop(@uriparts);
 5026:     my $pathname=join('/',@uriparts);
 5027:     return ($pathname,$filename);
 5028: }
 5029: # --------------------------------------------------- Is a resource on the map?
 5030: 
 5031: sub is_on_map {
 5032:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5033:     #Trying to find the conditional for the file
 5034:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5035: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5036:     if ($match) {
 5037: 	return (1,$1);
 5038:     } else {
 5039: 	return (0,0);
 5040:     }
 5041: }
 5042: 
 5043: # --------------------------------------------------------- Get symb from alias
 5044: 
 5045: sub get_symb_from_alias {
 5046:     my $symb=shift;
 5047:     my ($map,$resid,$url)=&decode_symb($symb);
 5048: # Already is a symb
 5049:     if ($url) { return $symb; }
 5050: # Must be an alias
 5051:     my $aliassymb='';
 5052:     my %bighash;
 5053:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5054:                             &GDBM_READER(),0640)) {
 5055:         my $rid=$bighash{'mapalias_'.$symb};
 5056: 	if ($rid) {
 5057: 	    my ($mapid,$resid)=split(/\./,$rid);
 5058: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5059: 				    $resid,$bighash{'src_'.$rid});
 5060: 	}
 5061:         untie %bighash;
 5062:     }
 5063:     return $aliassymb;
 5064: }
 5065: 
 5066: # ----------------------------------------------------------------- Define Role
 5067: 
 5068: sub definerole {
 5069:   if (allowed('mcr','/')) {
 5070:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5071:     foreach my $role (split(':',$sysrole)) {
 5072: 	my ($crole,$cqual)=split(/\&/,$role);
 5073:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5074:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5075: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5076:                return "refused:s:$crole&$cqual"; 
 5077:             }
 5078:         }
 5079:     }
 5080:     foreach my $role (split(':',$domrole)) {
 5081: 	my ($crole,$cqual)=split(/\&/,$role);
 5082:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5083:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5084: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5085:                return "refused:d:$crole&$cqual"; 
 5086:             }
 5087:         }
 5088:     }
 5089:     foreach my $role (split(':',$courole)) {
 5090: 	my ($crole,$cqual)=split(/\&/,$role);
 5091:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5092:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5093: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5094:                return "refused:c:$crole&$cqual"; 
 5095:             }
 5096:         }
 5097:     }
 5098:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5099:                 "$env{'user.domain'}:$env{'user.name'}:".
 5100: 	        "rolesdef_$rolename=".
 5101:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5102:     return reply($command,$env{'user.home'});
 5103:   } else {
 5104:     return 'refused';
 5105:   }
 5106: }
 5107: 
 5108: # ---------------- Make a metadata query against the network of library servers
 5109: 
 5110: sub metadata_query {
 5111:     my ($query,$custom,$customshow,$server_array)=@_;
 5112:     my %rhash;
 5113:     my %libserv = &all_library();
 5114:     my @server_list = (defined($server_array) ? @$server_array
 5115:                                               : keys(%libserv) );
 5116:     for my $server (@server_list) {
 5117: 	unless ($custom or $customshow) {
 5118: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5119: 	    $rhash{$server}=$reply;
 5120: 	}
 5121: 	else {
 5122: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5123: 			     &escape($custom).':'.&escape($customshow),
 5124: 			     $server);
 5125: 	    $rhash{$server}=$reply;
 5126: 	}
 5127:     }
 5128:     return \%rhash;
 5129: }
 5130: 
 5131: # ----------------------------------------- Send log queries and wait for reply
 5132: 
 5133: sub log_query {
 5134:     my ($uname,$udom,$query,%filters)=@_;
 5135:     my $uhome=&homeserver($uname,$udom);
 5136:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5137:     my $uhost=&hostname($uhome);
 5138:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5139:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5140:                        $uhome);
 5141:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5142:     return get_query_reply($queryid);
 5143: }
 5144: 
 5145: # -------------------------- Update MySQL table for portfolio file
 5146: 
 5147: sub update_portfolio_table {
 5148:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5149:     if ($group ne '') {
 5150:         $file_name =~s /^\Q$group\E//;
 5151:     }
 5152:     my $homeserver = &homeserver($uname,$udom);
 5153:     my $queryid=
 5154:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5155:                ':'.&escape($file_name).':'.$action,$homeserver);
 5156:     my $reply = &get_query_reply($queryid);
 5157:     return $reply;
 5158: }
 5159: 
 5160: # -------------------------- Update MySQL allusers table
 5161: 
 5162: sub update_allusers_table {
 5163:     my ($uname,$udom,$names) = @_;
 5164:     my $homeserver = &homeserver($uname,$udom);
 5165:     my $queryid=
 5166:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5167:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5168:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5169:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5170:                'generation='.&escape($names->{'generation'}).'%%'.
 5171:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5172:                'id='.&escape($names->{'id'}),$homeserver);
 5173:     my $reply = &get_query_reply($queryid);
 5174:     return $reply;
 5175: }
 5176: 
 5177: # ------- Request retrieval of institutional classlists for course(s)
 5178: 
 5179: sub fetch_enrollment_query {
 5180:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5181:     my $homeserver;
 5182:     my $maxtries = 1;
 5183:     if ($context eq 'automated') {
 5184:         $homeserver = $perlvar{'lonHostID'};
 5185:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5186:     } else {
 5187:         $homeserver = &homeserver($cnum,$dom);
 5188:     }
 5189:     my $host=&hostname($homeserver);
 5190:     my $cmd = '';
 5191:     foreach my $affiliate (keys %{$affiliatesref}) {
 5192:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5193:     }
 5194:     $cmd =~ s/%%$//;
 5195:     $cmd = &escape($cmd);
 5196:     my $query = 'fetchenrollment';
 5197:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5198:     unless ($queryid=~/^\Q$host\E\_/) { 
 5199:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5200:         return 'error: '.$queryid;
 5201:     }
 5202:     my $reply = &get_query_reply($queryid);
 5203:     my $tries = 1;
 5204:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5205:         $reply = &get_query_reply($queryid);
 5206:         $tries ++;
 5207:     }
 5208:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5209:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5210:     } else {
 5211:         my @responses = split(/:/,$reply);
 5212:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5213:             foreach my $line (@responses) {
 5214:                 my ($key,$value) = split(/=/,$line,2);
 5215:                 $$replyref{$key} = $value;
 5216:             }
 5217:         } else {
 5218:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5219:             foreach my $line (@responses) {
 5220:                 my ($key,$value) = split(/=/,$line);
 5221:                 $$replyref{$key} = $value;
 5222:                 if ($value > 0) {
 5223:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5224:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5225:                         my $destname = $pathname.'/'.$filename;
 5226:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5227:                         if ($xml_classlist =~ /^error/) {
 5228:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5229:                         } else {
 5230:                             if ( open(FILE,">$destname") ) {
 5231:                                 print FILE &unescape($xml_classlist);
 5232:                                 close(FILE);
 5233:                             } else {
 5234:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5235:                             }
 5236:                         }
 5237:                     }
 5238:                 }
 5239:             }
 5240:         }
 5241:         return 'ok';
 5242:     }
 5243:     return 'error';
 5244: }
 5245: 
 5246: sub get_query_reply {
 5247:     my $queryid=shift;
 5248:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5249:     my $reply='';
 5250:     for (1..100) {
 5251: 	sleep 2;
 5252:         if (-e $replyfile.'.end') {
 5253: 	    if (open(my $fh,$replyfile)) {
 5254: 		$reply = join('',<$fh>);
 5255: 		close($fh);
 5256: 	   } else { return 'error: reply_file_error'; }
 5257:            return &unescape($reply);
 5258: 	}
 5259:     }
 5260:     return 'timeout:'.$queryid;
 5261: }
 5262: 
 5263: sub courselog_query {
 5264: #
 5265: # possible filters:
 5266: # url: url or symb
 5267: # username
 5268: # domain
 5269: # action: view, submit, grade
 5270: # start: timestamp
 5271: # end: timestamp
 5272: #
 5273:     my (%filters)=@_;
 5274:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5275:     if ($filters{'url'}) {
 5276: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5277:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5278:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5279:     }
 5280:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5281:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5282:     return &log_query($cname,$cdom,'courselog',%filters);
 5283: }
 5284: 
 5285: sub userlog_query {
 5286: #
 5287: # possible filters:
 5288: # action: log check role
 5289: # start: timestamp
 5290: # end: timestamp
 5291: #
 5292:     my ($uname,$udom,%filters)=@_;
 5293:     return &log_query($uname,$udom,'userlog',%filters);
 5294: }
 5295: 
 5296: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5297: 
 5298: sub auto_run {
 5299:     my ($cnum,$cdom) = @_;
 5300:     my $response = 0;
 5301:     my $settings;
 5302:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5303:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5304:         $settings = $domconfig{'autoenroll'};
 5305:         if ($settings->{'run'} eq '1') {
 5306:             $response = 1;
 5307:         }
 5308:     } else {
 5309:         my $homeserver;
 5310:         if (&is_course($cdom,$cnum)) {
 5311:             $homeserver = &homeserver($cnum,$cdom);
 5312:         } else {
 5313:             $homeserver = &domain($cdom,'primary');
 5314:         }
 5315:         if ($homeserver ne 'no_host') {
 5316:             $response = &reply('autorun:'.$cdom,$homeserver);
 5317:         }
 5318:     }
 5319:     return $response;
 5320: }
 5321: 
 5322: sub auto_get_sections {
 5323:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5324:     my $homeserver = &homeserver($cnum,$cdom);
 5325:     my @secs = ();
 5326:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5327:     unless ($response eq 'refused') {
 5328:         @secs = split(/:/,$response);
 5329:     }
 5330:     return @secs;
 5331: }
 5332: 
 5333: sub auto_new_course {
 5334:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5335:     my $homeserver = &homeserver($cnum,$cdom);
 5336:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5337:     return $response;
 5338: }
 5339: 
 5340: sub auto_validate_courseID {
 5341:     my ($cnum,$cdom,$inst_course_id) = @_;
 5342:     my $homeserver = &homeserver($cnum,$cdom);
 5343:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5344:     return $response;
 5345: }
 5346: 
 5347: sub auto_create_password {
 5348:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5349:     my ($homeserver,$response);
 5350:     my $create_passwd = 0;
 5351:     my $authchk = '';
 5352:     if ($udom =~ /^$match_domain$/) {
 5353:         $homeserver = &domain($udom,'primary');
 5354:     }
 5355:     if ($homeserver eq '') {
 5356:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5357:             $homeserver = &homeserver($cnum,$cdom);
 5358:         }
 5359:     }
 5360:     if ($homeserver eq '') {
 5361:         $authchk = 'nodomain';
 5362:     } else {
 5363:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5364:         if ($response eq 'refused') {
 5365:             $authchk = 'refused';
 5366:         } else {
 5367:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5368:         }
 5369:     }
 5370:     return ($authparam,$create_passwd,$authchk);
 5371: }
 5372: 
 5373: sub auto_photo_permission {
 5374:     my ($cnum,$cdom,$students) = @_;
 5375:     my $homeserver = &homeserver($cnum,$cdom);
 5376:     my ($outcome,$perm_reqd,$conditions) = 
 5377: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5378:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5379: 	return (undef,undef);
 5380:     }
 5381:     return ($outcome,$perm_reqd,$conditions);
 5382: }
 5383: 
 5384: sub auto_checkphotos {
 5385:     my ($uname,$udom,$pid) = @_;
 5386:     my $homeserver = &homeserver($uname,$udom);
 5387:     my ($result,$resulttype);
 5388:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5389: 				   &escape($uname).':'.&escape($pid),
 5390: 				   $homeserver));
 5391:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5392: 	return (undef,undef);
 5393:     }
 5394:     if ($outcome) {
 5395:         ($result,$resulttype) = split(/:/,$outcome);
 5396:     } 
 5397:     return ($result,$resulttype);
 5398: }
 5399: 
 5400: sub auto_photochoice {
 5401:     my ($cnum,$cdom) = @_;
 5402:     my $homeserver = &homeserver($cnum,$cdom);
 5403:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5404: 						       &escape($cdom),
 5405: 						       $homeserver)));
 5406:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5407: 	return (undef,undef);
 5408:     }
 5409:     return ($update,$comment);
 5410: }
 5411: 
 5412: sub auto_photoupdate {
 5413:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5414:     my $homeserver = &homeserver($cnum,$dom);
 5415:     my $host=&hostname($homeserver);
 5416:     my $cmd = '';
 5417:     my $maxtries = 1;
 5418:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5419:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5420:     }
 5421:     $cmd =~ s/%%$//;
 5422:     $cmd = &escape($cmd);
 5423:     my $query = 'institutionalphotos';
 5424:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5425:     unless ($queryid=~/^\Q$host\E\_/) {
 5426:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5427:         return 'error: '.$queryid;
 5428:     }
 5429:     my $reply = &get_query_reply($queryid);
 5430:     my $tries = 1;
 5431:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5432:         $reply = &get_query_reply($queryid);
 5433:         $tries ++;
 5434:     }
 5435:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5436:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5437:     } else {
 5438:         my @responses = split(/:/,$reply);
 5439:         my $outcome = shift(@responses); 
 5440:         foreach my $item (@responses) {
 5441:             my ($key,$value) = split(/=/,$item);
 5442:             $$photo{$key} = $value;
 5443:         }
 5444:         return $outcome;
 5445:     }
 5446:     return 'error';
 5447: }
 5448: 
 5449: sub auto_instcode_format {
 5450:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5451: 	$cat_order) = @_;
 5452:     my $courses = '';
 5453:     my @homeservers;
 5454:     if ($caller eq 'global') {
 5455: 	my %servers = &get_servers($codedom,'library');
 5456: 	foreach my $tryserver (keys(%servers)) {
 5457: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5458: 		push(@homeservers,$tryserver);
 5459: 	    }
 5460:         }
 5461:     } else {
 5462:         push(@homeservers,&homeserver($caller,$codedom));
 5463:     }
 5464:     foreach my $code (keys(%{$instcodes})) {
 5465:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5466:     }
 5467:     chop($courses);
 5468:     my $ok_response = 0;
 5469:     my $response;
 5470:     while (@homeservers > 0 && $ok_response == 0) {
 5471:         my $server = shift(@homeservers); 
 5472:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5473:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5474:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5475: 		split(/:/,$response);
 5476:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5477:             push(@{$codetitles},&str2array($codetitles_str));
 5478:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5479:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5480:             $ok_response = 1;
 5481:         }
 5482:     }
 5483:     if ($ok_response) {
 5484:         return 'ok';
 5485:     } else {
 5486:         return $response;
 5487:     }
 5488: }
 5489: 
 5490: sub auto_instcode_defaults {
 5491:     my ($domain,$returnhash,$code_order) = @_;
 5492:     my @homeservers;
 5493: 
 5494:     my %servers = &get_servers($domain,'library');
 5495:     foreach my $tryserver (keys(%servers)) {
 5496: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5497: 	    push(@homeservers,$tryserver);
 5498: 	}
 5499:     }
 5500: 
 5501:     my $response;
 5502:     foreach my $server (@homeservers) {
 5503:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5504:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5505: 	
 5506: 	foreach my $pair (split(/\&/,$response)) {
 5507: 	    my ($name,$value)=split(/\=/,$pair);
 5508: 	    if ($name eq 'code_order') {
 5509: 		@{$code_order} = split(/\&/,&unescape($value));
 5510: 	    } else {
 5511: 		$returnhash->{&unescape($name)}=&unescape($value);
 5512: 	    }
 5513: 	}
 5514: 	return 'ok';
 5515:     }
 5516: 
 5517:     return $response;
 5518: } 
 5519: 
 5520: sub auto_validate_class_sec {
 5521:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5522:     my $homeserver = &homeserver($cnum,$cdom);
 5523:     my $ownerlist;
 5524:     if (ref($owners) eq 'ARRAY') {
 5525:         $ownerlist = join(',',@{$owners});
 5526:     } else {
 5527:         $ownerlist = $owners;
 5528:     }
 5529:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5530:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5531:     return $response;
 5532: }
 5533: 
 5534: # ------------------------------------------------------- Course Group routines
 5535: 
 5536: sub get_coursegroups {
 5537:     my ($cdom,$cnum,$group,$namespace) = @_;
 5538:     return(&dump($namespace,$cdom,$cnum,$group));
 5539: }
 5540: 
 5541: sub modify_coursegroup {
 5542:     my ($cdom,$cnum,$groupsettings) = @_;
 5543:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5544: }
 5545: 
 5546: sub toggle_coursegroup_status {
 5547:     my ($cdom,$cnum,$group,$action) = @_;
 5548:     my ($from_namespace,$to_namespace);
 5549:     if ($action eq 'delete') {
 5550:         $from_namespace = 'coursegroups';
 5551:         $to_namespace = 'deleted_groups';
 5552:     } else {
 5553:         $from_namespace = 'deleted_groups';
 5554:         $to_namespace = 'coursegroups';
 5555:     }
 5556:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5557:     if (my $tmp = &error(%curr_group)) {
 5558:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5559:         return ('read error',$tmp);
 5560:     } else {
 5561:         my %savedsettings = %curr_group; 
 5562:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5563:         my $deloutcome;
 5564:         if ($result eq 'ok') {
 5565:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5566:         } else {
 5567:             return ('write error',$result);
 5568:         }
 5569:         if ($deloutcome eq 'ok') {
 5570:             return 'ok';
 5571:         } else {
 5572:             return ('delete error',$deloutcome);
 5573:         }
 5574:     }
 5575: }
 5576: 
 5577: sub modify_group_roles {
 5578:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5579:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5580:     my $role = 'gr/'.&escape($userprivs);
 5581:     my ($uname,$udom) = split(/:/,$user);
 5582:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5583:     if ($result eq 'ok') {
 5584:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5585:     }
 5586:     return $result;
 5587: }
 5588: 
 5589: sub modify_coursegroup_membership {
 5590:     my ($cdom,$cnum,$membership) = @_;
 5591:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5592:     return $result;
 5593: }
 5594: 
 5595: sub get_active_groups {
 5596:     my ($udom,$uname,$cdom,$cnum) = @_;
 5597:     my $now = time;
 5598:     my %groups = ();
 5599:     foreach my $key (keys(%env)) {
 5600:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5601:             my ($start,$end) = split(/\./,$env{$key});
 5602:             if (($end!=0) && ($end<$now)) { next; }
 5603:             if (($start!=0) && ($start>$now)) { next; }
 5604:             if ($1 eq $cdom && $2 eq $cnum) {
 5605:                 $groups{$3} = $env{$key} ;
 5606:             }
 5607:         }
 5608:     }
 5609:     return %groups;
 5610: }
 5611: 
 5612: sub get_group_membership {
 5613:     my ($cdom,$cnum,$group) = @_;
 5614:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5615: }
 5616: 
 5617: sub get_users_groups {
 5618:     my ($udom,$uname,$courseid) = @_;
 5619:     my @usersgroups;
 5620:     my $cachetime=1800;
 5621: 
 5622:     my $hashid="$udom:$uname:$courseid";
 5623:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5624:     if (defined($cached)) {
 5625:         @usersgroups = split(/:/,$grouplist);
 5626:     } else {  
 5627:         $grouplist = '';
 5628:         my $courseurl = &courseid_to_courseurl($courseid);
 5629:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5630:         my $access_end = $env{'course.'.$courseid.
 5631:                               '.default_enrollment_end_date'};
 5632:         my $now = time;
 5633:         foreach my $key (keys(%roleshash)) {
 5634:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5635:                 my $group = $1;
 5636:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5637:                     my $start = $2;
 5638:                     my $end = $1;
 5639:                     if ($start == -1) { next; } # deleted from group
 5640:                     if (($start!=0) && ($start>$now)) { next; }
 5641:                     if (($end!=0) && ($end<$now)) {
 5642:                         if ($access_end && $access_end < $now) {
 5643:                             if ($access_end - $end < 86400) {
 5644:                                 push(@usersgroups,$group);
 5645:                             }
 5646:                         }
 5647:                         next;
 5648:                     }
 5649:                     push(@usersgroups,$group);
 5650:                 }
 5651:             }
 5652:         }
 5653:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5654:         $grouplist = join(':',@usersgroups);
 5655:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5656:     }
 5657:     return @usersgroups;
 5658: }
 5659: 
 5660: sub devalidate_getgroups_cache {
 5661:     my ($udom,$uname,$cdom,$cnum)=@_;
 5662:     my $courseid = $cdom.'_'.$cnum;
 5663: 
 5664:     my $hashid="$udom:$uname:$courseid";
 5665:     &devalidate_cache_new('getgroups',$hashid);
 5666: }
 5667: 
 5668: # ------------------------------------------------------------------ Plain Text
 5669: 
 5670: sub plaintext {
 5671:     my ($short,$type,$cid) = @_;
 5672:     if ($short =~ /^cr/) {
 5673: 	return (split('/',$short))[-1];
 5674:     }
 5675:     if (!defined($cid)) {
 5676:         $cid = $env{'request.course.id'};
 5677:     }
 5678:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5679:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5680:                                           '.plaintext'});
 5681:     }
 5682:     my %rolenames = (
 5683:                       Course => 'std',
 5684:                       Group => 'alt1',
 5685:                     );
 5686:     if (defined($type) && 
 5687:          defined($rolenames{$type}) && 
 5688:          defined($prp{$short}{$rolenames{$type}})) {
 5689:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5690:     } else {
 5691:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5692:     }
 5693: }
 5694: 
 5695: # ----------------------------------------------------------------- Assign Role
 5696: 
 5697: sub assignrole {
 5698:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5699:         $context)=@_;
 5700:     my $mrole;
 5701:     if ($role =~ /^cr\//) {
 5702:         my $cwosec=$url;
 5703:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5704: 	unless (&allowed('ccr',$cwosec)) {
 5705:            &logthis('Refused custom assignrole: '.
 5706:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5707: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5708:            return 'refused'; 
 5709:         }
 5710:         $mrole='cr';
 5711:     } elsif ($role =~ /^gr\//) {
 5712:         my $cwogrp=$url;
 5713:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5714:         unless (&allowed('mdg',$cwogrp)) {
 5715:             &logthis('Refused group assignrole: '.
 5716:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5717:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5718:             return 'refused';
 5719:         }
 5720:         $mrole='gr';
 5721:     } else {
 5722:         my $cwosec=$url;
 5723:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5724:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5725:             my $refused;
 5726:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5727:                 if (!(&allowed('c'.$role,$url))) {
 5728:                     $refused = 1;
 5729:                 }
 5730:             } else {
 5731:                 $refused = 1;
 5732:             }
 5733:             if ($refused) {
 5734:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5735:                     $refused = '';
 5736:                 } else {
 5737:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5738:                              ' '.$role.' '.$end.' '.$start.' by '.
 5739: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5740:                     return 'refused';
 5741:                 }
 5742:             }
 5743:         }
 5744:         $mrole=$role;
 5745:     }
 5746:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5747:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5748:     if ($end) { $command.='_'.$end; }
 5749:     if ($start) {
 5750: 	if ($end) { 
 5751:            $command.='_'.$start; 
 5752:         } else {
 5753:            $command.='_0_'.$start;
 5754:         }
 5755:     }
 5756:     my $origstart = $start;
 5757:     my $origend = $end;
 5758:     my $delflag;
 5759: # actually delete
 5760:     if ($deleteflag) {
 5761: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5762: # modify command to delete the role
 5763:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5764:                 "$udom:$uname:$url".'_'."$mrole";
 5765: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5766: # set start and finish to negative values for userrolelog
 5767:            $start=-1;
 5768:            $end=-1;
 5769:            $delflag = 1;
 5770:         }
 5771:     }
 5772: # send command
 5773:     my $answer=&reply($command,&homeserver($uname,$udom));
 5774: # log new user role if status is ok
 5775:     if ($answer eq 'ok') {
 5776: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5777: # for course roles, perform group memberships changes triggered by role change.
 5778:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5779:         unless ($role =~ /^gr/) {
 5780:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5781:                                              $origstart,$selfenroll,$context);
 5782:         }
 5783:     }
 5784:     return $answer;
 5785: }
 5786: 
 5787: # -------------------------------------------------- Modify user authentication
 5788: # Overrides without validation
 5789: 
 5790: sub modifyuserauth {
 5791:     my ($udom,$uname,$umode,$upass)=@_;
 5792:     my $uhome=&homeserver($uname,$udom);
 5793:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5794:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5795:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5796:              ' in domain '.$env{'request.role.domain'});  
 5797:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5798: 		     &escape($upass),$uhome);
 5799:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5800:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5801:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5802:     &log($udom,,$uname,$uhome,
 5803:         'Authentication changed by '.$env{'user.domain'}.', '.
 5804:                                      $env{'user.name'}.', '.$umode.
 5805:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5806:     unless ($reply eq 'ok') {
 5807:         &logthis('Authentication mode error: '.$reply);
 5808: 	return 'error: '.$reply;
 5809:     }   
 5810:     return 'ok';
 5811: }
 5812: 
 5813: # --------------------------------------------------------------- Modify a user
 5814: 
 5815: sub modifyuser {
 5816:     my ($udom,    $uname, $uid,
 5817:         $umode,   $upass, $first,
 5818:         $middle,  $last,  $gene,
 5819:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5820:     $udom= &LONCAPA::clean_domain($udom);
 5821:     $uname=&LONCAPA::clean_username($uname);
 5822:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5823:              $umode.', '.$first.', '.$middle.', '.
 5824: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5825:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5826:                                      ' desiredhome not specified'). 
 5827:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5828:              ' in domain '.$env{'request.role.domain'});
 5829:     my $uhome=&homeserver($uname,$udom,'true');
 5830: # ----------------------------------------------------------------- Create User
 5831:     if (($uhome eq 'no_host') && 
 5832: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5833:         my $unhome='';
 5834:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5835:             $unhome = $desiredhome;
 5836: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5837: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5838:         } else { # load balancing routine for determining $unhome
 5839:             my $loadm=10000000;
 5840: 	    my %servers = &get_servers($udom,'library');
 5841: 	    foreach my $tryserver (keys(%servers)) {
 5842: 		my $answer=reply('load',$tryserver);
 5843: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5844: 		    $loadm=$answer;
 5845: 		    $unhome=$tryserver;
 5846: 		}
 5847: 	    }
 5848:         }
 5849:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5850: 	    return 'error: unable to find a home server for '.$uname.
 5851:                    ' in domain '.$udom;
 5852:         }
 5853:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5854:                          &escape($upass),$unhome);
 5855: 	unless ($reply eq 'ok') {
 5856:             return 'error: '.$reply;
 5857:         }   
 5858:         $uhome=&homeserver($uname,$udom,'true');
 5859:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5860: 	    return 'error: unable verify users home machine.';
 5861:         }
 5862:     }   # End of creation of new user
 5863: # ---------------------------------------------------------------------- Add ID
 5864:     if ($uid) {
 5865:        $uid=~tr/A-Z/a-z/;
 5866:        my %uidhash=&idrget($udom,$uname);
 5867:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5868:          && (!$forceid)) {
 5869: 	  unless ($uid eq $uidhash{$uname}) {
 5870: 	      return 'error: user id "'.$uid.'" does not match '.
 5871:                   'current user id "'.$uidhash{$uname}.'".';
 5872:           }
 5873:        } else {
 5874: 	  &idput($udom,($uname => $uid));
 5875:        }
 5876:     }
 5877: # -------------------------------------------------------------- Add names, etc
 5878:     my @tmp=&get('environment',
 5879: 		   ['firstname','middlename','lastname','generation','id',
 5880:                     'permanentemail','inststatus'],
 5881: 		   $udom,$uname);
 5882:     my %names;
 5883:     if ($tmp[0] =~ m/^error:.*/) { 
 5884:         %names=(); 
 5885:     } else {
 5886:         %names = @tmp;
 5887:     }
 5888: #
 5889: # Make sure to not trash student environment if instructor does not bother
 5890: # to supply name and email information
 5891: #
 5892:     if ($first)  { $names{'firstname'}  = $first; }
 5893:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5894:     if ($last)   { $names{'lastname'}   = $last; }
 5895:     if (defined($gene))   { $names{'generation'} = $gene; }
 5896:     if ($email) {
 5897:        $email=~s/[^\w\@\.\-\,]//gs;
 5898:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5899:     }
 5900:     if ($uid) { $names{'id'}  = $uid; }
 5901:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5902:     my $reply = &put('environment', \%names, $udom,$uname);
 5903:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5904:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5905:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5906:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5907:                  $umode.', '.$first.', '.$middle.', '.
 5908: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5909:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5910:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5911:     } else {
 5912:         $logmsg .= ' during self creation';
 5913:     }
 5914:     &logthis($logmsg);
 5915:     return 'ok';
 5916: }
 5917: 
 5918: # -------------------------------------------------------------- Modify student
 5919: 
 5920: sub modifystudent {
 5921:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5922:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5923:         $selfenroll,$context)=@_;
 5924:     if (!$cid) {
 5925: 	unless ($cid=$env{'request.course.id'}) {
 5926: 	    return 'not_in_class';
 5927: 	}
 5928:     }
 5929: # --------------------------------------------------------------- Make the user
 5930:     my $reply=&modifyuser
 5931: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5932:          $desiredhome,$email);
 5933:     unless ($reply eq 'ok') { return $reply; }
 5934:     # This will cause &modify_student_enrollment to get the uid from the
 5935:     # students environment
 5936:     $uid = undef if (!$forceid);
 5937:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5938: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5939:     return $reply;
 5940: }
 5941: 
 5942: sub modify_student_enrollment {
 5943:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5944:     my ($cdom,$cnum,$chome);
 5945:     if (!$cid) {
 5946: 	unless ($cid=$env{'request.course.id'}) {
 5947: 	    return 'not_in_class';
 5948: 	}
 5949: 	$cdom=$env{'course.'.$cid.'.domain'};
 5950: 	$cnum=$env{'course.'.$cid.'.num'};
 5951:     } else {
 5952: 	($cdom,$cnum)=split(/_/,$cid);
 5953:     }
 5954:     $chome=$env{'course.'.$cid.'.home'};
 5955:     if (!$chome) {
 5956: 	$chome=&homeserver($cnum,$cdom);
 5957:     }
 5958:     if (!$chome) { return 'unknown_course'; }
 5959:     # Make sure the user exists
 5960:     my $uhome=&homeserver($uname,$udom);
 5961:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5962: 	return 'error: no such user';
 5963:     }
 5964:     # Get student data if we were not given enough information
 5965:     if (!defined($first)  || $first  eq '' || 
 5966:         !defined($last)   || $last   eq '' || 
 5967:         !defined($uid)    || $uid    eq '' || 
 5968:         !defined($middle) || $middle eq '' || 
 5969:         !defined($gene)   || $gene   eq '') {
 5970:         # They did not supply us with enough data to enroll the student, so
 5971:         # we need to pick up more information.
 5972:         my %tmp = &get('environment',
 5973:                        ['firstname','middlename','lastname', 'generation','id']
 5974:                        ,$udom,$uname);
 5975: 
 5976:         #foreach my $key (keys(%tmp)) {
 5977:         #    &logthis("key $key = ".$tmp{$key});
 5978:         #}
 5979:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5980:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5981:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5982:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5983:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5984:     }
 5985:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5986:     my $reply=cput('classlist',
 5987: 		   {"$uname:$udom" => 
 5988: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5989: 		   $cdom,$cnum);
 5990:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5991: 	return 'error: '.$reply;
 5992:     } else {
 5993: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5994:     }
 5995:     # Add student role to user
 5996:     my $uurl='/'.$cid;
 5997:     $uurl=~s/\_/\//g;
 5998:     if ($usec) {
 5999: 	$uurl.='/'.$usec;
 6000:     }
 6001:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6002: }
 6003: 
 6004: sub format_name {
 6005:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6006:     my $name;
 6007:     if ($first ne 'lastname') {
 6008: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6009:     } else {
 6010: 	if ($lastname=~/\S/) {
 6011: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6012: 	    $name=~s/\s+,/,/;
 6013: 	} else {
 6014: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6015: 	}
 6016:     }
 6017:     $name=~s/^\s+//;
 6018:     $name=~s/\s+$//;
 6019:     $name=~s/\s+/ /g;
 6020:     return $name;
 6021: }
 6022: 
 6023: # ------------------------------------------------- Write to course preferences
 6024: 
 6025: sub writecoursepref {
 6026:     my ($courseid,%prefs)=@_;
 6027:     $courseid=~s/^\///;
 6028:     $courseid=~s/\_/\//g;
 6029:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6030:     my $chome=homeserver($cnum,$cdomain);
 6031:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6032: 	return 'error: no such course';
 6033:     }
 6034:     my $cstring='';
 6035:     foreach my $pref (keys(%prefs)) {
 6036: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6037:     }
 6038:     $cstring=~s/\&$//;
 6039:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6040: }
 6041: 
 6042: # ---------------------------------------------------------- Make/modify course
 6043: 
 6044: sub createcourse {
 6045:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6046:         $course_owner,$crstype)=@_;
 6047:     $url=&declutter($url);
 6048:     my $cid='';
 6049:     unless (&allowed('ccc',$udom)) {
 6050:         return 'refused';
 6051:     }
 6052: # ------------------------------------------------------------------- Create ID
 6053:    my $uname=int(1+rand(9)).
 6054:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6055:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6056:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6057: # ----------------------------------------------- Make sure that does not exist
 6058:    my $uhome=&homeserver($uname,$udom,'true');
 6059:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6060:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6061:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6062:        $uhome=&homeserver($uname,$udom,'true');       
 6063:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6064:            return 'error: unable to generate unique course-ID';
 6065:        } 
 6066:    }
 6067: # ------------------------------------------------ Check supplied server name
 6068:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6069:     if (! &is_library($course_server)) {
 6070:         return 'error:bad server name '.$course_server;
 6071:     }
 6072: # ------------------------------------------------------------- Make the course
 6073:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6074:                       $course_server);
 6075:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6076:     $uhome=&homeserver($uname,$udom,'true');
 6077:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6078: 	return 'error: no such course';
 6079:     }
 6080: # ----------------------------------------------------------------- Course made
 6081: # log existence
 6082:     my $newcourse = {
 6083:                     $udom.'_'.$uname => {
 6084:                                      description => $description,
 6085:                                      inst_code   => $inst_code,
 6086:                                      owner       => $course_owner,
 6087:                                      type        => $crstype,
 6088:                                                 },
 6089:                     };
 6090:     &courseidput($udom,$newcourse,$uhome,'notime');
 6091: # set toplevel url
 6092:     my $topurl=$url;
 6093:     unless ($nonstandard) {
 6094: # ------------------------------------------ For standard courses, make top url
 6095:         my $mapurl=&clutter($url);
 6096:         if ($mapurl eq '/res/') { $mapurl=''; }
 6097:         $env{'form.initmap'}=(<<ENDINITMAP);
 6098: <map>
 6099: <resource id="1" type="start"></resource>
 6100: <resource id="2" src="$mapurl"></resource>
 6101: <resource id="3" type="finish"></resource>
 6102: <link index="1" from="1" to="2"></link>
 6103: <link index="2" from="2" to="3"></link>
 6104: </map>
 6105: ENDINITMAP
 6106:         $topurl=&declutter(
 6107:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6108:                           );
 6109:     }
 6110: # ----------------------------------------------------------- Write preferences
 6111:     &writecoursepref($udom.'_'.$uname,
 6112:                      ('description' => $description,
 6113:                       'url'         => $topurl));
 6114:     return '/'.$udom.'/'.$uname;
 6115: }
 6116: 
 6117: sub is_course {
 6118:     my ($cdom,$cnum) = @_;
 6119:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6120: 				undef,'.');
 6121:     if (exists($courses{$cdom.'_'.$cnum})) {
 6122:         return 1;
 6123:     }
 6124:     return 0;
 6125: }
 6126: 
 6127: # ---------------------------------------------------------- Assign Custom Role
 6128: 
 6129: sub assigncustomrole {
 6130:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6131:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6132:                        $end,$start,$deleteflag,$selfenroll,$context);
 6133: }
 6134: 
 6135: # ----------------------------------------------------------------- Revoke Role
 6136: 
 6137: sub revokerole {
 6138:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6139:     my $now=time;
 6140:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6141: }
 6142: 
 6143: # ---------------------------------------------------------- Revoke Custom Role
 6144: 
 6145: sub revokecustomrole {
 6146:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6147:     my $now=time;
 6148:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6149:            $deleteflag,$selfenroll,$context);
 6150: }
 6151: 
 6152: # ------------------------------------------------------------ Disk usage
 6153: sub diskusage {
 6154:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6155:     $directorypath =~ s/\/$//;
 6156:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6157:                        .&escape($getpropath).':'.&escape($uname).':'
 6158:                        .&escape($udom),homeserver($uname,$udom));
 6159:     if ($listing eq 'unknown_cmd') {
 6160:         if ($getpropath) {
 6161:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6162:         }
 6163:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6164:     }
 6165:     return $listing;
 6166: }
 6167: 
 6168: sub is_locked {
 6169:     my ($file_name, $domain, $user) = @_;
 6170:     my @check;
 6171:     my $is_locked;
 6172:     push @check, $file_name;
 6173:     my %locked = &get('file_permissions',\@check,
 6174: 		      $env{'user.domain'},$env{'user.name'});
 6175:     my ($tmp)=keys(%locked);
 6176:     if ($tmp=~/^error:/) { undef(%locked); }
 6177:     
 6178:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6179:         $is_locked = 'false';
 6180:         foreach my $entry (@{$locked{$file_name}}) {
 6181:            if (ref($entry) eq 'ARRAY') { 
 6182:                $is_locked = 'true';
 6183:                last;
 6184:            }
 6185:        }
 6186:     } else {
 6187:         $is_locked = 'false';
 6188:     }
 6189: }
 6190: 
 6191: sub declutter_portfile {
 6192:     my ($file) = @_;
 6193:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6194:     return $file;
 6195: }
 6196: 
 6197: # ------------------------------------------------------------- Mark as Read Only
 6198: 
 6199: sub mark_as_readonly {
 6200:     my ($domain,$user,$files,$what) = @_;
 6201:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6202:     my ($tmp)=keys(%current_permissions);
 6203:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6204:     foreach my $file (@{$files}) {
 6205: 	$file = &declutter_portfile($file);
 6206:         push(@{$current_permissions{$file}},$what);
 6207:     }
 6208:     &put('file_permissions',\%current_permissions,$domain,$user);
 6209:     return;
 6210: }
 6211: 
 6212: # ------------------------------------------------------------Save Selected Files
 6213: 
 6214: sub save_selected_files {
 6215:     my ($user, $path, @files) = @_;
 6216:     my $filename = $user."savedfiles";
 6217:     my @other_files = &files_not_in_path($user, $path);
 6218:     open (OUT, '>'.$tmpdir.$filename);
 6219:     foreach my $file (@files) {
 6220:         print (OUT $env{'form.currentpath'}.$file."\n");
 6221:     }
 6222:     foreach my $file (@other_files) {
 6223:         print (OUT $file."\n");
 6224:     }
 6225:     close (OUT);
 6226:     return 'ok';
 6227: }
 6228: 
 6229: sub clear_selected_files {
 6230:     my ($user) = @_;
 6231:     my $filename = $user."savedfiles";
 6232:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6233:     print (OUT undef);
 6234:     close (OUT);
 6235:     return ("ok");    
 6236: }
 6237: 
 6238: sub files_in_path {
 6239:     my ($user, $path) = @_;
 6240:     my $filename = $user."savedfiles";
 6241:     my %return_files;
 6242:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6243:     while (my $line_in = <IN>) {
 6244:         chomp ($line_in);
 6245:         my @paths_and_file = split (m!/!, $line_in);
 6246:         my $file_part = pop (@paths_and_file);
 6247:         my $path_part = join ('/', @paths_and_file);
 6248:         $path_part.='/';
 6249:         my $path_and_file = $path_part.$file_part;
 6250:         if ($path_part eq $path) {
 6251:             $return_files{$file_part}= 'selected';
 6252:         }
 6253:     }
 6254:     close (IN);
 6255:     return (\%return_files);
 6256: }
 6257: 
 6258: # called in portfolio select mode, to show files selected NOT in current directory
 6259: sub files_not_in_path {
 6260:     my ($user, $path) = @_;
 6261:     my $filename = $user."savedfiles";
 6262:     my @return_files;
 6263:     my $path_part;
 6264:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6265:     while (my $line = <IN>) {
 6266:         #ok, I know it's clunky, but I want it to work
 6267:         my @paths_and_file = split(m|/|, $line);
 6268:         my $file_part = pop(@paths_and_file);
 6269:         chomp($file_part);
 6270:         my $path_part = join('/', @paths_and_file);
 6271:         $path_part .= '/';
 6272:         my $path_and_file = $path_part.$file_part;
 6273:         if ($path_part ne $path) {
 6274:             push(@return_files, ($path_and_file));
 6275:         }
 6276:     }
 6277:     close(OUT);
 6278:     return (@return_files);
 6279: }
 6280: 
 6281: #----------------------------------------------Get portfolio file permissions
 6282: 
 6283: sub get_portfile_permissions {
 6284:     my ($domain,$user) = @_;
 6285:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6286:     my ($tmp)=keys(%current_permissions);
 6287:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6288:     return \%current_permissions;
 6289: }
 6290: 
 6291: #---------------------------------------------Get portfolio file access controls
 6292: 
 6293: sub get_access_controls {
 6294:     my ($current_permissions,$group,$file) = @_;
 6295:     my %access;
 6296:     my $real_file = $file;
 6297:     $file =~ s/\.meta$//;
 6298:     if (defined($file)) {
 6299:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6300:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6301:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6302:             }
 6303:         }
 6304:     } else {
 6305:         foreach my $key (keys(%{$current_permissions})) {
 6306:             if ($key =~ /\0accesscontrol$/) {
 6307:                 if (defined($group)) {
 6308:                     if ($key !~ m-^\Q$group\E/-) {
 6309:                         next;
 6310:                     }
 6311:                 }
 6312:                 my ($fullpath) = split(/\0/,$key);
 6313:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6314:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6315:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6316:                     }
 6317:                 }
 6318:             }
 6319:         }
 6320:     }
 6321:     return %access;
 6322: }
 6323: 
 6324: sub modify_access_controls {
 6325:     my ($file_name,$changes,$domain,$user)=@_;
 6326:     my ($outcome,$deloutcome);
 6327:     my %store_permissions;
 6328:     my %new_values;
 6329:     my %new_control;
 6330:     my %translation;
 6331:     my @deletions = ();
 6332:     my $now = time;
 6333:     if (exists($$changes{'activate'})) {
 6334:         if (ref($$changes{'activate'}) eq 'HASH') {
 6335:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6336:             my $numnew = scalar(@newitems);
 6337:             for (my $i=0; $i<$numnew; $i++) {
 6338:                 my $newkey = $newitems[$i];
 6339:                 my $newid = &Apache::loncommon::get_cgi_id();
 6340:                 if ($newkey =~ /^\d+:/) { 
 6341:                     $newkey =~ s/^(\d+)/$newid/;
 6342:                     $translation{$1} = $newid;
 6343:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6344:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6345:                     $translation{$1} = $newid;
 6346:                 }
 6347:                 $new_values{$file_name."\0".$newkey} = 
 6348:                                           $$changes{'activate'}{$newitems[$i]};
 6349:                 $new_control{$newkey} = $now;
 6350:             }
 6351:         }
 6352:     }
 6353:     my %todelete;
 6354:     my %changed_items;
 6355:     foreach my $action ('delete','update') {
 6356:         if (exists($$changes{$action})) {
 6357:             if (ref($$changes{$action}) eq 'HASH') {
 6358:                 foreach my $key (keys(%{$$changes{$action}})) {
 6359:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6360:                     if ($action eq 'delete') { 
 6361:                         $todelete{$itemnum} = 1;
 6362:                     } else {
 6363:                         $changed_items{$itemnum} = $key;
 6364:                     }
 6365:                 }
 6366:             }
 6367:         }
 6368:     }
 6369:     # get lock on access controls for file.
 6370:     my $lockhash = {
 6371:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6372:                                                        ':'.$env{'user.domain'},
 6373:                    }; 
 6374:     my $tries = 0;
 6375:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6376:    
 6377:     while (($gotlock ne 'ok') && $tries <3) {
 6378:         $tries ++;
 6379:         sleep 1;
 6380:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6381:     }
 6382:     if ($gotlock eq 'ok') {
 6383:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6384:         my ($tmp)=keys(%curr_permissions);
 6385:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6386:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6387:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6388:             if (ref($curr_controls) eq 'HASH') {
 6389:                 foreach my $control_item (keys(%{$curr_controls})) {
 6390:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6391:                     if (defined($todelete{$itemnum})) {
 6392:                         push(@deletions,$file_name."\0".$control_item);
 6393:                     } else {
 6394:                         if (defined($changed_items{$itemnum})) {
 6395:                             $new_control{$changed_items{$itemnum}} = $now;
 6396:                             push(@deletions,$file_name."\0".$control_item);
 6397:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6398:                         } else {
 6399:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6400:                         }
 6401:                     }
 6402:                 }
 6403:             }
 6404:         }
 6405:         my ($group);
 6406:         if (&is_course($domain,$user)) {
 6407:             ($group,my $file) = split(/\//,$file_name,2);
 6408:         }
 6409:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6410:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6411:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6412:         #  remove lock
 6413:         my @del_lock = ($file_name."\0".'locked_access_records');
 6414:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6415:         my $sqlresult =
 6416:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6417:                                     $group);
 6418:     } else {
 6419:         $outcome = "error: could not obtain lockfile\n";  
 6420:     }
 6421:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6422: }
 6423: 
 6424: sub make_public_indefinitely {
 6425:     my ($requrl) = @_;
 6426:     my $now = time;
 6427:     my $action = 'activate';
 6428:     my $aclnum = 0;
 6429:     if (&is_portfolio_url($requrl)) {
 6430:         my (undef,$udom,$unum,$file_name,$group) =
 6431:             &parse_portfolio_url($requrl);
 6432:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6433:         my %access_controls = &get_access_controls($current_perms,
 6434:                                                    $group,$file_name);
 6435:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6436:             my ($num,$scope,$end,$start) = 
 6437:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6438:             if ($scope eq 'public') {
 6439:                 if ($start <= $now && $end == 0) {
 6440:                     $action = 'none';
 6441:                 } else {
 6442:                     $action = 'update';
 6443:                     $aclnum = $num;
 6444:                 }
 6445:                 last;
 6446:             }
 6447:         }
 6448:         if ($action eq 'none') {
 6449:              return 'ok';
 6450:         } else {
 6451:             my %changes;
 6452:             my $newend = 0;
 6453:             my $newstart = $now;
 6454:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6455:             $changes{$action}{$newkey} = {
 6456:                 type => 'public',
 6457:                 time => {
 6458:                     start => $newstart,
 6459:                     end   => $newend,
 6460:                 },
 6461:             };
 6462:             my ($outcome,$deloutcome,$new_values,$translation) =
 6463:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6464:             return $outcome;
 6465:         }
 6466:     } else {
 6467:         return 'invalid';
 6468:     }
 6469: }
 6470: 
 6471: #------------------------------------------------------Get Marked as Read Only
 6472: 
 6473: sub get_marked_as_readonly {
 6474:     my ($domain,$user,$what,$group) = @_;
 6475:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6476:     my @readonly_files;
 6477:     my $cmp1=$what;
 6478:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6479:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6480:         if (defined($group)) {
 6481:             if ($file_name !~ m-^\Q$group\E/-) {
 6482:                 next;
 6483:             }
 6484:         }
 6485:         if (ref($value) eq "ARRAY"){
 6486:             foreach my $stored_what (@{$value}) {
 6487:                 my $cmp2=$stored_what;
 6488:                 if (ref($stored_what) eq 'ARRAY') {
 6489:                     $cmp2=join('',@{$stored_what});
 6490:                 }
 6491:                 if ($cmp1 eq $cmp2) {
 6492:                     push(@readonly_files, $file_name);
 6493:                     last;
 6494:                 } elsif (!defined($what)) {
 6495:                     push(@readonly_files, $file_name);
 6496:                     last;
 6497:                 }
 6498:             }
 6499:         }
 6500:     }
 6501:     return @readonly_files;
 6502: }
 6503: #-----------------------------------------------------------Get Marked as Read Only Hash
 6504: 
 6505: sub get_marked_as_readonly_hash {
 6506:     my ($current_permissions,$group,$what) = @_;
 6507:     my %readonly_files;
 6508:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6509:         if (defined($group)) {
 6510:             if ($file_name !~ m-^\Q$group\E/-) {
 6511:                 next;
 6512:             }
 6513:         }
 6514:         if (ref($value) eq "ARRAY"){
 6515:             foreach my $stored_what (@{$value}) {
 6516:                 if (ref($stored_what) eq 'ARRAY') {
 6517:                     foreach my $lock_descriptor(@{$stored_what}) {
 6518:                         if ($lock_descriptor eq 'graded') {
 6519:                             $readonly_files{$file_name} = 'graded';
 6520:                         } elsif ($lock_descriptor eq 'handback') {
 6521:                             $readonly_files{$file_name} = 'handback';
 6522:                         } else {
 6523:                             if (!exists($readonly_files{$file_name})) {
 6524:                                 $readonly_files{$file_name} = 'locked';
 6525:                             }
 6526:                         }
 6527:                     }
 6528:                 } 
 6529:             }
 6530:         } 
 6531:     }
 6532:     return %readonly_files;
 6533: }
 6534: # ------------------------------------------------------------ Unmark as Read Only
 6535: 
 6536: sub unmark_as_readonly {
 6537:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6538:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6539:     my ($domain,$user,$what,$file_name,$group) = @_;
 6540:     $file_name = &declutter_portfile($file_name);
 6541:     my $symb_crs = $what;
 6542:     if (ref($what)) { $symb_crs=join('',@$what); }
 6543:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6544:     my ($tmp)=keys(%current_permissions);
 6545:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6546:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6547:     foreach my $file (@readonly_files) {
 6548: 	my $clean_file = &declutter_portfile($file);
 6549: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6550: 	my $current_locks = $current_permissions{$file};
 6551:         my @new_locks;
 6552:         my @del_keys;
 6553:         if (ref($current_locks) eq "ARRAY"){
 6554:             foreach my $locker (@{$current_locks}) {
 6555:                 my $compare=$locker;
 6556:                 if (ref($locker) eq 'ARRAY') {
 6557:                     $compare=join('',@{$locker});
 6558:                     if ($compare ne $symb_crs) {
 6559:                         push(@new_locks, $locker);
 6560:                     }
 6561:                 }
 6562:             }
 6563:             if (scalar(@new_locks) > 0) {
 6564:                 $current_permissions{$file} = \@new_locks;
 6565:             } else {
 6566:                 push(@del_keys, $file);
 6567:                 &del('file_permissions',\@del_keys, $domain, $user);
 6568:                 delete($current_permissions{$file});
 6569:             }
 6570:         }
 6571:     }
 6572:     &put('file_permissions',\%current_permissions,$domain,$user);
 6573:     return;
 6574: }
 6575: 
 6576: # ------------------------------------------------------------ Directory lister
 6577: 
 6578: sub dirlist {
 6579:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6580:     $uri=~s/^\///;
 6581:     $uri=~s/\/$//;
 6582:     my ($udom, $uname);
 6583:     if ($getuserdir) {
 6584:         $udom = $userdomain;
 6585:         $uname = $username;
 6586:     } else {
 6587:         (undef,$udom,$uname)=split(/\//,$uri);
 6588:         if(defined($userdomain)) {
 6589:             $udom = $userdomain;
 6590:         }
 6591:         if(defined($username)) {
 6592:             $uname = $username;
 6593:         }
 6594:     }
 6595:     my ($dirRoot,$listing,@listing_results);
 6596: 
 6597:     $dirRoot = $perlvar{'lonDocRoot'};
 6598:     if (defined($getpropath)) {
 6599:         $dirRoot = &propath($udom,$uname);
 6600:         $dirRoot =~ s/\/$//;
 6601:     } elsif (defined($getuserdir)) {
 6602:         my $subdir=$uname.'__';
 6603:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6604:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6605:                    ."/$udom/$subdir/$uname";
 6606:     } elsif (defined($alternateRoot)) {
 6607:         $dirRoot = $alternateRoot;
 6608:     }
 6609: 
 6610:     if($udom) {
 6611:         if($uname) {
 6612:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6613:                               .$getuserdir.':'.&escape($dirRoot)
 6614:                               .':'.&escape($uname).':'.&escape($udom),
 6615:                               &homeserver($uname,$udom));
 6616:             if ($listing eq 'unknown_cmd') {
 6617:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6618:                                   &homeserver($uname,$udom));
 6619:             } else {
 6620:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6621:             }
 6622:             if ($listing eq 'unknown_cmd') {
 6623:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6624: 				  &homeserver($uname,$udom));
 6625:                 @listing_results = split(/:/,$listing);
 6626:             } else {
 6627:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6628:             }
 6629:             return @listing_results;
 6630:         } elsif(!$alternateRoot) {
 6631:             my %allusers;
 6632: 	    my %servers = &get_servers($udom,'library');
 6633:  	    foreach my $tryserver (keys(%servers)) {
 6634:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6635:                                   &escape($udom),$tryserver);
 6636:                 if ($listing eq 'unknown_cmd') {
 6637: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6638: 				      $udom, $tryserver);
 6639:                 } else {
 6640:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6641:                 }
 6642: 		if ($listing eq 'unknown_cmd') {
 6643: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6644: 				      $udom, $tryserver);
 6645: 		    @listing_results = split(/:/,$listing);
 6646: 		} else {
 6647: 		    @listing_results =
 6648: 			map { &unescape($_); } split(/:/,$listing);
 6649: 		}
 6650: 		if ($listing_results[0] ne 'no_such_dir' && 
 6651: 		    $listing_results[0] ne 'empty'       &&
 6652: 		    $listing_results[0] ne 'con_lost') {
 6653: 		    foreach my $line (@listing_results) {
 6654: 			my ($entry) = split(/&/,$line,2);
 6655: 			$allusers{$entry} = 1;
 6656: 		    }
 6657: 		}
 6658:             }
 6659:             my $alluserstr='';
 6660:             foreach my $user (sort(keys(%allusers))) {
 6661:                 $alluserstr.=$user.'&user:';
 6662:             }
 6663:             $alluserstr=~s/:$//;
 6664:             return split(/:/,$alluserstr);
 6665:         } else {
 6666:             return ('missing user name');
 6667:         }
 6668:     } elsif(!defined($getpropath)) {
 6669:         my @all_domains = sort(&all_domains());
 6670:         foreach my $domain (@all_domains) {
 6671:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6672:         }
 6673:         return @all_domains;
 6674:     } else {
 6675:         return ('missing domain');
 6676:     }
 6677: }
 6678: 
 6679: # --------------------------------------------- GetFileTimestamp
 6680: # This function utilizes dirlist and returns the date stamp for
 6681: # when it was last modified.  It will also return an error of -1
 6682: # if an error occurs
 6683: 
 6684: sub GetFileTimestamp {
 6685:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6686:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6687:     $studentName   = &LONCAPA::clean_username($studentName);
 6688:     my ($fileStat) = 
 6689:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6690:                                  undef,$getuserdir);
 6691:     my @stats = split('&', $fileStat);
 6692:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6693:         # @stats contains first the filename, then the stat output
 6694:         return $stats[10]; # so this is 10 instead of 9.
 6695:     } else {
 6696:         return -1;
 6697:     }
 6698: }
 6699: 
 6700: sub stat_file {
 6701:     my ($uri) = @_;
 6702:     $uri = &clutter_with_no_wrapper($uri);
 6703: 
 6704:     my ($udom,$uname,$file);
 6705:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6706: 	($udom,$uname,$file) =
 6707: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6708: 	$file = 'userfiles/'.$file;
 6709:     }
 6710:     if ($uri =~ m-^/res/-) {
 6711: 	($udom,$uname) = 
 6712: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6713: 	$file = $uri;
 6714:     }
 6715: 
 6716:     if (!$udom || !$uname || !$file) {
 6717: 	# unable to handle the uri
 6718: 	return ();
 6719:     }
 6720:     my $getpropath;
 6721:     if ($file =~ /^userfiles\//) {
 6722:         $getpropath = 1;
 6723:     }
 6724:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6725:     my @stats = split('&', $result);
 6726:     
 6727:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6728: 	shift(@stats); #filename is first
 6729: 	return @stats;
 6730:     }
 6731:     return ();
 6732: }
 6733: 
 6734: # -------------------------------------------------------- Value of a Condition
 6735: 
 6736: # gets the value of a specific preevaluated condition
 6737: #    stored in the string  $env{user.state.<cid>}
 6738: # or looks up a condition reference in the bighash and if if hasn't
 6739: # already been evaluated recurses into docondval to get the value of
 6740: # the condition, then memoizing it to 
 6741: #   $env{user.state.<cid>.<condition>}
 6742: sub directcondval {
 6743:     my $number=shift;
 6744:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6745: 	&Apache::lonuserstate::evalstate();
 6746:     }
 6747:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6748: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6749:     } elsif ($number =~ /^_/) {
 6750: 	my $sub_condition;
 6751: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6752: 		&GDBM_READER(),0640)) {
 6753: 	    $sub_condition=$bighash{'conditions'.$number};
 6754: 	    untie(%bighash);
 6755: 	}
 6756: 	my $value = &docondval($sub_condition);
 6757: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6758: 	return $value;
 6759:     }
 6760:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6761:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6762:     } else {
 6763:        return 2;
 6764:     }
 6765: }
 6766: 
 6767: # get the collection of conditions for this resource
 6768: sub condval {
 6769:     my $condidx=shift;
 6770:     my $allpathcond='';
 6771:     foreach my $cond (split(/\|/,$condidx)) {
 6772: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6773: 	    $allpathcond.=
 6774: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6775: 	}
 6776:     }
 6777:     $allpathcond=~s/\|$//;
 6778:     return &docondval($allpathcond);
 6779: }
 6780: 
 6781: #evaluates an expression of conditions
 6782: sub docondval {
 6783:     my ($allpathcond) = @_;
 6784:     my $result=0;
 6785:     if ($env{'request.course.id'}
 6786: 	&& defined($allpathcond)) {
 6787: 	my $operand='|';
 6788: 	my @stack;
 6789: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6790: 	    if ($chunk eq '(') {
 6791: 		push @stack,($operand,$result);
 6792: 	    } elsif ($chunk eq ')') {
 6793: 		my $before=pop @stack;
 6794: 		if (pop @stack eq '&') {
 6795: 		    $result=$result>$before?$before:$result;
 6796: 		} else {
 6797: 		    $result=$result>$before?$result:$before;
 6798: 		}
 6799: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6800: 		$operand=$chunk;
 6801: 	    } else {
 6802: 		my $new=directcondval($chunk);
 6803: 		if ($operand eq '&') {
 6804: 		    $result=$result>$new?$new:$result;
 6805: 		} else {
 6806: 		    $result=$result>$new?$result:$new;
 6807: 		}
 6808: 	    }
 6809: 	}
 6810:     }
 6811:     return $result;
 6812: }
 6813: 
 6814: # ---------------------------------------------------- Devalidate courseresdata
 6815: 
 6816: sub devalidatecourseresdata {
 6817:     my ($coursenum,$coursedomain)=@_;
 6818:     my $hashid=$coursenum.':'.$coursedomain;
 6819:     &devalidate_cache_new('courseres',$hashid);
 6820: }
 6821: 
 6822: 
 6823: # --------------------------------------------------- Course Resourcedata Query
 6824: #
 6825: #  Parameters:
 6826: #      $coursenum    - Number of the course.
 6827: #      $coursedomain - Domain at which the course was created.
 6828: #  Returns:
 6829: #     A hash of the course parameters along (I think) with timestamps
 6830: #     and version info.
 6831: 
 6832: sub get_courseresdata {
 6833:     my ($coursenum,$coursedomain)=@_;
 6834:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6835:     my $hashid=$coursenum.':'.$coursedomain;
 6836:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6837:     my %dumpreply;
 6838:     unless (defined($cached)) {
 6839: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6840: 	$result=\%dumpreply;
 6841: 	my ($tmp) = keys(%dumpreply);
 6842: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6843: 	    &do_cache_new('courseres',$hashid,$result,600);
 6844: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6845: 	    return $tmp;
 6846: 	} elsif ($tmp =~ /^(error)/) {
 6847: 	    $result=undef;
 6848: 	    &do_cache_new('courseres',$hashid,$result,600);
 6849: 	}
 6850:     }
 6851:     return $result;
 6852: }
 6853: 
 6854: sub devalidateuserresdata {
 6855:     my ($uname,$udom)=@_;
 6856:     my $hashid="$udom:$uname";
 6857:     &devalidate_cache_new('userres',$hashid);
 6858: }
 6859: 
 6860: sub get_userresdata {
 6861:     my ($uname,$udom)=@_;
 6862:     #most student don\'t have any data set, check if there is some data
 6863:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6864: 
 6865:     my $hashid="$udom:$uname";
 6866:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6867:     if (!defined($cached)) {
 6868: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6869: 	$result=\%resourcedata;
 6870: 	&do_cache_new('userres',$hashid,$result,600);
 6871:     }
 6872:     my ($tmp)=keys(%$result);
 6873:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6874: 	return $result;
 6875:     }
 6876:     #error 2 occurs when the .db doesn't exist
 6877:     if ($tmp!~/error: 2 /) {
 6878: 	&logthis("<font color=\"blue\">WARNING:".
 6879: 		 " Trying to get resource data for ".
 6880: 		 $uname." at ".$udom.": ".
 6881: 		 $tmp."</font>");
 6882:     } elsif ($tmp=~/error: 2 /) {
 6883: 	#&EXT_cache_set($udom,$uname);
 6884: 	&do_cache_new('userres',$hashid,undef,600);
 6885: 	undef($tmp); # not really an error so don't send it back
 6886:     }
 6887:     return $tmp;
 6888: }
 6889: #----------------------------------------------- resdata - return resource data
 6890: #  Purpose:
 6891: #    Return resource data for either users or for a course.
 6892: #  Parameters:
 6893: #     $name      - Course/user name.
 6894: #     $domain    - Name of the domain the user/course is registered on.
 6895: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6896: #     @which     - Array of names of resources desired.
 6897: #  Returns:
 6898: #     The value of the first reasource in @which that is found in the
 6899: #     resource hash.
 6900: #  Exceptional Conditions:
 6901: #     If the $type passed in is not valid (not the string 'course' or 
 6902: #     'user', an undefined  reference is returned.
 6903: #     If none of the resources are found, an undef is returned
 6904: sub resdata {
 6905:     my ($name,$domain,$type,@which)=@_;
 6906:     my $result;
 6907:     if ($type eq 'course') {
 6908: 	$result=&get_courseresdata($name,$domain);
 6909:     } elsif ($type eq 'user') {
 6910: 	$result=&get_userresdata($name,$domain);
 6911:     }
 6912:     if (!ref($result)) { return $result; }    
 6913:     foreach my $item (@which) {
 6914: 	if (defined($result->{$item->[0]})) {
 6915: 	    return [$result->{$item->[0]},$item->[1]];
 6916: 	}
 6917:     }
 6918:     return undef;
 6919: }
 6920: 
 6921: #
 6922: # EXT resource caching routines
 6923: #
 6924: 
 6925: sub clear_EXT_cache_status {
 6926:     &delenv('cache.EXT.');
 6927: }
 6928: 
 6929: sub EXT_cache_status {
 6930:     my ($target_domain,$target_user) = @_;
 6931:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6932:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6933:         # We know already the user has no data
 6934:         return 1;
 6935:     } else {
 6936:         return 0;
 6937:     }
 6938: }
 6939: 
 6940: sub EXT_cache_set {
 6941:     my ($target_domain,$target_user) = @_;
 6942:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6943:     #&appenv({$cachename => time});
 6944: }
 6945: 
 6946: # --------------------------------------------------------- Value of a Variable
 6947: sub EXT {
 6948: 
 6949:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6950:     unless ($varname) { return ''; }
 6951:     #get real user name/domain, courseid and symb
 6952:     my $courseid;
 6953:     my $publicuser;
 6954:     if ($symbparm) {
 6955: 	$symbparm=&get_symb_from_alias($symbparm);
 6956:     }
 6957:     if (!($uname && $udom)) {
 6958:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6959:       if (!$symbparm) {	$symbparm=$cursymb; }
 6960:     } else {
 6961: 	$courseid=$env{'request.course.id'};
 6962:     }
 6963:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6964:     my $rest;
 6965:     if (defined($therest[0])) {
 6966:        $rest=join('.',@therest);
 6967:     } else {
 6968:        $rest='';
 6969:     }
 6970: 
 6971:     my $qualifierrest=$qualifier;
 6972:     if ($rest) { $qualifierrest.='.'.$rest; }
 6973:     my $spacequalifierrest=$space;
 6974:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6975:     if ($realm eq 'user') {
 6976: # --------------------------------------------------------------- user.resource
 6977: 	if ($space eq 'resource') {
 6978: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6979: 		  || defined($Apache::lonhomework::parsing_a_task))
 6980: 		 &&
 6981: 		 ($symbparm eq &symbread()) ) {	
 6982: 		# if we are in the middle of processing the resource the
 6983: 		# get the value we are planning on committing
 6984:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6985:                     return $Apache::lonhomework::results{$qualifierrest};
 6986:                 } else {
 6987:                     return $Apache::lonhomework::history{$qualifierrest};
 6988:                 }
 6989: 	    } else {
 6990: 		my %restored;
 6991: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6992: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6993: 		} else {
 6994: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6995: 		}
 6996: 		return $restored{$qualifierrest};
 6997: 	    }
 6998: # ----------------------------------------------------------------- user.access
 6999:         } elsif ($space eq 'access') {
 7000: 	    # FIXME - not supporting calls for a specific user
 7001:             return &allowed($qualifier,$rest);
 7002: # ------------------------------------------ user.preferences, user.environment
 7003:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7004: 	    if (($uname eq $env{'user.name'}) &&
 7005: 		($udom eq $env{'user.domain'})) {
 7006: 		return $env{join('.',('environment',$qualifierrest))};
 7007: 	    } else {
 7008: 		my %returnhash;
 7009: 		if (!$publicuser) {
 7010: 		    %returnhash=&userenvironment($udom,$uname,
 7011: 						 $qualifierrest);
 7012: 		}
 7013: 		return $returnhash{$qualifierrest};
 7014: 	    }
 7015: # ----------------------------------------------------------------- user.course
 7016:         } elsif ($space eq 'course') {
 7017: 	    # FIXME - not supporting calls for a specific user
 7018:             return $env{join('.',('request.course',$qualifier))};
 7019: # ------------------------------------------------------------------- user.role
 7020:         } elsif ($space eq 'role') {
 7021: 	    # FIXME - not supporting calls for a specific user
 7022:             my ($role,$where)=split(/\./,$env{'request.role'});
 7023:             if ($qualifier eq 'value') {
 7024: 		return $role;
 7025:             } elsif ($qualifier eq 'extent') {
 7026:                 return $where;
 7027:             }
 7028: # ----------------------------------------------------------------- user.domain
 7029:         } elsif ($space eq 'domain') {
 7030:             return $udom;
 7031: # ------------------------------------------------------------------- user.name
 7032:         } elsif ($space eq 'name') {
 7033:             return $uname;
 7034: # ---------------------------------------------------- Any other user namespace
 7035:         } else {
 7036: 	    my %reply;
 7037: 	    if (!$publicuser) {
 7038: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7039: 	    }
 7040: 	    return $reply{$qualifierrest};
 7041:         }
 7042:     } elsif ($realm eq 'query') {
 7043: # ---------------------------------------------- pull stuff out of query string
 7044:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7045: 						[$spacequalifierrest]);
 7046: 	return $env{'form.'.$spacequalifierrest}; 
 7047:    } elsif ($realm eq 'request') {
 7048: # ------------------------------------------------------------- request.browser
 7049:         if ($space eq 'browser') {
 7050: 	    if ($qualifier eq 'textremote') {
 7051: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7052: 		    return 1;
 7053: 		} else {
 7054: 		    return 0;
 7055: 		}
 7056: 	    } else {
 7057: 		return $env{'browser.'.$qualifier};
 7058: 	    }
 7059: # ------------------------------------------------------------ request.filename
 7060:         } else {
 7061:             return $env{'request.'.$spacequalifierrest};
 7062:         }
 7063:     } elsif ($realm eq 'course') {
 7064: # ---------------------------------------------------------- course.description
 7065:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7066:     } elsif ($realm eq 'resource') {
 7067: 
 7068: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7069: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7070: 	}
 7071: 
 7072: 	if ($space eq 'title') {
 7073: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7074: 	    return &gettitle($symbparm);
 7075: 	}
 7076: 	
 7077: 	if ($space eq 'map') {
 7078: 	    my ($map) = &decode_symb($symbparm);
 7079: 	    return &symbread($map);
 7080: 	}
 7081: 	if ($space eq 'filename') {
 7082: 	    if ($symbparm) {
 7083: 		return &clutter((&decode_symb($symbparm))[2]);
 7084: 	    }
 7085: 	    return &hreflocation('',$env{'request.filename'});
 7086: 	}
 7087: 
 7088: 	my ($section, $group, @groups);
 7089: 	my ($courselevelm,$courselevel);
 7090: 	if ($symbparm && defined($courseid) && 
 7091: 	    $courseid eq $env{'request.course.id'}) {
 7092: 
 7093: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7094: 
 7095: # ----------------------------------------------------- Cascading lookup scheme
 7096: 	    my $symbp=$symbparm;
 7097: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7098: 
 7099: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7100: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7101: 
 7102: 	    if (($env{'user.name'} eq $uname) &&
 7103: 		($env{'user.domain'} eq $udom)) {
 7104: 		$section=$env{'request.course.sec'};
 7105:                 @groups = split(/:/,$env{'request.course.groups'});  
 7106:                 @groups=&sort_course_groups($courseid,@groups); 
 7107: 	    } else {
 7108: 		if (! defined($usection)) {
 7109: 		    $section=&getsection($udom,$uname,$courseid);
 7110: 		} else {
 7111: 		    $section = $usection;
 7112: 		}
 7113:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7114: 	    }
 7115: 
 7116: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7117: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7118: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7119: 
 7120: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7121: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7122: 	    $courselevelm=$courseid.'.'.$mapparm;
 7123: 
 7124: # ----------------------------------------------------------- first, check user
 7125: 
 7126: 	    my $userreply=&resdata($uname,$udom,'user',
 7127: 				       ([$courselevelr,'resource'],
 7128: 					[$courselevelm,'map'     ],
 7129: 					[$courselevel, 'course'  ]));
 7130: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7131: 
 7132: # ------------------------------------------------ second, check some of course
 7133:             my $coursereply;
 7134:             if (@groups > 0) {
 7135:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7136:                                        $mapparm,$spacequalifierrest);
 7137:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7138:             }
 7139: 
 7140: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7141: 				  $env{'course.'.$courseid.'.domain'},
 7142: 				  'course',
 7143: 				  ([$seclevelr,   'resource'],
 7144: 				   [$seclevelm,   'map'     ],
 7145: 				   [$seclevel,    'course'  ],
 7146: 				   [$courselevelr,'resource']));
 7147: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7148: 
 7149: # ------------------------------------------------------ third, check map parms
 7150: 	    my %parmhash=();
 7151: 	    my $thisparm='';
 7152: 	    if (tie(%parmhash,'GDBM_File',
 7153: 		    $env{'request.course.fn'}.'_parms.db',
 7154: 		    &GDBM_READER(),0640)) {
 7155: 		$thisparm=$parmhash{$symbparm};
 7156: 		untie(%parmhash);
 7157: 	    }
 7158: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7159: 	}
 7160: # ------------------------------------------ fourth, look in resource metadata
 7161: 
 7162: 	$spacequalifierrest=~s/\./\_/;
 7163: 	my $filename;
 7164: 	if (!$symbparm) { $symbparm=&symbread(); }
 7165: 	if ($symbparm) {
 7166: 	    $filename=(&decode_symb($symbparm))[2];
 7167: 	} else {
 7168: 	    $filename=$env{'request.filename'};
 7169: 	}
 7170: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7171: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7172: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7173: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7174: 
 7175: # ---------------------------------------------- fourth, look in rest of course
 7176: 	if ($symbparm && defined($courseid) && 
 7177: 	    $courseid eq $env{'request.course.id'}) {
 7178: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7179: 				     $env{'course.'.$courseid.'.domain'},
 7180: 				     'course',
 7181: 				     ([$courselevelm,'map'   ],
 7182: 				      [$courselevel, 'course']));
 7183: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7184: 	}
 7185: # ------------------------------------------------------------------ Cascade up
 7186: 	unless ($space eq '0') {
 7187: 	    my @parts=split(/_/,$space);
 7188: 	    my $id=pop(@parts);
 7189: 	    my $part=join('_',@parts);
 7190: 	    if ($part eq '') { $part='0'; }
 7191: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7192: 				 $symbparm,$udom,$uname,$section,1);
 7193: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7194: 	}
 7195: 	if ($recurse) { return undef; }
 7196: 	my $pack_def=&packages_tab_default($filename,$varname);
 7197: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7198: # ---------------------------------------------------- Any other user namespace
 7199:     } elsif ($realm eq 'environment') {
 7200: # ----------------------------------------------------------------- environment
 7201: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7202: 	    return $env{'environment.'.$spacequalifierrest};
 7203: 	} else {
 7204: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7205: 		return '';
 7206: 	    }
 7207: 	    my %returnhash=&userenvironment($udom,$uname,
 7208: 					    $spacequalifierrest);
 7209: 	    return $returnhash{$spacequalifierrest};
 7210: 	}
 7211:     } elsif ($realm eq 'system') {
 7212: # ----------------------------------------------------------------- system.time
 7213: 	if ($space eq 'time') {
 7214: 	    return time;
 7215:         }
 7216:     } elsif ($realm eq 'server') {
 7217: # ----------------------------------------------------------------- system.time
 7218: 	if ($space eq 'name') {
 7219: 	    return $ENV{'SERVER_NAME'};
 7220:         }
 7221:     }
 7222:     return '';
 7223: }
 7224: 
 7225: sub get_reply {
 7226:     my ($reply_value) = @_;
 7227:     if (ref($reply_value) eq 'ARRAY') {
 7228:         if (wantarray) {
 7229: 	    return @$reply_value;
 7230:         }
 7231:         return $reply_value->[0];
 7232:     } else {
 7233:         return $reply_value;
 7234:     }
 7235: }
 7236: 
 7237: sub check_group_parms {
 7238:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7239:     my @groupitems = ();
 7240:     my $resultitem;
 7241:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7242:     foreach my $group (@{$groups}) {
 7243:         foreach my $level (@levels) {
 7244:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7245:              push(@groupitems,[$item,$level->[1]]);
 7246:         }
 7247:     }
 7248:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7249:                             $env{'course.'.$courseid.'.domain'},
 7250:                                      'course',@groupitems);
 7251:     return $coursereply;
 7252: }
 7253: 
 7254: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7255:     my ($courseid,@groups) = @_;
 7256:     @groups = sort(@groups);
 7257:     return @groups;
 7258: }
 7259: 
 7260: sub packages_tab_default {
 7261:     my ($uri,$varname)=@_;
 7262:     my (undef,$part,$name)=split(/\./,$varname);
 7263: 
 7264:     my (@extension,@specifics,$do_default);
 7265:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7266: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7267: 	if ($pack_type eq 'default') {
 7268: 	    $do_default=1;
 7269: 	} elsif ($pack_type eq 'extension') {
 7270: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7271: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7272: 	    # only look at packages defaults for packages that this id is
 7273: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7274: 	}
 7275:     }
 7276:     # first look for a package that matches the requested part id
 7277:     foreach my $package (@specifics) {
 7278: 	my (undef,$pack_type,$pack_part)=@{$package};
 7279: 	next if ($pack_part ne $part);
 7280: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7281: 	    return $packagetab{"$pack_type&$name&default"};
 7282: 	}
 7283:     }
 7284:     # look for any possible matching non extension_ package
 7285:     foreach my $package (@specifics) {
 7286: 	my (undef,$pack_type,$pack_part)=@{$package};
 7287: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7288: 	    return $packagetab{"$pack_type&$name&default"};
 7289: 	}
 7290: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7291: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7292: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7293: 	}
 7294:     }
 7295:     # look for any posible extension_ match
 7296:     foreach my $package (@extension) {
 7297: 	my ($package,$pack_type)=@{$package};
 7298: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7299: 	    return $packagetab{"$pack_type&$name&default"};
 7300: 	}
 7301: 	if (defined($packagetab{$package."&$name&default"})) {
 7302: 	    return $packagetab{$package."&$name&default"};
 7303: 	}
 7304:     }
 7305:     # look for a global default setting
 7306:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7307: 	return $packagetab{"default&$name&default"};
 7308:     }
 7309:     return undef;
 7310: }
 7311: 
 7312: sub add_prefix_and_part {
 7313:     my ($prefix,$part)=@_;
 7314:     my $keyroot;
 7315:     if (defined($prefix) && $prefix !~ /^__/) {
 7316: 	# prefix that has a part already
 7317: 	$keyroot=$prefix;
 7318:     } elsif (defined($prefix)) {
 7319: 	# prefix that is missing a part
 7320: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7321:     } else {
 7322: 	# no prefix at all
 7323: 	if (defined($part)) { $keyroot='_'.$part; }
 7324:     }
 7325:     return $keyroot;
 7326: }
 7327: 
 7328: # ---------------------------------------------------------------- Get metadata
 7329: 
 7330: my %metaentry;
 7331: sub metadata {
 7332:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7333:     $uri=&declutter($uri);
 7334:     # if it is a non metadata possible uri return quickly
 7335:     if (($uri eq '') || 
 7336: 	(($uri =~ m|^/*adm/|) && 
 7337: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7338:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7339: 	return undef;
 7340:     }
 7341:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7342: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7343: 	return undef;
 7344:     }
 7345:     my $filename=$uri;
 7346:     $uri=~s/\.meta$//;
 7347: #
 7348: # Is the metadata already cached?
 7349: # Look at timestamp of caching
 7350: # Everything is cached by the main uri, libraries are never directly cached
 7351: #
 7352:     if (!defined($liburi)) {
 7353: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7354: 	if (defined($cached)) { return $result->{':'.$what}; }
 7355:     }
 7356:     {
 7357: #
 7358: # Is this a recursive call for a library?
 7359: #
 7360: #	if (! exists($metacache{$uri})) {
 7361: #	    $metacache{$uri}={};
 7362: #	}
 7363: 	my $cachetime = 60*60;
 7364:         if ($liburi) {
 7365: 	    $liburi=&declutter($liburi);
 7366:             $filename=$liburi;
 7367:         } else {
 7368: 	    &devalidate_cache_new('meta',$uri);
 7369: 	    undef(%metaentry);
 7370: 	}
 7371:         my %metathesekeys=();
 7372:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7373: 	my $metastring;
 7374: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7375: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7376: 	    $metastring = 
 7377: 		&Apache::lonnet::ssi_body($which,
 7378: 					  ('grade_target' => 'meta'));
 7379: 	    $cachetime = 1; # only want this cached in the child not long term
 7380: 	} elsif ($uri !~ m -^(editupload)/-) {
 7381: 	    my $file=&filelocation('',&clutter($filename));
 7382: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7383: 	    $metastring=&getfile($file);
 7384: 	}
 7385:         my $parser=HTML::LCParser->new(\$metastring);
 7386:         my $token;
 7387:         undef %metathesekeys;
 7388:         while ($token=$parser->get_token) {
 7389: 	    if ($token->[0] eq 'S') {
 7390: 		if (defined($token->[2]->{'package'})) {
 7391: #
 7392: # This is a package - get package info
 7393: #
 7394: 		    my $package=$token->[2]->{'package'};
 7395: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7396: 		    if (defined($token->[2]->{'id'})) { 
 7397: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7398: 		    }
 7399: 		    if ($metaentry{':packages'}) {
 7400: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7401: 		    } else {
 7402: 			$metaentry{':packages'}=$package.$keyroot;
 7403: 		    }
 7404: 		    foreach my $pack_entry (keys(%packagetab)) {
 7405: 			my $part=$keyroot;
 7406: 			$part=~s/^\_//;
 7407: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7408: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7409: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7410: 			    # ignore package.tab specified default values
 7411:                             # here &package_tab_default() will fetch those
 7412: 			    if ($subp eq 'default') { next; }
 7413: 			    my $value=$packagetab{$pack_entry};
 7414: 			    my $unikey;
 7415: 			    if ($pack =~ /_0$/) {
 7416: 				$unikey='parameter_0_'.$name;
 7417: 				$part=0;
 7418: 			    } else {
 7419: 				$unikey='parameter'.$keyroot.'_'.$name;
 7420: 			    }
 7421: 			    if ($subp eq 'display') {
 7422: 				$value.=' [Part: '.$part.']';
 7423: 			    }
 7424: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7425: 			    $metathesekeys{$unikey}=1;
 7426: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7427: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7428: 			    }
 7429: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7430: 				$metaentry{':'.$unikey}=
 7431: 				    $metaentry{':'.$unikey.'.default'};
 7432: 			    }
 7433: 			}
 7434: 		    }
 7435: 		} else {
 7436: #
 7437: # This is not a package - some other kind of start tag
 7438: #
 7439: 		    my $entry=$token->[1];
 7440: 		    my $unikey;
 7441: 		    if ($entry eq 'import') {
 7442: 			$unikey='';
 7443: 		    } else {
 7444: 			$unikey=$entry;
 7445: 		    }
 7446: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7447: 
 7448: 		    if (defined($token->[2]->{'id'})) { 
 7449: 			$unikey.='_'.$token->[2]->{'id'}; 
 7450: 		    }
 7451: 
 7452: 		    if ($entry eq 'import') {
 7453: #
 7454: # Importing a library here
 7455: #
 7456: 			if ($depthcount<20) {
 7457: 			    my $location=$parser->get_text('/import');
 7458: 			    my $dir=$filename;
 7459: 			    $dir=~s|[^/]*$||;
 7460: 			    $location=&filelocation($dir,$location);
 7461: 			    my $metadata = 
 7462: 				&metadata($uri,'keys', $location,$unikey,
 7463: 					  $depthcount+1);
 7464: 			    foreach my $meta (split(',',$metadata)) {
 7465: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7466: 				$metathesekeys{$meta}=1;
 7467: 			    }
 7468: 			}
 7469: 		    } else { 
 7470: 			
 7471: 			if (defined($token->[2]->{'name'})) { 
 7472: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7473: 			}
 7474: 			$metathesekeys{$unikey}=1;
 7475: 			foreach my $param (@{$token->[3]}) {
 7476: 			    $metaentry{':'.$unikey.'.'.$param} =
 7477: 				$token->[2]->{$param};
 7478: 			}
 7479: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7480: 			my $default=$metaentry{':'.$unikey.'.default'};
 7481: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7482: 		 # only ws inside the tag, and not in default, so use default
 7483: 		 # as value
 7484: 			    $metaentry{':'.$unikey}=$default;
 7485: 			} elsif ( $internaltext =~ /\S/ ) {
 7486: 		  # something interesting inside the tag
 7487: 			    $metaentry{':'.$unikey}=$internaltext;
 7488: 			} else {
 7489: 		  # no interesting values, don't set a default
 7490: 			}
 7491: # end of not-a-package not-a-library import
 7492: 		    }
 7493: # end of not-a-package start tag
 7494: 		}
 7495: # the next is the end of "start tag"
 7496: 	    }
 7497: 	}
 7498: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7499: 	$extension = lc($extension);
 7500: 	if ($extension eq 'htm') { $extension='html'; }
 7501: 
 7502: 	foreach my $key (keys(%packagetab)) {
 7503: 	    #no specific packages #how's our extension
 7504: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7505: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7506: 					 \%metathesekeys);
 7507: 	}
 7508: 
 7509: 	if (!exists($metaentry{':packages'})
 7510: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7511: 	    foreach my $key (keys(%packagetab)) {
 7512: 		#no specific packages well let's get default then
 7513: 		if ($key!~/^default&/) { next; }
 7514: 		&metadata_create_package_def($uri,$key,'default',
 7515: 					     \%metathesekeys);
 7516: 	    }
 7517: 	}
 7518: # are there custom rights to evaluate
 7519: 	if ($metaentry{':copyright'} eq 'custom') {
 7520: 
 7521:     #
 7522:     # Importing a rights file here
 7523:     #
 7524: 	    unless ($depthcount) {
 7525: 		my $location=$metaentry{':customdistributionfile'};
 7526: 		my $dir=$filename;
 7527: 		$dir=~s|[^/]*$||;
 7528: 		$location=&filelocation($dir,$location);
 7529: 		my $rights_metadata =
 7530: 		    &metadata($uri,'keys',$location,'_rights',
 7531: 			      $depthcount+1);
 7532: 		foreach my $rights (split(',',$rights_metadata)) {
 7533: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7534: 		    $metathesekeys{$rights}=1;
 7535: 		}
 7536: 	    }
 7537: 	}
 7538: 	# uniqifiy package listing
 7539: 	my %seen;
 7540: 	my @uniq_packages =
 7541: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7542: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7543: 
 7544: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7545: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7546: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7547: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7548: # this is the end of "was not already recently cached
 7549:     }
 7550:     return $metaentry{':'.$what};
 7551: }
 7552: 
 7553: sub metadata_create_package_def {
 7554:     my ($uri,$key,$package,$metathesekeys)=@_;
 7555:     my ($pack,$name,$subp)=split(/\&/,$key);
 7556:     if ($subp eq 'default') { next; }
 7557:     
 7558:     if (defined($metaentry{':packages'})) {
 7559: 	$metaentry{':packages'}.=','.$package;
 7560:     } else {
 7561: 	$metaentry{':packages'}=$package;
 7562:     }
 7563:     my $value=$packagetab{$key};
 7564:     my $unikey;
 7565:     $unikey='parameter_0_'.$name;
 7566:     $metaentry{':'.$unikey.'.part'}=0;
 7567:     $$metathesekeys{$unikey}=1;
 7568:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7569: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7570:     }
 7571:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7572: 	$metaentry{':'.$unikey}=
 7573: 	    $metaentry{':'.$unikey.'.default'};
 7574:     }
 7575: }
 7576: 
 7577: sub metadata_generate_part0 {
 7578:     my ($metadata,$metacache,$uri) = @_;
 7579:     my %allnames;
 7580:     foreach my $metakey (keys(%$metadata)) {
 7581: 	if ($metakey=~/^parameter\_(.*)/) {
 7582: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7583: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7584: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7585: 	    $allnames{$name}=$part;
 7586: 	  }
 7587: 	}
 7588:     }
 7589:     foreach my $name (keys(%allnames)) {
 7590:       $$metadata{"parameter_0_$name"}=1;
 7591:       my $key=":parameter_0_$name";
 7592:       $$metacache{"$key.part"}='0';
 7593:       $$metacache{"$key.name"}=$name;
 7594:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7595: 					   $allnames{$name}.'_'.$name.
 7596: 					   '.type'};
 7597:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7598: 			     '.display'};
 7599:       my $expr='[Part: '.$allnames{$name}.']';
 7600:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7601:       $$metacache{"$key.display"}=$olddis;
 7602:     }
 7603: }
 7604: 
 7605: # ------------------------------------------------------ Devalidate title cache
 7606: 
 7607: sub devalidate_title_cache {
 7608:     my ($url)=@_;
 7609:     if (!$env{'request.course.id'}) { return; }
 7610:     my $symb=&symbread($url);
 7611:     if (!$symb) { return; }
 7612:     my $key=$env{'request.course.id'}."\0".$symb;
 7613:     &devalidate_cache_new('title',$key);
 7614: }
 7615: 
 7616: # ------------------------------------------------- Get the title of a resource
 7617: 
 7618: sub gettitle {
 7619:     my $urlsymb=shift;
 7620:     my $symb=&symbread($urlsymb);
 7621:     if ($symb) {
 7622: 	my $key=$env{'request.course.id'}."\0".$symb;
 7623: 	my ($result,$cached)=&is_cached_new('title',$key);
 7624: 	if (defined($cached)) { 
 7625: 	    return $result;
 7626: 	}
 7627: 	my ($map,$resid,$url)=&decode_symb($symb);
 7628: 	my $title='';
 7629: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7630: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7631: 	} else {
 7632: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7633: 		    &GDBM_READER(),0640)) {
 7634: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7635: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7636: 		untie(%bighash);
 7637: 	    }
 7638: 	}
 7639: 	$title=~s/\&colon\;/\:/gs;
 7640: 	if ($title) {
 7641: 	    return &do_cache_new('title',$key,$title,600);
 7642: 	}
 7643: 	$urlsymb=$url;
 7644:     }
 7645:     my $title=&metadata($urlsymb,'title');
 7646:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7647:     return $title;
 7648: }
 7649: 
 7650: sub get_slot {
 7651:     my ($which,$cnum,$cdom)=@_;
 7652:     if (!$cnum || !$cdom) {
 7653: 	(undef,my $courseid)=&whichuser();
 7654: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7655: 	$cnum=$env{'course.'.$courseid.'.num'};
 7656:     }
 7657:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7658:     my %slotinfo;
 7659:     if (exists($remembered{$key})) {
 7660: 	$slotinfo{$which} = $remembered{$key};
 7661:     } else {
 7662: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7663: 	&Apache::lonhomework::showhash(%slotinfo);
 7664: 	my ($tmp)=keys(%slotinfo);
 7665: 	if ($tmp=~/^error:/) { return (); }
 7666: 	$remembered{$key} = $slotinfo{$which};
 7667:     }
 7668:     if (ref($slotinfo{$which}) eq 'HASH') {
 7669: 	return %{$slotinfo{$which}};
 7670:     }
 7671:     return $slotinfo{$which};
 7672: }
 7673: # ------------------------------------------------- Update symbolic store links
 7674: 
 7675: sub symblist {
 7676:     my ($mapname,%newhash)=@_;
 7677:     $mapname=&deversion(&declutter($mapname));
 7678:     my %hash;
 7679:     if (($env{'request.course.fn'}) && (%newhash)) {
 7680:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7681:                       &GDBM_WRCREAT(),0640)) {
 7682: 	    foreach my $url (keys %newhash) {
 7683: 		next if ($url eq 'last_known'
 7684: 			 && $env{'form.no_update_last_known'});
 7685: 		$hash{declutter($url)}=&encode_symb($mapname,
 7686: 						    $newhash{$url}->[1],
 7687: 						    $newhash{$url}->[0]);
 7688:             }
 7689:             if (untie(%hash)) {
 7690: 		return 'ok';
 7691:             }
 7692:         }
 7693:     }
 7694:     return 'error';
 7695: }
 7696: 
 7697: # --------------------------------------------------------------- Verify a symb
 7698: 
 7699: sub symbverify {
 7700:     my ($symb,$thisurl)=@_;
 7701:     my $thisfn=$thisurl;
 7702:     $thisfn=&declutter($thisfn);
 7703: # direct jump to resource in page or to a sequence - will construct own symbs
 7704:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7705: # check URL part
 7706:     my ($map,$resid,$url)=&decode_symb($symb);
 7707: 
 7708:     unless ($url eq $thisfn) { return 0; }
 7709: 
 7710:     $symb=&symbclean($symb);
 7711:     $thisurl=&deversion($thisurl);
 7712:     $thisfn=&deversion($thisfn);
 7713: 
 7714:     my %bighash;
 7715:     my $okay=0;
 7716: 
 7717:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7718:                             &GDBM_READER(),0640)) {
 7719:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7720:         unless ($ids) { 
 7721:            $ids=$bighash{'ids_/'.$thisurl};
 7722:         }
 7723:         if ($ids) {
 7724: # ------------------------------------------------------------------- Has ID(s)
 7725: 	    foreach my $id (split(/\,/,$ids)) {
 7726: 	       my ($mapid,$resid)=split(/\./,$id);
 7727:                if (
 7728:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7729:    eq $symb) { 
 7730: 		   if (($env{'request.role.adv'}) ||
 7731: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7732: 		       $okay=1; 
 7733: 		   }
 7734: 	       }
 7735: 	   }
 7736:         }
 7737: 	untie(%bighash);
 7738:     }
 7739:     return $okay;
 7740: }
 7741: 
 7742: # --------------------------------------------------------------- Clean-up symb
 7743: 
 7744: sub symbclean {
 7745:     my $symb=shift;
 7746:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7747: # remove version from map
 7748:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7749: 
 7750: # remove version from URL
 7751:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7752: 
 7753: # remove wrapper
 7754: 
 7755:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7756:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7757:     return $symb;
 7758: }
 7759: 
 7760: # ---------------------------------------------- Split symb to find map and url
 7761: 
 7762: sub encode_symb {
 7763:     my ($map,$resid,$url)=@_;
 7764:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7765: }
 7766: 
 7767: sub decode_symb {
 7768:     my $symb=shift;
 7769:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7770:     my ($map,$resid,$url)=split(/___/,$symb);
 7771:     return (&fixversion($map),$resid,&fixversion($url));
 7772: }
 7773: 
 7774: sub fixversion {
 7775:     my $fn=shift;
 7776:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7777:     my %bighash;
 7778:     my $uri=&clutter($fn);
 7779:     my $key=$env{'request.course.id'}.'_'.$uri;
 7780: # is this cached?
 7781:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7782:     if (defined($cached)) { return $result; }
 7783: # unfortunately not cached, or expired
 7784:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7785: 	    &GDBM_READER(),0640)) {
 7786:  	if ($bighash{'version_'.$uri}) {
 7787:  	    my $version=$bighash{'version_'.$uri};
 7788:  	    unless (($version eq 'mostrecent') || 
 7789: 		    ($version==&getversion($uri))) {
 7790:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7791:  	    }
 7792:  	}
 7793:  	untie %bighash;
 7794:     }
 7795:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7796: }
 7797: 
 7798: sub deversion {
 7799:     my $url=shift;
 7800:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7801:     return $url;
 7802: }
 7803: 
 7804: # ------------------------------------------------------ Return symb list entry
 7805: 
 7806: sub symbread {
 7807:     my ($thisfn,$donotrecurse)=@_;
 7808:     my $cache_str='request.symbread.cached.'.$thisfn;
 7809:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7810: # no filename provided? try from environment
 7811:     unless ($thisfn) {
 7812:         if ($env{'request.symb'}) {
 7813: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7814: 	}
 7815: 	$thisfn=$env{'request.filename'};
 7816:     }
 7817:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7818: # is that filename actually a symb? Verify, clean, and return
 7819:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7820: 	if (&symbverify($thisfn,$1)) {
 7821: 	    return $env{$cache_str}=&symbclean($thisfn);
 7822: 	}
 7823:     }
 7824:     $thisfn=declutter($thisfn);
 7825:     my %hash;
 7826:     my %bighash;
 7827:     my $syval='';
 7828:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7829:         my $targetfn = $thisfn;
 7830:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7831:             $targetfn = 'adm/wrapper/'.$thisfn;
 7832:         }
 7833: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7834: 	    $targetfn=$1;
 7835: 	}
 7836:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7837:                       &GDBM_READER(),0640)) {
 7838: 	    $syval=$hash{$targetfn};
 7839:             untie(%hash);
 7840:         }
 7841: # ---------------------------------------------------------- There was an entry
 7842:         if ($syval) {
 7843: 	    #unless ($syval=~/\_\d+$/) {
 7844: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7845: 		    #&appenv({'request.ambiguous' => $thisfn});
 7846: 		    #return $env{$cache_str}='';
 7847: 		#}    
 7848: 		#$syval.=$1;
 7849: 	    #}
 7850:         } else {
 7851: # ------------------------------------------------------- Was not in symb table
 7852:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7853:                             &GDBM_READER(),0640)) {
 7854: # ---------------------------------------------- Get ID(s) for current resource
 7855:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7856:               unless ($ids) { 
 7857:                  $ids=$bighash{'ids_/'.$thisfn};
 7858:               }
 7859:               unless ($ids) {
 7860: # alias?
 7861: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7862:               }
 7863:               if ($ids) {
 7864: # ------------------------------------------------------------------- Has ID(s)
 7865:                  my @possibilities=split(/\,/,$ids);
 7866:                  if ($#possibilities==0) {
 7867: # ----------------------------------------------- There is only one possibility
 7868: 		     my ($mapid,$resid)=split(/\./,$ids);
 7869: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7870: 						    $resid,$thisfn);
 7871:                  } elsif (!$donotrecurse) {
 7872: # ------------------------------------------ There is more than one possibility
 7873:                      my $realpossible=0;
 7874:                      foreach my $id (@possibilities) {
 7875: 			 my $file=$bighash{'src_'.$id};
 7876:                          if (&allowed('bre',$file)) {
 7877:          		    my ($mapid,$resid)=split(/\./,$id);
 7878:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7879: 				$realpossible++;
 7880:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7881: 						    $resid,$thisfn);
 7882:                             }
 7883: 			 }
 7884:                      }
 7885: 		     if ($realpossible!=1) { $syval=''; }
 7886:                  } else {
 7887:                      $syval='';
 7888:                  }
 7889: 	      }
 7890:               untie(%bighash)
 7891:            }
 7892:         }
 7893:         if ($syval) {
 7894: 	    return $env{$cache_str}=$syval;
 7895:         }
 7896:     }
 7897:     &appenv({'request.ambiguous' => $thisfn});
 7898:     return $env{$cache_str}='';
 7899: }
 7900: 
 7901: # ---------------------------------------------------------- Return random seed
 7902: 
 7903: sub numval {
 7904:     my $txt=shift;
 7905:     $txt=~tr/A-J/0-9/;
 7906:     $txt=~tr/a-j/0-9/;
 7907:     $txt=~tr/K-T/0-9/;
 7908:     $txt=~tr/k-t/0-9/;
 7909:     $txt=~tr/U-Z/0-5/;
 7910:     $txt=~tr/u-z/0-5/;
 7911:     $txt=~s/\D//g;
 7912:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7913:     return int($txt);
 7914: }
 7915: 
 7916: sub numval2 {
 7917:     my $txt=shift;
 7918:     $txt=~tr/A-J/0-9/;
 7919:     $txt=~tr/a-j/0-9/;
 7920:     $txt=~tr/K-T/0-9/;
 7921:     $txt=~tr/k-t/0-9/;
 7922:     $txt=~tr/U-Z/0-5/;
 7923:     $txt=~tr/u-z/0-5/;
 7924:     $txt=~s/\D//g;
 7925:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7926:     my $total;
 7927:     foreach my $val (@txts) { $total+=$val; }
 7928:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7929:     return int($total);
 7930: }
 7931: 
 7932: sub numval3 {
 7933:     use integer;
 7934:     my $txt=shift;
 7935:     $txt=~tr/A-J/0-9/;
 7936:     $txt=~tr/a-j/0-9/;
 7937:     $txt=~tr/K-T/0-9/;
 7938:     $txt=~tr/k-t/0-9/;
 7939:     $txt=~tr/U-Z/0-5/;
 7940:     $txt=~tr/u-z/0-5/;
 7941:     $txt=~s/\D//g;
 7942:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7943:     my $total;
 7944:     foreach my $val (@txts) { $total+=$val; }
 7945:     if ($_64bit) { $total=(($total<<32)>>32); }
 7946:     return $total;
 7947: }
 7948: 
 7949: sub digest {
 7950:     my ($data)=@_;
 7951:     my $digest=&Digest::MD5::md5($data);
 7952:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7953:     my ($e,$f);
 7954:     {
 7955:         use integer;
 7956:         $e=($a+$b);
 7957:         $f=($c+$d);
 7958:         if ($_64bit) {
 7959:             $e=(($e<<32)>>32);
 7960:             $f=(($f<<32)>>32);
 7961:         }
 7962:     }
 7963:     if (wantarray) {
 7964: 	return ($e,$f);
 7965:     } else {
 7966: 	my $g;
 7967: 	{
 7968: 	    use integer;
 7969: 	    $g=($e+$f);
 7970: 	    if ($_64bit) {
 7971: 		$g=(($g<<32)>>32);
 7972: 	    }
 7973: 	}
 7974: 	return $g;
 7975:     }
 7976: }
 7977: 
 7978: sub latest_rnd_algorithm_id {
 7979:     return '64bit5';
 7980: }
 7981: 
 7982: sub get_rand_alg {
 7983:     my ($courseid)=@_;
 7984:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7985:     if ($courseid) {
 7986: 	return $env{"course.$courseid.rndseed"};
 7987:     }
 7988:     return &latest_rnd_algorithm_id();
 7989: }
 7990: 
 7991: sub validCODE {
 7992:     my ($CODE)=@_;
 7993:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7994:     return 0;
 7995: }
 7996: 
 7997: sub getCODE {
 7998:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7999:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8000: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8001: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8002: 	return $Apache::lonhomework::history{'resource.CODE'};
 8003:     }
 8004:     return undef;
 8005: }
 8006: 
 8007: sub rndseed {
 8008:     my ($symb,$courseid,$domain,$username)=@_;
 8009:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8010:     if (!defined($symb)) {
 8011: 	unless ($symb=$wsymb) { return time; }
 8012:     }
 8013:     if (!$courseid) { $courseid=$wcourseid; }
 8014:     if (!$domain) { $domain=$wdomain; }
 8015:     if (!$username) { $username=$wusername }
 8016:     my $which=&get_rand_alg();
 8017: 
 8018:     if (defined(&getCODE())) {
 8019: 	if ($which eq '64bit5') {
 8020: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8021: 	} elsif ($which eq '64bit4') {
 8022: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8023: 	} else {
 8024: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8025: 	}
 8026:     } elsif ($which eq '64bit5') {
 8027: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8028:     } elsif ($which eq '64bit4') {
 8029: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8030:     } elsif ($which eq '64bit3') {
 8031: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8032:     } elsif ($which eq '64bit2') {
 8033: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8034:     } elsif ($which eq '64bit') {
 8035: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8036:     }
 8037:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8038: }
 8039: 
 8040: sub rndseed_32bit {
 8041:     my ($symb,$courseid,$domain,$username)=@_;
 8042:     {
 8043: 	use integer;
 8044: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8045: 	my $symbseed=numval($symb) << 22;
 8046: 	my $namechck=unpack("%32C*",$username) << 17;
 8047: 	my $nameseed=numval($username) << 12;
 8048: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8049: 	my $courseseed=unpack("%32C*",$courseid);
 8050: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8052: 	#&logthis("rndseed :$num:$symb");
 8053: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8054: 	return $num;
 8055:     }
 8056: }
 8057: 
 8058: sub rndseed_64bit {
 8059:     my ($symb,$courseid,$domain,$username)=@_;
 8060:     {
 8061: 	use integer;
 8062: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8063: 	my $symbseed=numval($symb) << 10;
 8064: 	my $namechck=unpack("%32S*",$username);
 8065: 	
 8066: 	my $nameseed=numval($username) << 21;
 8067: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8068: 	my $courseseed=unpack("%32S*",$courseid);
 8069: 	
 8070: 	my $num1=$symbchck+$symbseed+$namechck;
 8071: 	my $num2=$nameseed+$domainseed+$courseseed;
 8072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8073: 	#&logthis("rndseed :$num:$symb");
 8074: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8075: 	return "$num1,$num2";
 8076:     }
 8077: }
 8078: 
 8079: sub rndseed_64bit2 {
 8080:     my ($symb,$courseid,$domain,$username)=@_;
 8081:     {
 8082: 	use integer;
 8083: 	# strings need to be an even # of cahracters long, it it is odd the
 8084:         # last characters gets thrown away
 8085: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8086: 	my $symbseed=numval($symb) << 10;
 8087: 	my $namechck=unpack("%32S*",$username.' ');
 8088: 	
 8089: 	my $nameseed=numval($username) << 21;
 8090: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8091: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8092: 	
 8093: 	my $num1=$symbchck+$symbseed+$namechck;
 8094: 	my $num2=$nameseed+$domainseed+$courseseed;
 8095: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8096: 	#&logthis("rndseed :$num:$symb");
 8097: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8098: 	return "$num1,$num2";
 8099:     }
 8100: }
 8101: 
 8102: sub rndseed_64bit3 {
 8103:     my ($symb,$courseid,$domain,$username)=@_;
 8104:     {
 8105: 	use integer;
 8106: 	# strings need to be an even # of cahracters long, it it is odd the
 8107:         # last characters gets thrown away
 8108: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8109: 	my $symbseed=numval2($symb) << 10;
 8110: 	my $namechck=unpack("%32S*",$username.' ');
 8111: 	
 8112: 	my $nameseed=numval2($username) << 21;
 8113: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8114: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8115: 	
 8116: 	my $num1=$symbchck+$symbseed+$namechck;
 8117: 	my $num2=$nameseed+$domainseed+$courseseed;
 8118: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8119: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8120: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8121: 	
 8122: 	return "$num1:$num2";
 8123:     }
 8124: }
 8125: 
 8126: sub rndseed_64bit4 {
 8127:     my ($symb,$courseid,$domain,$username)=@_;
 8128:     {
 8129: 	use integer;
 8130: 	# strings need to be an even # of cahracters long, it it is odd the
 8131:         # last characters gets thrown away
 8132: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8133: 	my $symbseed=numval3($symb) << 10;
 8134: 	my $namechck=unpack("%32S*",$username.' ');
 8135: 	
 8136: 	my $nameseed=numval3($username) << 21;
 8137: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8138: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8139: 	
 8140: 	my $num1=$symbchck+$symbseed+$namechck;
 8141: 	my $num2=$nameseed+$domainseed+$courseseed;
 8142: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8143: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8144: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8145: 	
 8146: 	return "$num1:$num2";
 8147:     }
 8148: }
 8149: 
 8150: sub rndseed_64bit5 {
 8151:     my ($symb,$courseid,$domain,$username)=@_;
 8152:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8153:     return "$num1:$num2";
 8154: }
 8155: 
 8156: sub rndseed_CODE_64bit {
 8157:     my ($symb,$courseid,$domain,$username)=@_;
 8158:     {
 8159: 	use integer;
 8160: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8161: 	my $symbseed=numval2($symb);
 8162: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8163: 	my $CODEseed=numval(&getCODE());
 8164: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8165: 	my $num1=$symbseed+$CODEchck;
 8166: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8167: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8168: 	#&logthis("rndseed :$num1:$num2:$symb");
 8169: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8170: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8171: 	return "$num1:$num2";
 8172:     }
 8173: }
 8174: 
 8175: sub rndseed_CODE_64bit4 {
 8176:     my ($symb,$courseid,$domain,$username)=@_;
 8177:     {
 8178: 	use integer;
 8179: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8180: 	my $symbseed=numval3($symb);
 8181: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8182: 	my $CODEseed=numval3(&getCODE());
 8183: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8184: 	my $num1=$symbseed+$CODEchck;
 8185: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8186: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8187: 	#&logthis("rndseed :$num1:$num2:$symb");
 8188: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8189: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8190: 	return "$num1:$num2";
 8191:     }
 8192: }
 8193: 
 8194: sub rndseed_CODE_64bit5 {
 8195:     my ($symb,$courseid,$domain,$username)=@_;
 8196:     my $code = &getCODE();
 8197:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8198:     return "$num1:$num2";
 8199: }
 8200: 
 8201: sub setup_random_from_rndseed {
 8202:     my ($rndseed)=@_;
 8203:     if ($rndseed =~/([,:])/) {
 8204: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8205: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8206:     } else {
 8207: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8208:     }
 8209: }
 8210: 
 8211: sub latest_receipt_algorithm_id {
 8212:     return 'receipt3';
 8213: }
 8214: 
 8215: sub recunique {
 8216:     my $fucourseid=shift;
 8217:     my $unique;
 8218:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8219: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8220: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8221:     } else {
 8222: 	$unique=$perlvar{'lonReceipt'};
 8223:     }
 8224:     return unpack("%32C*",$unique);
 8225: }
 8226: 
 8227: sub recprefix {
 8228:     my $fucourseid=shift;
 8229:     my $prefix;
 8230:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8231: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8232: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8233:     } else {
 8234: 	$prefix=$perlvar{'lonHostID'};
 8235:     }
 8236:     return unpack("%32C*",$prefix);
 8237: }
 8238: 
 8239: sub ireceipt {
 8240:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8241: 
 8242:     my $return =&recprefix($fucourseid).'-';
 8243: 
 8244:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8245: 	$env{'request.state'} eq 'construct') {
 8246: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8247: 	return $return;
 8248:     }
 8249: 
 8250:     my $cuname=unpack("%32C*",$funame);
 8251:     my $cudom=unpack("%32C*",$fudom);
 8252:     my $cucourseid=unpack("%32C*",$fucourseid);
 8253:     my $cusymb=unpack("%32C*",$fusymb);
 8254:     my $cunique=&recunique($fucourseid);
 8255:     my $cpart=unpack("%32S*",$part);
 8256:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8257: 
 8258: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8259: 			       
 8260: 	$return.= ($cunique%$cuname+
 8261: 		   $cunique%$cudom+
 8262: 		   $cusymb%$cuname+
 8263: 		   $cusymb%$cudom+
 8264: 		   $cucourseid%$cuname+
 8265: 		   $cucourseid%$cudom+
 8266: 		   $cpart%$cuname+
 8267: 		   $cpart%$cudom);
 8268:     } else {
 8269: 	$return.= ($cunique%$cuname+
 8270: 		   $cunique%$cudom+
 8271: 		   $cusymb%$cuname+
 8272: 		   $cusymb%$cudom+
 8273: 		   $cucourseid%$cuname+
 8274: 		   $cucourseid%$cudom);
 8275:     }
 8276:     return $return;
 8277: }
 8278: 
 8279: sub receipt {
 8280:     my ($part)=@_;
 8281:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8282:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8283: }
 8284: 
 8285: sub whichuser {
 8286:     my ($passedsymb)=@_;
 8287:     my ($symb,$courseid,$domain,$name,$publicuser);
 8288:     if (defined($env{'form.grade_symb'})) {
 8289: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8290: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8291: 	if (!$allowed &&
 8292: 	    exists($env{'request.course.sec'}) &&
 8293: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8294: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8295: 			      '/'.$env{'request.course.sec'});
 8296: 	}
 8297: 	if ($allowed) {
 8298: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8299: 	    $courseid=$tmp_courseid;
 8300: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8301: 	    ($name)=&get_env_multiple('form.grade_username');
 8302: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8303: 	}
 8304:     }
 8305:     if (!$passedsymb) {
 8306: 	$symb=&symbread();
 8307:     } else {
 8308: 	$symb=$passedsymb;
 8309:     }
 8310:     $courseid=$env{'request.course.id'};
 8311:     $domain=$env{'user.domain'};
 8312:     $name=$env{'user.name'};
 8313:     if ($name eq 'public' && $domain eq 'public') {
 8314: 	if (!defined($env{'form.username'})) {
 8315: 	    $env{'form.username'}.=time.rand(10000000);
 8316: 	}
 8317: 	$name.=$env{'form.username'};
 8318:     }
 8319:     return ($symb,$courseid,$domain,$name,$publicuser);
 8320: 
 8321: }
 8322: 
 8323: # ------------------------------------------------------------ Serves up a file
 8324: # returns either the contents of the file or 
 8325: # -1 if the file doesn't exist
 8326: #
 8327: # if the target is a file that was uploaded via DOCS, 
 8328: # a check will be made to see if a current copy exists on the local server,
 8329: # if it does this will be served, otherwise a copy will be retrieved from
 8330: # the home server for the course and stored in /home/httpd/html/userfiles on
 8331: # the local server.   
 8332: 
 8333: sub getfile {
 8334:     my ($file) = @_;
 8335:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8336:     &repcopy($file);
 8337:     return &readfile($file);
 8338: }
 8339: 
 8340: sub repcopy_userfile {
 8341:     my ($file)=@_;
 8342:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8343:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8344:     my ($cdom,$cnum,$filename) = 
 8345: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8346:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8347:     if (-e "$file") {
 8348: # we already have a local copy, check it out
 8349: 	my @fileinfo = stat($file);
 8350: 	my $rtncode;
 8351: 	my $info;
 8352: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8353: 	if ($lwpresp ne 'ok') {
 8354: # there is no such file anymore, even though we had a local copy
 8355: 	    if ($rtncode eq '404') {
 8356: 		unlink($file);
 8357: 	    }
 8358: 	    return -1;
 8359: 	}
 8360: 	if ($info < $fileinfo[9]) {
 8361: # nice, the file we have is up-to-date, just say okay
 8362: 	    return 'ok';
 8363: 	} else {
 8364: # the file is outdated, get rid of it
 8365: 	    unlink($file);
 8366: 	}
 8367:     }
 8368: # one way or the other, at this point, we don't have the file
 8369: # construct the correct path for the file
 8370:     my @parts = ($cdom,$cnum); 
 8371:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8372: 	push @parts, split(/\//,$1);
 8373:     }
 8374:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8375:     foreach my $part (@parts) {
 8376: 	$path .= '/'.$part;
 8377: 	if (!-e $path) {
 8378: 	    mkdir($path,0770);
 8379: 	}
 8380:     }
 8381: # now the path exists for sure
 8382: # get a user agent
 8383:     my $ua=new LWP::UserAgent;
 8384:     my $transferfile=$file.'.in.transfer';
 8385: # FIXME: this should flock
 8386:     if (-e $transferfile) { return 'ok'; }
 8387:     my $request;
 8388:     $uri=~s/^\///;
 8389:     my $homeserver = &homeserver($cnum,$cdom);
 8390:     my $protocol = $protocol{$homeserver};
 8391:     $protocol = 'http' if ($protocol ne 'https');
 8392:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8393:     my $response=$ua->request($request,$transferfile);
 8394: # did it work?
 8395:     if ($response->is_error()) {
 8396: 	unlink($transferfile);
 8397: 	&logthis("Userfile repcopy failed for $uri");
 8398: 	return -1;
 8399:     }
 8400: # worked, rename the transfer file
 8401:     rename($transferfile,$file);
 8402:     return 'ok';
 8403: }
 8404: 
 8405: sub tokenwrapper {
 8406:     my $uri=shift;
 8407:     $uri=~s|^https?\://([^/]+)||;
 8408:     $uri=~s|^/||;
 8409:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8410:     my $token=$1;
 8411:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8412:     if ($udom && $uname && $file) {
 8413: 	$file=~s|(\?\.*)*$||;
 8414:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8415:         my $homeserver = &homeserver($uname,$udom);
 8416:         my $protocol = $protocol{$homeserver};
 8417:         $protocol = 'http' if ($protocol ne 'https');
 8418:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8419:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8420:                                '&tokenissued='.$perlvar{'lonHostID'};
 8421:     } else {
 8422:         return '/adm/notfound.html';
 8423:     }
 8424: }
 8425: 
 8426: # call with reqtype HEAD: get last modification time
 8427: # call with reqtype GET: get the file contents
 8428: # Do not call this with reqtype GET for large files! It loads everything into memory
 8429: #
 8430: sub getuploaded {
 8431:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8432:     $uri=~s/^\///;
 8433:     my $homeserver = &homeserver($cnum,$cdom);
 8434:     my $protocol = $protocol{$homeserver};
 8435:     $protocol = 'http' if ($protocol ne 'https');
 8436:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8437:     my $ua=new LWP::UserAgent;
 8438:     my $request=new HTTP::Request($reqtype,$uri);
 8439:     my $response=$ua->request($request);
 8440:     $$rtncode = $response->code;
 8441:     if (! $response->is_success()) {
 8442: 	return 'failed';
 8443:     }      
 8444:     if ($reqtype eq 'HEAD') {
 8445: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8446:     } elsif ($reqtype eq 'GET') {
 8447: 	$$info = $response->content;
 8448:     }
 8449:     return 'ok';
 8450: }
 8451: 
 8452: sub readfile {
 8453:     my $file = shift;
 8454:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8455:     my $fh;
 8456:     open($fh,"<$file");
 8457:     my $a='';
 8458:     while (my $line = <$fh>) { $a .= $line; }
 8459:     return $a;
 8460: }
 8461: 
 8462: sub filelocation {
 8463:     my ($dir,$file) = @_;
 8464:     my $location;
 8465:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8466: 
 8467:     if ($file =~ m-^/adm/-) {
 8468: 	$file=~s-^/adm/wrapper/-/-;
 8469: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8470:     }
 8471: 
 8472:     if ($file=~m:^/~:) { # is a contruction space reference
 8473:         $location = $file;
 8474:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8475:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8476: 	# is a correct contruction space reference
 8477:         $location = $file;
 8478:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8479:         $location = $file;
 8480:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8481:         my ($udom,$uname,$filename)=
 8482:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8483:         my $home=&homeserver($uname,$udom);
 8484:         my $is_me=0;
 8485:         my @ids=&current_machine_ids();
 8486:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8487:         if ($is_me) {
 8488:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8489:         } else {
 8490:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8491:   	      $udom.'/'.$uname.'/'.$filename;
 8492:         }
 8493:     } elsif ($file =~ m-^/adm/-) {
 8494: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8495:     } else {
 8496:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8497:         $file=~s:^/res/:/:;
 8498:         if ( !( $file =~ m:^/:) ) {
 8499:             $location = $dir. '/'.$file;
 8500:         } else {
 8501:             $location = '/home/httpd/html/res'.$file;
 8502:         }
 8503:     }
 8504:     $location=~s://+:/:g; # remove duplicate /
 8505:     while ($location=~m{/\.\./}) {
 8506: 	if ($location =~ m{/[^/]+/\.\./}) {
 8507: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8508: 	} else {
 8509: 	    $location=~ s{/\.\./}{/}g;
 8510: 	}
 8511:     } #remove dir/..
 8512:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8513:     return $location;
 8514: }
 8515: 
 8516: sub hreflocation {
 8517:     my ($dir,$file)=@_;
 8518:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8519: 	$file=filelocation($dir,$file);
 8520:     } elsif ($file=~m-^/adm/-) {
 8521: 	$file=~s-^/adm/wrapper/-/-;
 8522: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8523:     }
 8524:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8525: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8526:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8527: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8528:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8529: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8530: 	    -/uploaded/$1/$2/-x;
 8531:     }
 8532:     if ($file=~ m{^/userfiles/}) {
 8533: 	$file =~ s{^/userfiles/}{/uploaded/};
 8534:     }
 8535:     return $file;
 8536: }
 8537: 
 8538: sub current_machine_domains {
 8539:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8540: }
 8541: 
 8542: sub machine_domains {
 8543:     my ($hostname) = @_;
 8544:     my @domains;
 8545:     my %hostname = &all_hostnames();
 8546:     while( my($id, $name) = each(%hostname)) {
 8547: #	&logthis("-$id-$name-$hostname-");
 8548: 	if ($hostname eq $name) {
 8549: 	    push(@domains,&host_domain($id));
 8550: 	}
 8551:     }
 8552:     return @domains;
 8553: }
 8554: 
 8555: sub current_machine_ids {
 8556:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8557: }
 8558: 
 8559: sub machine_ids {
 8560:     my ($hostname) = @_;
 8561:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8562:     my @ids;
 8563:     my %name_to_host = &all_names();
 8564:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8565: 	return @{ $name_to_host{$hostname} };
 8566:     }
 8567:     return;
 8568: }
 8569: 
 8570: sub additional_machine_domains {
 8571:     my @domains;
 8572:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8573:     while( my $line = <$fh>) {
 8574:         $line =~ s/\s//g;
 8575:         push(@domains,$line);
 8576:     }
 8577:     return @domains;
 8578: }
 8579: 
 8580: sub default_login_domain {
 8581:     my $domain = $perlvar{'lonDefDomain'};
 8582:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8583:     foreach my $posdom (&current_machine_domains(),
 8584:                         &additional_machine_domains()) {
 8585:         if (lc($posdom) eq lc($testdomain)) {
 8586:             $domain=$posdom;
 8587:             last;
 8588:         }
 8589:     }
 8590:     return $domain;
 8591: }
 8592: 
 8593: # ------------------------------------------------------------- Declutters URLs
 8594: 
 8595: sub declutter {
 8596:     my $thisfn=shift;
 8597:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8598:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8599:     $thisfn=~s/^\///;
 8600:     $thisfn=~s|^adm/wrapper/||;
 8601:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8602:     $thisfn=~s/^res\///;
 8603:     $thisfn=~s/\?.+$//;
 8604:     return $thisfn;
 8605: }
 8606: 
 8607: # ------------------------------------------------------------- Clutter up URLs
 8608: 
 8609: sub clutter {
 8610:     my $thisfn='/'.&declutter(shift);
 8611:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8612: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8613:        $thisfn='/res'.$thisfn; 
 8614:     }
 8615:     if ($thisfn !~m|/adm|) {
 8616: 	if ($thisfn =~ m|/ext/|) {
 8617: 	    $thisfn='/adm/wrapper'.$thisfn;
 8618: 	} else {
 8619: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8620: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8621: 	    if ($embstyle eq 'ssi'
 8622: 		|| ($embstyle eq 'hdn')
 8623: 		|| ($embstyle eq 'rat')
 8624: 		|| ($embstyle eq 'prv')
 8625: 		|| ($embstyle eq 'ign')) {
 8626: 		#do nothing with these
 8627: 	    } elsif (($embstyle eq 'img') 
 8628: 		|| ($embstyle eq 'emb')
 8629: 		|| ($embstyle eq 'wrp')) {
 8630: 		$thisfn='/adm/wrapper'.$thisfn;
 8631: 	    } elsif ($embstyle eq 'unk'
 8632: 		     && $thisfn!~/\.(sequence|page)$/) {
 8633: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8634: 	    } else {
 8635: #		&logthis("Got a blank emb style");
 8636: 	    }
 8637: 	}
 8638:     }
 8639:     return $thisfn;
 8640: }
 8641: 
 8642: sub clutter_with_no_wrapper {
 8643:     my $uri = &clutter(shift);
 8644:     if ($uri =~ m-^/adm/-) {
 8645: 	$uri =~ s-^/adm/wrapper/-/-;
 8646: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8647:     }
 8648:     return $uri;
 8649: }
 8650: 
 8651: sub freeze_escape {
 8652:     my ($value)=@_;
 8653:     if (ref($value)) {
 8654: 	$value=&nfreeze($value);
 8655: 	return '__FROZEN__'.&escape($value);
 8656:     }
 8657:     return &escape($value);
 8658: }
 8659: 
 8660: 
 8661: sub thaw_unescape {
 8662:     my ($value)=@_;
 8663:     if ($value =~ /^__FROZEN__/) {
 8664: 	substr($value,0,10,undef);
 8665: 	$value=&unescape($value);
 8666: 	return &thaw($value);
 8667:     }
 8668:     return &unescape($value);
 8669: }
 8670: 
 8671: sub correct_line_ends {
 8672:     my ($result)=@_;
 8673:     $$result =~s/\r\n/\n/mg;
 8674:     $$result =~s/\r/\n/mg;
 8675: }
 8676: # ================================================================ Main Program
 8677: 
 8678: sub goodbye {
 8679:    &logthis("Starting Shut down");
 8680: #not converted to using infrastruture and probably shouldn't be
 8681:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8682: #converted
 8683: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8684:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8685: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8686: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8687: #1.1 only
 8688: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8689: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8690: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8691: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8692:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8693:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8694:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8695:    &flushcourselogs();
 8696:    &logthis("Shutting down");
 8697: }
 8698: 
 8699: sub get_dns {
 8700:     my ($url,$func,$ignore_cache) = @_;
 8701:     if (!$ignore_cache) {
 8702: 	my ($content,$cached)=
 8703: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8704: 	if ($cached) {
 8705: 	    &$func($content);
 8706: 	    return;
 8707: 	}
 8708:     }
 8709: 
 8710:     my %alldns;
 8711:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8712:     foreach my $dns (<$config>) {
 8713: 	next if ($dns !~ /^\^(\S*)/x);
 8714:         my $line = $1;
 8715:         my ($host,$protocol) = split(/:/,$line);
 8716:         if ($protocol ne 'https') {
 8717:             $protocol = 'http';
 8718:         }
 8719: 	$alldns{$host} = $protocol;
 8720:     }
 8721:     while (%alldns) {
 8722: 	my ($dns) = keys(%alldns);
 8723: 	my $ua=new LWP::UserAgent;
 8724: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8725: 	my $response=$ua->request($request);
 8726:         delete($alldns{$dns});
 8727: 	next if ($response->is_error());
 8728: 	my @content = split("\n",$response->content);
 8729: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8730: 	&$func(\@content);
 8731: 	return;
 8732:     }
 8733:     close($config);
 8734:     my $which = (split('/',$url))[3];
 8735:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8736:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8737:     my @content = <$config>;
 8738:     &$func(\@content);
 8739:     return;
 8740: }
 8741: # ------------------------------------------------------------ Read domain file
 8742: {
 8743:     my $loaded;
 8744:     my %domain;
 8745: 
 8746:     sub parse_domain_tab {
 8747: 	my ($lines) = @_;
 8748: 	foreach my $line (@$lines) {
 8749: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8750: 
 8751: 	    chomp($line);
 8752: 	    my ($name,@elements) = split(/:/,$line,9);
 8753: 	    my %this_domain;
 8754: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8755: 			       'lang_def', 'city', 'longi', 'lati',
 8756: 			       'primary') {
 8757: 		$this_domain{$field} = shift(@elements);
 8758: 	    }
 8759: 	    $domain{$name} = \%this_domain;
 8760: 	}
 8761:     }
 8762: 
 8763:     sub reset_domain_info {
 8764: 	undef($loaded);
 8765: 	undef(%domain);
 8766:     }
 8767: 
 8768:     sub load_domain_tab {
 8769: 	my ($ignore_cache) = @_;
 8770: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8771: 	my $fh;
 8772: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8773: 	    my @lines = <$fh>;
 8774: 	    &parse_domain_tab(\@lines);
 8775: 	}
 8776: 	close($fh);
 8777: 	$loaded = 1;
 8778:     }
 8779: 
 8780:     sub domain {
 8781: 	&load_domain_tab() if (!$loaded);
 8782: 
 8783: 	my ($name,$what) = @_;
 8784: 	return if ( !exists($domain{$name}) );
 8785: 
 8786: 	if (!$what) {
 8787: 	    return $domain{$name}{'description'};
 8788: 	}
 8789: 	return $domain{$name}{$what};
 8790:     }
 8791: 
 8792:     sub domain_info {
 8793:         &load_domain_tab() if (!$loaded);
 8794:         return %domain;
 8795:     }
 8796: 
 8797: }
 8798: 
 8799: 
 8800: # ------------------------------------------------------------- Read hosts file
 8801: {
 8802:     my %hostname;
 8803:     my %hostdom;
 8804:     my %libserv;
 8805:     my $loaded;
 8806:     my %name_to_host;
 8807: 
 8808:     sub parse_hosts_tab {
 8809: 	my ($file) = @_;
 8810: 	foreach my $configline (@$file) {
 8811: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8812: 	    next if ($configline =~ /^\^/);
 8813: 	    chomp($configline);
 8814: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8815: 	    $name=~s/\s//g;
 8816: 	    if ($id && $domain && $role && $name) {
 8817: 		$hostname{$id}=$name;
 8818: 		push(@{$name_to_host{$name}}, $id);
 8819: 		$hostdom{$id}=$domain;
 8820: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8821:                 if (defined($protocol)) {
 8822:                     if ($protocol eq 'https') {
 8823:                         $protocol{$id} = $protocol;
 8824:                     } else {
 8825:                         $protocol{$id} = 'http'; 
 8826:                     }
 8827:                 } else {
 8828:                     $protocol{$id} = 'http';
 8829:                 }
 8830: 	    }
 8831: 	}
 8832:     }
 8833:     
 8834:     sub reset_hosts_info {
 8835: 	&purge_remembered();
 8836: 	&reset_domain_info();
 8837: 	&reset_hosts_ip_info();
 8838: 	undef(%name_to_host);
 8839: 	undef(%hostname);
 8840: 	undef(%hostdom);
 8841: 	undef(%libserv);
 8842: 	undef($loaded);
 8843:     }
 8844: 
 8845:     sub load_hosts_tab {
 8846: 	my ($ignore_cache) = @_;
 8847: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8848: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8849: 	my @config = <$config>;
 8850: 	&parse_hosts_tab(\@config);
 8851: 	close($config);
 8852: 	$loaded=1;
 8853:     }
 8854: 
 8855:     sub hostname {
 8856: 	&load_hosts_tab() if (!$loaded);
 8857: 
 8858: 	my ($lonid) = @_;
 8859: 	return $hostname{$lonid};
 8860:     }
 8861: 
 8862:     sub all_hostnames {
 8863: 	&load_hosts_tab() if (!$loaded);
 8864: 
 8865: 	return %hostname;
 8866:     }
 8867: 
 8868:     sub all_names {
 8869: 	&load_hosts_tab() if (!$loaded);
 8870: 
 8871: 	return %name_to_host;
 8872:     }
 8873: 
 8874:     sub all_host_domain {
 8875:         &load_hosts_tab() if (!$loaded);
 8876:         return %hostdom;
 8877:     }
 8878: 
 8879:     sub is_library {
 8880: 	&load_hosts_tab() if (!$loaded);
 8881: 
 8882: 	return exists($libserv{$_[0]});
 8883:     }
 8884: 
 8885:     sub all_library {
 8886: 	&load_hosts_tab() if (!$loaded);
 8887: 
 8888: 	return %libserv;
 8889:     }
 8890: 
 8891:     sub get_servers {
 8892: 	&load_hosts_tab() if (!$loaded);
 8893: 
 8894: 	my ($domain,$type) = @_;
 8895: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8896: 	                                          : %hostname;
 8897: 	my %result;
 8898: 	if (ref($domain) eq 'ARRAY') {
 8899: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8900: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8901: 		    $result{$host} = $hostname;
 8902: 		}
 8903: 	    }
 8904: 	} else {
 8905: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8906: 		if ($hostdom{$host} eq $domain) {
 8907: 		    $result{$host} = $hostname;
 8908: 		}
 8909: 	    }
 8910: 	}
 8911: 	return %result;
 8912:     }
 8913: 
 8914:     sub host_domain {
 8915: 	&load_hosts_tab() if (!$loaded);
 8916: 
 8917: 	my ($lonid) = @_;
 8918: 	return $hostdom{$lonid};
 8919:     }
 8920: 
 8921:     sub all_domains {
 8922: 	&load_hosts_tab() if (!$loaded);
 8923: 
 8924: 	my %seen;
 8925: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8926: 	return @uniq;
 8927:     }
 8928: }
 8929: 
 8930: { 
 8931:     my %iphost;
 8932:     my %name_to_ip;
 8933:     my %lonid_to_ip;
 8934: 
 8935:     sub get_hosts_from_ip {
 8936: 	my ($ip) = @_;
 8937: 	my %iphosts = &get_iphost();
 8938: 	if (ref($iphosts{$ip})) {
 8939: 	    return @{$iphosts{$ip}};
 8940: 	}
 8941: 	return;
 8942:     }
 8943:     
 8944:     sub reset_hosts_ip_info {
 8945: 	undef(%iphost);
 8946: 	undef(%name_to_ip);
 8947: 	undef(%lonid_to_ip);
 8948:     }
 8949: 
 8950:     sub get_host_ip {
 8951: 	my ($lonid) = @_;
 8952: 	if (exists($lonid_to_ip{$lonid})) {
 8953: 	    return $lonid_to_ip{$lonid};
 8954: 	}
 8955: 	my $name=&hostname($lonid);
 8956:    	my $ip = gethostbyname($name);
 8957: 	return if (!$ip || length($ip) ne 4);
 8958: 	$ip=inet_ntoa($ip);
 8959: 	$name_to_ip{$name}   = $ip;
 8960: 	$lonid_to_ip{$lonid} = $ip;
 8961: 	return $ip;
 8962:     }
 8963:     
 8964:     sub get_iphost {
 8965: 	my ($ignore_cache) = @_;
 8966: 
 8967: 	if (!$ignore_cache) {
 8968: 	    if (%iphost) {
 8969: 		return %iphost;
 8970: 	    }
 8971: 	    my ($ip_info,$cached)=
 8972: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8973: 	    if ($cached) {
 8974: 		%iphost      = %{$ip_info->[0]};
 8975: 		%name_to_ip  = %{$ip_info->[1]};
 8976: 		%lonid_to_ip = %{$ip_info->[2]};
 8977: 		return %iphost;
 8978: 	    }
 8979: 	}
 8980: 
 8981: 	# get yesterday's info for fallback
 8982: 	my %old_name_to_ip;
 8983: 	my ($ip_info,$cached)=
 8984: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8985: 	if ($cached) {
 8986: 	    %old_name_to_ip = %{$ip_info->[1]};
 8987: 	}
 8988: 
 8989: 	my %name_to_host = &all_names();
 8990: 	foreach my $name (keys(%name_to_host)) {
 8991: 	    my $ip;
 8992: 	    if (!exists($name_to_ip{$name})) {
 8993: 		$ip = gethostbyname($name);
 8994: 		if (!$ip || length($ip) ne 4) {
 8995: 		    if (defined($old_name_to_ip{$name})) {
 8996: 			$ip = $old_name_to_ip{$name};
 8997: 			&logthis("Can't find $name defaulting to old $ip");
 8998: 		    } else {
 8999: 			&logthis("Name $name no IP found");
 9000: 			next;
 9001: 		    }
 9002: 		} else {
 9003: 		    $ip=inet_ntoa($ip);
 9004: 		}
 9005: 		$name_to_ip{$name} = $ip;
 9006: 	    } else {
 9007: 		$ip = $name_to_ip{$name};
 9008: 	    }
 9009: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9010: 		$lonid_to_ip{$id} = $ip;
 9011: 	    }
 9012: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9013: 	}
 9014: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9015: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9016: 				      48*60*60);
 9017: 
 9018: 	return %iphost;
 9019:     }
 9020: }
 9021: 
 9022: #
 9023: #  Given a DNS returns the loncapa host name for that DNS 
 9024: # 
 9025: sub host_from_dns {
 9026:     my ($dns) = @_;
 9027:     my @hosts;
 9028:     my $ip;
 9029: 
 9030:     $ip = gethostbyname($dns);	# Initial translation to IP is in net order.
 9031:     if (length($ip) == 4) { 
 9032: 	$ip   = &IO::Socket::inet_ntoa($ip);
 9033: 	@hosts = get_hosts_from_ip($ip);
 9034: 	return $hosts[0];
 9035:     }
 9036:     return undef;
 9037: }
 9038: 
 9039: BEGIN {
 9040: 
 9041: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9042:     unless ($readit) {
 9043: {
 9044:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9045:     %perlvar = (%perlvar,%{$configvars});
 9046: }
 9047: 
 9048: 
 9049: # ------------------------------------------------------ Read spare server file
 9050: {
 9051:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9052: 
 9053:     while (my $configline=<$config>) {
 9054:        chomp($configline);
 9055:        if ($configline) {
 9056: 	   my ($host,$type) = split(':',$configline,2);
 9057: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9058: 	   push(@{ $spareid{$type} }, $host);
 9059:        }
 9060:     }
 9061:     close($config);
 9062: }
 9063: # ------------------------------------------------------------ Read permissions
 9064: {
 9065:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9066: 
 9067:     while (my $configline=<$config>) {
 9068: 	chomp($configline);
 9069: 	if ($configline) {
 9070: 	    my ($role,$perm)=split(/ /,$configline);
 9071: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9072: 	}
 9073:     }
 9074:     close($config);
 9075: }
 9076: 
 9077: # -------------------------------------------- Read plain texts for permissions
 9078: {
 9079:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9080: 
 9081:     while (my $configline=<$config>) {
 9082: 	chomp($configline);
 9083: 	if ($configline) {
 9084: 	    my ($short,@plain)=split(/:/,$configline);
 9085:             %{$prp{$short}} = ();
 9086: 	    if (@plain > 0) {
 9087:                 $prp{$short}{'std'} = $plain[0];
 9088:                 for (my $i=1; $i<@plain; $i++) {
 9089:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9090:                 }
 9091:             }
 9092: 	}
 9093:     }
 9094:     close($config);
 9095: }
 9096: 
 9097: # ---------------------------------------------------------- Read package table
 9098: {
 9099:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9100: 
 9101:     while (my $configline=<$config>) {
 9102: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9103: 	chomp($configline);
 9104: 	my ($short,$plain)=split(/:/,$configline);
 9105: 	my ($pack,$name)=split(/\&/,$short);
 9106: 	if ($plain ne '') {
 9107: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9108: 	    $packagetab{$short}=$plain; 
 9109: 	}
 9110:     }
 9111:     close($config);
 9112: }
 9113: 
 9114: # ------------- set up temporary directory
 9115: {
 9116:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9117: 
 9118: }
 9119: 
 9120: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9121: 				'compress_threshold'=> 20_000,
 9122:  			        });
 9123: 
 9124: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9125: $dumpcount=0;
 9126: $locknum=0;
 9127: 
 9128: &logtouch();
 9129: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9130: $readit=1;
 9131:     {
 9132: 	use integer;
 9133: 	my $test=(2**32)+1;
 9134: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9135: 	&logthis(" Detected 64bit platform ($_64bit)");
 9136:     }
 9137: }
 9138: }
 9139: 
 9140: 1;
 9141: __END__
 9142: 
 9143: =pod
 9144: 
 9145: =head1 NAME
 9146: 
 9147: Apache::lonnet - Subroutines to ask questions about things in the network.
 9148: 
 9149: =head1 SYNOPSIS
 9150: 
 9151: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9152: 
 9153:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9154: 
 9155: Common parameters:
 9156: 
 9157: =over 4
 9158: 
 9159: =item *
 9160: 
 9161: $uname : an internal username (if $cname expecting a course Id specifically)
 9162: 
 9163: =item *
 9164: 
 9165: $udom : a domain (if $cdom expecting a course's domain specifically)
 9166: 
 9167: =item *
 9168: 
 9169: $symb : a resource instance identifier
 9170: 
 9171: =item *
 9172: 
 9173: $namespace : the name of a .db file that contains the data needed or
 9174: being set.
 9175: 
 9176: =back
 9177: 
 9178: =head1 OVERVIEW
 9179: 
 9180: lonnet provides subroutines which interact with the
 9181: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9182: about classes, users, and resources.
 9183: 
 9184: For many of these objects you can also use this to store data about
 9185: them or modify them in various ways.
 9186: 
 9187: =head2 Symbs
 9188: 
 9189: To identify a specific instance of a resource, LON-CAPA uses symbols
 9190: or "symbs"X<symb>. These identifiers are built from the URL of the
 9191: map, the resource number of the resource in the map, and the URL of
 9192: the resource itself. The latter is somewhat redundant, but might help
 9193: if maps change.
 9194: 
 9195: An example is
 9196: 
 9197:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9198: 
 9199: The respective map entry is
 9200: 
 9201:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9202:   title="Problem 2">
 9203:  </resource>
 9204: 
 9205: Symbs are used by the random number generator, as well as to store and
 9206: restore data specific to a certain instance of for example a problem.
 9207: 
 9208: =head2 Storing And Retrieving Data
 9209: 
 9210: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9211: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9212: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9213: is is the non-critical message twin of cstore. These functions are for
 9214: handlers to store a perl hash to a user's permanent data space in an
 9215: easy manner, and to retrieve it again on another call. It is expected
 9216: that a handler would use this once at the beginning to retrieve data,
 9217: and then again once at the end to send only the new data back.
 9218: 
 9219: The data is stored in the user's data directory on the user's
 9220: homeserver under the ID of the course.
 9221: 
 9222: The hash that is returned by restore will have all of the previous
 9223: value for all of the elements of the hash.
 9224: 
 9225: Example:
 9226: 
 9227:  #creating a hash
 9228:  my %hash;
 9229:  $hash{'foo'}='bar';
 9230: 
 9231:  #storing it
 9232:  &Apache::lonnet::cstore(\%hash);
 9233: 
 9234:  #changing a value
 9235:  $hash{'foo'}='notbar';
 9236: 
 9237:  #adding a new value
 9238:  $hash{'bar'}='foo';
 9239:  &Apache::lonnet::cstore(\%hash);
 9240: 
 9241:  #retrieving the hash
 9242:  my %history=&Apache::lonnet::restore();
 9243: 
 9244:  #print the hash
 9245:  foreach my $key (sort(keys(%history))) {
 9246:    print("\%history{$key} = $history{$key}");
 9247:  }
 9248: 
 9249: Will print out:
 9250: 
 9251:  %history{1:foo} = bar
 9252:  %history{1:keys} = foo:timestamp
 9253:  %history{1:timestamp} = 990455579
 9254:  %history{2:bar} = foo
 9255:  %history{2:foo} = notbar
 9256:  %history{2:keys} = foo:bar:timestamp
 9257:  %history{2:timestamp} = 990455580
 9258:  %history{bar} = foo
 9259:  %history{foo} = notbar
 9260:  %history{timestamp} = 990455580
 9261:  %history{version} = 2
 9262: 
 9263: Note that the special hash entries C<keys>, C<version> and
 9264: C<timestamp> were added to the hash. C<version> will be equal to the
 9265: total number of versions of the data that have been stored. The
 9266: C<timestamp> attribute will be the UNIX time the hash was
 9267: stored. C<keys> is available in every historical section to list which
 9268: keys were added or changed at a specific historical revision of a
 9269: hash.
 9270: 
 9271: B<Warning>: do not store the hash that restore returns directly. This
 9272: will cause a mess since it will restore the historical keys as if the
 9273: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9274: 
 9275: Calling convention:
 9276: 
 9277:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9278:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9279: 
 9280: For more detailed information, see lonnet specific documentation.
 9281: 
 9282: =head1 RETURN MESSAGES
 9283: 
 9284: =over 4
 9285: 
 9286: =item * B<con_lost>: unable to contact remote host
 9287: 
 9288: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9289: when the connection is brought back up
 9290: 
 9291: =item * B<con_failed>: unable to contact remote host and unable to save message
 9292: for later delivery
 9293: 
 9294: =item * B<error:>: an error a occurred, a description of the error follows the :
 9295: 
 9296: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9297: that was requested
 9298: 
 9299: =back
 9300: 
 9301: =head1 PUBLIC SUBROUTINES
 9302: 
 9303: =head2 Session Environment Functions
 9304: 
 9305: =over 4
 9306: 
 9307: =item * 
 9308: X<appenv()>
 9309: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9310: the user envirnoment file, and will be restored for each access this
 9311: user makes during this session, also modifies the %env for the current
 9312: process. Optional rolesarrayref - if defined contains a reference to an array
 9313: of roles which are exempt from the restriction on modifying user.role entries 
 9314: in the user's environment.db and in %env.    
 9315: 
 9316: =item *
 9317: X<delenv()>
 9318: B<delenv($delthis,$regexp)>: removes all items from the session
 9319: environment file that begin with $delthis. If the 
 9320: optional second arg - $regexp - is true, $delthis is treated as a 
 9321: regular expression, otherwise \Q$delthis\E is used. 
 9322: The values are also deleted from the current processes %env.
 9323: 
 9324: =item * get_env_multiple($name) 
 9325: 
 9326: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9327: values may be defined and end up as an array ref.
 9328: 
 9329: returns an array of values
 9330: 
 9331: =back
 9332: 
 9333: =head2 User Information
 9334: 
 9335: =over 4
 9336: 
 9337: =item *
 9338: X<queryauthenticate()>
 9339: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9340: authentication scheme
 9341: 
 9342: =item *
 9343: X<authenticate()>
 9344: B<authenticate($uname,$upass,$udom)>: try to
 9345: authenticate user from domain's lib servers (first use the current
 9346: one). C<$upass> should be the users password.
 9347: 
 9348: =item *
 9349: X<homeserver()>
 9350: B<homeserver($uname,$udom)>: find the server which has
 9351: the user's directory and files (there must be only one), this caches
 9352: the answer, and also caches if there is a borken connection.
 9353: 
 9354: =item *
 9355: X<idget()>
 9356: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9357: (IDs are a unique resource in a domain, there must be only 1 ID per
 9358: username, and only 1 username per ID in a specific domain) (returns
 9359: hash: id=>name,id=>name)
 9360: 
 9361: =item *
 9362: X<idrget()>
 9363: B<idrget($udom,@unames)>: find the IDs behind a list of
 9364: usernames (returns hash: name=>id,name=>id)
 9365: 
 9366: =item *
 9367: X<idput()>
 9368: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9369: 
 9370: =item *
 9371: X<rolesinit()>
 9372: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9373: 
 9374: =item *
 9375: X<getsection()>
 9376: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9377: course $cname, return section name/number or '' for "not in course"
 9378: and '-1' for "no section"
 9379: 
 9380: =item *
 9381: X<userenvironment()>
 9382: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9383: passed in @what from the requested user's environment, returns a hash
 9384: 
 9385: =item * 
 9386: X<userlog_query()>
 9387: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9388: activity.log file. %filters defines filters applied when parsing the
 9389: log file. These can be start or end timestamps, or the type of action
 9390: - log to look for Login or Logout events, check for Checkin or
 9391: Checkout, role for role selection. The response is in the form
 9392: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9393: escaped strings of the action recorded in the activity.log file.
 9394: 
 9395: =back
 9396: 
 9397: =head2 User Roles
 9398: 
 9399: =over 4
 9400: 
 9401: =item *
 9402: 
 9403: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9404:  F: full access
 9405:  U,I,K: authentication modes (cxx only)
 9406:  '': forbidden
 9407:  1: user needs to choose course
 9408:  2: browse allowed
 9409:  A: passphrase authentication needed
 9410: 
 9411: =item *
 9412: 
 9413: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9414: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9415: and course level
 9416: 
 9417: =item *
 9418: 
 9419: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9420: explanation of a user role term
 9421: 
 9422: =item *
 9423: 
 9424: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9425: All arguments are optional. Returns a hash of a roles, either for
 9426: co-author/assistant author roles for a user's Construction Space
 9427: (default), or if $context is 'userroles', roles for the user himself,
 9428: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9429: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9430: For each key, value is set to colon-separated start and end times for
 9431: the role.  If no username and domain are specified, will default to
 9432: current user/domain. Types, roles, and roledoms are references to arrays
 9433: of role statuses (active, future or previous), roles 
 9434: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9435: to restrict the list of roles reported. If no array ref is 
 9436: provided for types, will default to return only active roles.
 9437: 
 9438: =back
 9439: 
 9440: =head2 User Modification
 9441: 
 9442: =over 4
 9443: 
 9444: =item *
 9445: 
 9446: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9447: user for the level given by URL.  Optional start and end dates (leave empty
 9448: string or zero for "no date")
 9449: 
 9450: =item *
 9451: 
 9452: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9453: change a users, password, possible return values are: ok,
 9454: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9455: refused
 9456: 
 9457: =item *
 9458: 
 9459: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9460: 
 9461: =item *
 9462: 
 9463: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9464:            $forceid,$desiredhome,$email,$inststatus) : 
 9465: modify user
 9466: 
 9467: =item *
 9468: 
 9469: modifystudent
 9470: 
 9471: modify a student's enrollment and identification information.
 9472: The course id is resolved based on the current users environment.  
 9473: This means the envoking user must be a course coordinator or otherwise
 9474: associated with a course.
 9475: 
 9476: This call is essentially a wrapper for lonnet::modifyuser and
 9477: lonnet::modify_student_enrollment
 9478: 
 9479: Inputs: 
 9480: 
 9481: =over 4
 9482: 
 9483: =item B<$udom> Student's loncapa domain
 9484: 
 9485: =item B<$uname> Student's loncapa login name
 9486: 
 9487: =item B<$uid> Student/Employee ID
 9488: 
 9489: =item B<$umode> Student's authentication mode
 9490: 
 9491: =item B<$upass> Student's password
 9492: 
 9493: =item B<$first> Student's first name
 9494: 
 9495: =item B<$middle> Student's middle name
 9496: 
 9497: =item B<$last> Student's last name
 9498: 
 9499: =item B<$gene> Student's generation
 9500: 
 9501: =item B<$usec> Student's section in course
 9502: 
 9503: =item B<$end> Unix time of the roles expiration
 9504: 
 9505: =item B<$start> Unix time of the roles start date
 9506: 
 9507: =item B<$forceid> If defined, allow $uid to be changed
 9508: 
 9509: =item B<$desiredhome> server to use as home server for student
 9510: 
 9511: =item B<$email> Student's permanent e-mail address
 9512: 
 9513: =item B<$type> Type of enrollment (auto or manual)
 9514: 
 9515: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9516: 
 9517: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9518: 
 9519: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9520: 
 9521: =item B<$context> role change context (shown in User Management Logs display in a course)
 9522: 
 9523: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9524: 
 9525: =back
 9526: 
 9527: =item *
 9528: 
 9529: modify_student_enrollment
 9530: 
 9531: Change a students enrollment status in a class.  The environment variable
 9532: 'role.request.course' must be defined for this function to proceed.
 9533: 
 9534: Inputs:
 9535: 
 9536: =over 4
 9537: 
 9538: =item $udom, students domain
 9539: 
 9540: =item $uname, students name
 9541: 
 9542: =item $uid, students user id
 9543: 
 9544: =item $first, students first name
 9545: 
 9546: =item $middle
 9547: 
 9548: =item $last
 9549: 
 9550: =item $gene
 9551: 
 9552: =item $usec
 9553: 
 9554: =item $end
 9555: 
 9556: =item $start
 9557: 
 9558: =item $type
 9559: 
 9560: =item $locktype
 9561: 
 9562: =item $cid
 9563: 
 9564: =item $selfenroll
 9565: 
 9566: =item $context
 9567: 
 9568: =back
 9569: 
 9570: 
 9571: =item *
 9572: 
 9573: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9574: custom role; give a custom role to a user for the level given by URL.  Specify
 9575: name and domain of role author, and role name
 9576: 
 9577: =item *
 9578: 
 9579: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9580: 
 9581: =item *
 9582: 
 9583: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9584: 
 9585: =back
 9586: 
 9587: =head2 Course Infomation
 9588: 
 9589: =over 4
 9590: 
 9591: =item *
 9592: 
 9593: coursedescription($courseid) : returns a hash of information about the
 9594: specified course id, including all environment settings for the
 9595: course, the description of the course will be in the hash under the
 9596: key 'description'
 9597: 
 9598: =item *
 9599: 
 9600: resdata($name,$domain,$type,@which) : request for current parameter
 9601: setting for a specific $type, where $type is either 'course' or 'user',
 9602: @what should be a list of parameters to ask about. This routine caches
 9603: answers for 5 minutes.
 9604: 
 9605: =item *
 9606: 
 9607: get_courseresdata($courseid, $domain) : dump the entire course resource
 9608: data base, returning a hash that is keyed by the resource name and has
 9609: values that are the resource value.  I believe that the timestamps and
 9610: versions are also returned.
 9611: 
 9612: 
 9613: =back
 9614: 
 9615: =head2 Course Modification
 9616: 
 9617: =over 4
 9618: 
 9619: =item *
 9620: 
 9621: writecoursepref($courseid,%prefs) : write preferences (environment
 9622: database) for a course
 9623: 
 9624: =item *
 9625: 
 9626: createcourse($udom,$description,$url) : make/modify course
 9627: 
 9628: =back
 9629: 
 9630: =head2 Resource Subroutines
 9631: 
 9632: =over 4
 9633: 
 9634: =item *
 9635: 
 9636: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9637: 
 9638: =item *
 9639: 
 9640: repcopy($filename) : subscribes to the requested file, and attempts to
 9641: replicate from the owning library server, Might return
 9642: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9643: 'bad_request', also attempts to grab the metadata for the
 9644: resource. Expects the local filesystem pathname
 9645: (/home/httpd/html/res/....)
 9646: 
 9647: =back
 9648: 
 9649: =head2 Resource Information
 9650: 
 9651: =over 4
 9652: 
 9653: =item *
 9654: 
 9655: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9656: a vairety of different possible values, $varname should be a request
 9657: string, and the other parameters can be used to specify who and what
 9658: one is asking about.
 9659: 
 9660: Possible values for $varname are environment.lastname (or other item
 9661: from the envirnment hash), user.name (or someother aspect about the
 9662: user), resource.0.maxtries (or some other part and parameter of a
 9663: resource)
 9664: 
 9665: =item *
 9666: 
 9667: directcondval($number) : get current value of a condition; reads from a state
 9668: string
 9669: 
 9670: =item *
 9671: 
 9672: condval($condidx) : value of condition index based on state
 9673: 
 9674: =item *
 9675: 
 9676: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9677: resource's metadata, $what should be either a specific key, or either
 9678: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9679: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9680: 
 9681: this function automatically caches all requests
 9682: 
 9683: =item *
 9684: 
 9685: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9686: network of library servers; returns file handle of where SQL and regex results
 9687: will be stored for query
 9688: 
 9689: =item *
 9690: 
 9691: symbread($filename) : return symbolic list entry (filename argument optional);
 9692: returns the data handle
 9693: 
 9694: =item *
 9695: 
 9696: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9697: a possible symb for the URL in $thisfn, and if is an encryypted
 9698: resource that the user accessed using /enc/ returns a 1 on success, 0
 9699: on failure, user must be in a course, as it assumes the existance of
 9700: the course initial hash, and uses $env('request.course.id'}
 9701: 
 9702: 
 9703: =item *
 9704: 
 9705: symbclean($symb) : removes versions numbers from a symb, returns the
 9706: cleaned symb
 9707: 
 9708: =item *
 9709: 
 9710: is_on_map($uri) : checks if the $uri is somewhere on the current
 9711: course map, user must be in a course for it to work.
 9712: 
 9713: =item *
 9714: 
 9715: numval($salt) : return random seed value (addend for rndseed)
 9716: 
 9717: =item *
 9718: 
 9719: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9720: a random seed, all arguments are optional, if they aren't sent it uses the
 9721: environment to derive them. Note: if symb isn't sent and it can't get one
 9722: from &symbread it will use the current time as its return value
 9723: 
 9724: =item *
 9725: 
 9726: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9727: unfakeable, receipt
 9728: 
 9729: =item *
 9730: 
 9731: receipt() : API to ireceipt working off of env values; given out to users
 9732: 
 9733: =item *
 9734: 
 9735: countacc($url) : count the number of accesses to a given URL
 9736: 
 9737: =item *
 9738: 
 9739: 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
 9740: 
 9741: =item *
 9742: 
 9743: 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)
 9744: 
 9745: =item *
 9746: 
 9747: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9748: 
 9749: =item *
 9750: 
 9751: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9752: forcing spreadsheet to reevaluate the resource scores next time.
 9753: 
 9754: =back
 9755: 
 9756: =head2 Storing/Retreiving Data
 9757: 
 9758: =over 4
 9759: 
 9760: =item *
 9761: 
 9762: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9763: for this url; hashref needs to be given and should be a \%hashname; the
 9764: remaining args aren't required and if they aren't passed or are '' they will
 9765: be derived from the env
 9766: 
 9767: =item *
 9768: 
 9769: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9770: uses critical subroutine
 9771: 
 9772: =item *
 9773: 
 9774: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9775: all args are optional
 9776: 
 9777: =item *
 9778: 
 9779: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9780: dumps the complete (or key matching regexp) namespace into a hash
 9781: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9782: normally &store()ed into
 9783: 
 9784: $range should be either an integer '100' (give me the first 100
 9785:                                            matching records)
 9786:               or be  two integers sperated by a - with no spaces
 9787:                  '30-50' (give me the 30th through the 50th matching
 9788:                           records)
 9789: 
 9790: 
 9791: =item *
 9792: 
 9793: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9794: replaces a &store() version of data with a replacement set of data
 9795: for a particular resource in a namespace passed in the $storehash hash 
 9796: reference
 9797: 
 9798: =item *
 9799: 
 9800: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9801: works very similar to store/cstore, but all data is stored in a
 9802: temporary location and can be reset using tmpreset, $storehash should
 9803: be a hash reference, returns nothing on success
 9804: 
 9805: =item *
 9806: 
 9807: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9808: similar to restore, but all data is stored in a temporary location and
 9809: can be reset using tmpreset. Returns a hash of values on success,
 9810: error string otherwise.
 9811: 
 9812: =item *
 9813: 
 9814: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9815: deltes all keys for $symb form the temporary storage hash.
 9816: 
 9817: =item *
 9818: 
 9819: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9820: reference filled in from namesp ($udom and $uname are optional)
 9821: 
 9822: =item *
 9823: 
 9824: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9825: namesp ($udom and $uname are optional)
 9826: 
 9827: =item *
 9828: 
 9829: dump($namespace,$udom,$uname,$regexp,$range) : 
 9830: dumps the complete (or key matching regexp) namespace into a hash
 9831: ($udom, $uname, $regexp, $range are optional)
 9832: 
 9833: $range should be either an integer '100' (give me the first 100
 9834:                                            matching records)
 9835:               or be  two integers sperated by a - with no spaces
 9836:                  '30-50' (give me the 30th through the 50th matching
 9837:                           records)
 9838: =item *
 9839: 
 9840: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9841: $store can be a scalar, an array reference, or if the amount to be 
 9842: incremented is > 1, a hash reference.
 9843: 
 9844: ($udom and $uname are optional)
 9845: 
 9846: =item *
 9847: 
 9848: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9849: ($udom and $uname are optional)
 9850: 
 9851: =item *
 9852: 
 9853: cput($namespace,$storehash,$udom,$uname) : critical put
 9854: ($udom and $uname are optional)
 9855: 
 9856: =item *
 9857: 
 9858: newput($namespace,$storehash,$udom,$uname) :
 9859: 
 9860: Attempts to store the items in the $storehash, but only if they don't
 9861: currently exist, if this succeeds you can be certain that you have 
 9862: successfully created a new key value pair in the $namespace db.
 9863: 
 9864: 
 9865: Args:
 9866:  $namespace: name of database to store values to
 9867:  $storehash: hashref to store to the db
 9868:  $udom: (optional) domain of user containing the db
 9869:  $uname: (optional) name of user caontaining the db
 9870: 
 9871: Returns:
 9872:  'ok' -> succeeded in storing all keys of $storehash
 9873:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9874:                         least <key> already existed in the db (other
 9875:                         requested keys may also already exist)
 9876:  'error: <msg>' -> unable to tie the DB or other error occurred
 9877:  'con_lost' -> unable to contact request server
 9878:  'refused' -> action was not allowed by remote machine
 9879: 
 9880: 
 9881: =item *
 9882: 
 9883: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9884: reference filled in from namesp (encrypts the return communication)
 9885: ($udom and $uname are optional)
 9886: 
 9887: =item *
 9888: 
 9889: log($udom,$name,$home,$message) : write to permanent log for user; use
 9890: critical subroutine
 9891: 
 9892: =item *
 9893: 
 9894: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9895: array reference filled in from namespace found in domain level on either
 9896: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9897: 
 9898: =item *
 9899: 
 9900: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9901: domain level either on specified domain server ($uhome) or primary domain 
 9902: server ($udom and $uhome are optional)
 9903: 
 9904: =item * 
 9905: 
 9906: get_domain_defaults($target_domain) : returns hash with defaults for
 9907: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9908: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9909: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9910: Values are retrieved from cache (if current), or from domain's configuration.db
 9911: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9912: or lonTabs/domain.tab. 
 9913: 
 9914: %domdefaults = &get_auth_defaults($target_domain);
 9915: 
 9916: =back
 9917: 
 9918: =head2 Network Status Functions
 9919: 
 9920: =over 4
 9921: 
 9922: =item *
 9923: 
 9924: dirlist($uri) : return directory list based on URI
 9925: 
 9926: =item *
 9927: 
 9928: spareserver() : find server with least workload from spare.tab
 9929: 
 9930: 
 9931: =item *
 9932: 
 9933: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
 9934: if there is no corresponding loncapa host.
 9935: 
 9936: =back
 9937: 
 9938: 
 9939: =head2 Apache Request
 9940: 
 9941: =over 4
 9942: 
 9943: =item *
 9944: 
 9945: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9946: localhost, posts hash
 9947: 
 9948: =back
 9949: 
 9950: =head2 Data to String to Data
 9951: 
 9952: =over 4
 9953: 
 9954: =item *
 9955: 
 9956: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9957: and '&' separators, supports elements that are arrayrefs and hashrefs
 9958: 
 9959: =item *
 9960: 
 9961: hashref2str($hashref) : convert a hashref into a string complete with
 9962: escaping and '=' and '&' separators, supports elements that are
 9963: arrayrefs and hashrefs
 9964: 
 9965: =item *
 9966: 
 9967: arrayref2str($arrayref) : convert an arrayref into a string complete
 9968: with escaping and '&' separators, supports elements that are arrayrefs
 9969: and hashrefs
 9970: 
 9971: =item *
 9972: 
 9973: str2hash($string) : convert string to hash using unescaping and
 9974: splitting on '=' and '&', supports elements that are arrayrefs and
 9975: hashrefs
 9976: 
 9977: =item *
 9978: 
 9979: str2array($string) : convert string to hash using unescaping and
 9980: splitting on '&', supports elements that are arrayrefs and hashrefs
 9981: 
 9982: =back
 9983: 
 9984: =head2 Logging Routines
 9985: 
 9986: =over 4
 9987: 
 9988: These routines allow one to make log messages in the lonnet.log and
 9989: lonnet.perm logfiles.
 9990: 
 9991: =item *
 9992: 
 9993: logtouch() : make sure the logfile, lonnet.log, exists
 9994: 
 9995: =item *
 9996: 
 9997: logthis() : append message to the normal lonnet.log file, it gets
 9998: preiodically rolled over and deleted.
 9999: 
10000: =item *
10001: 
10002: logperm() : append a permanent message to lonnet.perm.log, this log
10003: file never gets deleted by any automated portion of the system, only
10004: messages of critical importance should go in here.
10005: 
10006: =back
10007: 
10008: =head2 General File Helper Routines
10009: 
10010: =over 4
10011: 
10012: =item *
10013: 
10014: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10015: (a) files in /uploaded
10016:   (i) If a local copy of the file exists - 
10017:       compares modification date of local copy with last-modified date for 
10018:       definitive version stored on home server for course. If local copy is 
10019:       stale, requests a new version from the home server and stores it. 
10020:       If the original has been removed from the home server, then local copy 
10021:       is unlinked.
10022:   (ii) If local copy does not exist -
10023:       requests the file from the home server and stores it. 
10024:   
10025:   If $caller is 'uploadrep':  
10026:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10027:     for request for files originally uploaded via DOCS. 
10028:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10029:   
10030:   Otherwise:
10031:      This indicates a call from the content generation phase of the request.
10032:      -  returns the entire contents of the file or -1.
10033:      
10034: (b) files in /res
10035:    - returns the entire contents of a file or -1; 
10036:    it properly subscribes to and replicates the file if neccessary.
10037: 
10038: 
10039: =item *
10040: 
10041: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10042:                   reference
10043: 
10044: returns either a stat() list of data about the file or an empty list
10045: if the file doesn't exist or couldn't find out about it (connection
10046: problems or user unknown)
10047: 
10048: =item *
10049: 
10050: filelocation($dir,$file) : returns file system location of a file
10051: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10052: directory that relative $file lookups are to looked in ($dir of /a/dir
10053: and a file of ../bob will become /a/bob)
10054: 
10055: =item *
10056: 
10057: hreflocation($dir,$file) : returns file system location or a URL; same as
10058: filelocation except for hrefs
10059: 
10060: =item *
10061: 
10062: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10063: 
10064: =back
10065: 
10066: =head2 Usererfile file routines (/uploaded*)
10067: 
10068: =over 4
10069: 
10070: =item *
10071: 
10072: userfileupload(): main rotine for putting a file in a user or course's
10073:                   filespace, arguments are,
10074: 
10075:  formname - required - this is the name of the element in $env where the
10076:            filename, and the contents of the file to create/modifed exist
10077:            the filename is in $env{'form.'.$formname.'.filename'} and the
10078:            contents of the file is located in $env{'form.'.$formname}
10079:  coursedoc - if true, store the file in the course of the active role
10080:              of the current user
10081:  subdir - required - subdirectory to put the file in under ../userfiles/
10082:          if undefined, it will be placed in "unknown"
10083: 
10084:  (This routine calls clean_filename() to remove any dangerous
10085:  characters from the filename, and then calls finuserfileupload() to
10086:  complete the transaction)
10087: 
10088:  returns either the url of the uploaded file (/uploaded/....) if successful
10089:  and /adm/notfound.html if unsuccessful
10090: 
10091: =item *
10092: 
10093: clean_filename(): routine for cleaing a filename up for storage in
10094:                  userfile space, argument is:
10095: 
10096:  filename - proposed filename
10097: 
10098: returns: the new clean filename
10099: 
10100: =item *
10101: 
10102: finishuserfileupload(): routine that creaes and sends the file to
10103: userspace, probably shouldn't be called directly
10104: 
10105:   docuname: username or courseid of destination for the file
10106:   docudom: domain of user/course of destination for the file
10107:   formname: same as for userfileupload()
10108:   fname: filename (inculding subdirectories) for the file
10109: 
10110:  returns either the url of the uploaded file (/uploaded/....) if successful
10111:  and /adm/notfound.html if unsuccessful
10112: 
10113: =item *
10114: 
10115: renameuserfile(): renames an existing userfile to a new name
10116: 
10117:   Args:
10118:    docuname: username or courseid of destination for the file
10119:    docudom: domain of user/course of destination for the file
10120:    old: current file name (including any subdirs under userfiles)
10121:    new: desired file name (including any subdirs under userfiles)
10122: 
10123: =item *
10124: 
10125: mkdiruserfile(): creates a directory is a userfiles dir
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:    dir: dir to create (including any subdirs under userfiles)
10131: 
10132: =item *
10133: 
10134: removeuserfile(): removes a file that exists in userfiles
10135: 
10136:   Args:
10137:    docuname: username or courseid of destination for the file
10138:    docudom: domain of user/course of destination for the file
10139:    fname: filname to delete (including any subdirs under userfiles)
10140: 
10141: =item *
10142: 
10143: removeuploadedurl(): convience function for removeuserfile()
10144: 
10145:   Args:
10146:    url:  a full /uploaded/... url to delete
10147: 
10148: =item * 
10149: 
10150: get_portfile_permissions():
10151:   Args:
10152:     domain: domain of user or course contain the portfolio files
10153:     user: name of user or num of course contain the portfolio files
10154:   Returns:
10155:     hashref of a dump of the proper file_permissions.db
10156:    
10157: 
10158: =item * 
10159: 
10160: get_access_controls():
10161: 
10162: Args:
10163:   current_permissions: the hash ref returned from get_portfile_permissions()
10164:   group: (optional) the group you want the files associated with
10165:   file: (optional) the file you want access info on
10166: 
10167: Returns:
10168:     a hash (keys are file names) of hashes containing
10169:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10170:         values are XML containing access control settings (see below) 
10171: 
10172: Internal notes:
10173: 
10174:  access controls are stored in file_permissions.db as key=value pairs.
10175:     key -> path to file/file_name\0uniqueID:scope_end_start
10176:         where scope -> public,guest,course,group,domains or users.
10177:               end -> UNIX time for end of access (0 -> no end date)
10178:               start -> UNIX time for start of access
10179: 
10180:     value -> XML description of access control
10181:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10182:             <start></start>
10183:             <end></end>
10184: 
10185:             <password></password>  for scope type = guest
10186: 
10187:             <domain></domain>     for scope type = course or group
10188:             <number></number>
10189:             <roles id="">
10190:              <role></role>
10191:              <access></access>
10192:              <section></section>
10193:              <group></group>
10194:             </roles>
10195: 
10196:             <dom></dom>         for scope type = domains
10197: 
10198:             <users>             for scope type = users
10199:              <user>
10200:               <uname></uname>
10201:               <udom></udom>
10202:              </user>
10203:             </users>
10204:            </scope> 
10205:               
10206:  Access data is also aggregated for each file in an additional key=value pair:
10207:  key -> path to file/file_name\0accesscontrol 
10208:  value -> reference to hash
10209:           hash contains key = value pairs
10210:           where key = uniqueID:scope_end_start
10211:                 value = UNIX time record was last updated
10212: 
10213:           Used to improve speed of look-ups of access controls for each file.  
10214:  
10215:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10216: 
10217: modify_access_controls():
10218: 
10219: Modifies access controls for a portfolio file
10220: Args
10221: 1. file name
10222: 2. reference to hash of required changes,
10223: 3. domain
10224: 4. username
10225:   where domain,username are the domain of the portfolio owner 
10226:   (either a user or a course) 
10227: 
10228: Returns:
10229: 1. result of additions or updates ('ok' or 'error', with error message). 
10230: 2. result of deletions ('ok' or 'error', with error message).
10231: 3. reference to hash of any new or updated access controls.
10232: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10233:    key = integer (inbound ID)
10234:    value = uniqueID  
10235: 
10236: =back
10237: 
10238: =head2 HTTP Helper Routines
10239: 
10240: =over 4
10241: 
10242: =item *
10243: 
10244: escape() : unpack non-word characters into CGI-compatible hex codes
10245: 
10246: =item *
10247: 
10248: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10249: 
10250: =back
10251: 
10252: =head1 PRIVATE SUBROUTINES
10253: 
10254: =head2 Underlying communication routines (Shouldn't call)
10255: 
10256: =over 4
10257: 
10258: =item *
10259: 
10260: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10261: 
10262: =item *
10263: 
10264: reply() : uses subreply to send a message to remote machine, logs all failures
10265: 
10266: =item *
10267: 
10268: critical() : passes a critical message to another server; if cannot
10269: get through then place message in connection buffer directory and
10270: returns con_delayed, if incapable of saving message, returns
10271: con_failed
10272: 
10273: =item *
10274: 
10275: reconlonc() : tries to reconnect lonc client processes.
10276: 
10277: =back
10278: 
10279: =head2 Resource Access Logging
10280: 
10281: =over 4
10282: 
10283: =item *
10284: 
10285: flushcourselogs() : flush (save) buffer logs and access logs
10286: 
10287: =item *
10288: 
10289: courselog($what) : save message for course in hash
10290: 
10291: =item *
10292: 
10293: courseacclog($what) : save message for course using &courselog().  Perform
10294: special processing for specific resource types (problems, exams, quizzes, etc).
10295: 
10296: =item *
10297: 
10298: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10299: as a PerlChildExitHandler
10300: 
10301: =back
10302: 
10303: =head2 Other
10304: 
10305: =over 4
10306: 
10307: =item *
10308: 
10309: symblist($mapname,%newhash) : update symbolic storage links
10310: 
10311: =back
10312: 
10313: =cut
10314: 

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