File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.873: download - view: text, annotated - select for diffs
Fri May 11 01:48:19 2007 UTC (17 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 5134. If the course owner was not an existing user and needed to be added as a new user, this would fail for a user with auth type = localauth because no homeserver existed for the course for lonnet::auto_create_password().
- now pass an extra argument (domain of new user) and contact primary domain server for this domain to access localauth password cretion in localenroll.pm
- extra logging in Enrollment.pm to log case where authchk fails for localauth case
- batchcreatecourse.pm now checks whether a valid courseID was returned for the new course.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.873 2007/05/11 01:48:19 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: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Date;
   35: # use Date::Parse;
   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   37:             $_64bit %env);
   38: 
   39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   42:     %courseownerbuf, %coursetypebuf);
   43: 
   44: use IO::Socket;
   45: use GDBM_File;
   46: use HTML::LCParser;
   47: use Fcntl qw(:flock);
   48: use Storable qw(thaw nfreeze);
   49: use Time::HiRes qw( gettimeofday tv_interval );
   50: use Cache::Memcached;
   51: use Digest::MD5;
   52: use Math::Random;
   53: use LONCAPA qw(:DEFAULT :match);
   54: use LONCAPA::Configuration;
   55: 
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: {
   89:     my $logid;
   90:     sub instructor_log {
   91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   92: 	$logid++;
   93: 	my $id=time().'00000'.$$.'00000'.$logid;
   94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   95: 				    { $id => {
   96: 					'exe_uname' => $env{'user.name'},
   97: 					'exe_udom'  => $env{'user.domain'},
   98: 					'exe_time'  => time(),
   99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  100: 					'delflag'   => $delflag,
  101: 					'logentry'  => $storehash,
  102: 					'uname'     => $uname,
  103: 					'udom'      => $udom,
  104: 				    }
  105: 				  },
  106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  108: 				    );
  109:     }
  110: }
  111: 
  112: sub logtouch {
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     unless (-e "$execdir/logs/lonnet.log") {	
  115: 	open(my $fh,">>$execdir/logs/lonnet.log");
  116: 	close $fh;
  117:     }
  118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  120: }
  121: 
  122: sub logthis {
  123:     my $message=shift;
  124:     my $execdir=$perlvar{'lonDaemons'};
  125:     my $now=time;
  126:     my $local=localtime($now);
  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  128: 	print $fh "$local ($$): $message\n";
  129: 	close($fh);
  130:     }
  131:     return 1;
  132: }
  133: 
  134: sub logperm {
  135:     my $message=shift;
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     my $now=time;
  138:     my $local=localtime($now);
  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  140: 	print $fh "$now:$message:$local\n";
  141: 	close($fh);
  142:     }
  143:     return 1;
  144: }
  145: 
  146: sub create_connection {
  147:     my ($hostname,$lonid) = @_;
  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  149: 				     Type    => SOCK_STREAM,
  150: 				     Timeout => 10);
  151:     return 0 if (!$client);
  152:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
  153:     my $result = <$client>;
  154:     chomp($result);
  155:     return 1 if ($result eq 'done');
  156:     return 0;
  157: }
  158: 
  159: 
  160: # -------------------------------------------------- Non-critical communication
  161: sub subreply {
  162:     my ($cmd,$server)=@_;
  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  164:     #
  165:     #  With loncnew process trimming, there's a timing hole between lonc server
  166:     #  process exit and the master server picking up the listen on the AF_UNIX
  167:     #  socket.  In that time interval, a lock file will exist:
  168: 
  169:     my $lockfile=$peerfile.".lock";
  170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  171: 	sleep(1);
  172:     }
  173:     # At this point, either a loncnew parent is listening or an old lonc
  174:     # or loncnew child is listening so we can connect or everything's dead.
  175:     #
  176:     #   We'll give the connection a few tries before abandoning it.  If
  177:     #   connection is not possible, we'll con_lost back to the client.
  178:     #   
  179:     my $client;
  180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  182: 				      Type    => SOCK_STREAM,
  183: 				      Timeout => 10);
  184: 	if ($client) {
  185: 	    last;		# Connected!
  186: 	} else {
  187: 	    &create_connection(&hostname($server),$server);
  188: 	}
  189:         sleep(1);		# Try again later if failed connection.
  190:     }
  191:     my $answer;
  192:     if ($client) {
  193: 	print $client "sethost:$server:$cmd\n";
  194: 	$answer=<$client>;
  195: 	if (!$answer) { $answer="con_lost"; }
  196: 	chomp($answer);
  197:     } else {
  198: 	$answer = 'con_lost';	# Failed connection.
  199:     }
  200:     return $answer;
  201: }
  202: 
  203: sub reply {
  204:     my ($cmd,$server)=@_;
  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  206:     my $answer=subreply($cmd,$server);
  207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  208:        &logthis("<font color=\"blue\">WARNING:".
  209:                 " $cmd to $server returned $answer</font>");
  210:     }
  211:     return $answer;
  212: }
  213: 
  214: # ----------------------------------------------------------- Send USR1 to lonc
  215: 
  216: sub reconlonc {
  217:     &logthis("Trying to reconnect lonc");
  218:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  219:     if (open(my $fh,"<$loncfile")) {
  220: 	my $loncpid=<$fh>;
  221:         chomp($loncpid);
  222:         if (kill 0 => $loncpid) {
  223: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  224:             kill USR1 => $loncpid;
  225:             sleep 1;
  226:          } else {
  227: 	    &logthis(
  228:                "<font color=\"blue\">WARNING:".
  229:                " lonc at pid $loncpid not responding, giving up</font>");
  230:         }
  231:     } else {
  232: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  233:     }
  234: }
  235: 
  236: # ------------------------------------------------------ Critical communication
  237: 
  238: sub critical {
  239:     my ($cmd,$server)=@_;
  240:     unless (&hostname($server)) {
  241:         &logthis("<font color=\"blue\">WARNING:".
  242:                " Critical message to unknown server ($server)</font>");
  243:         return 'no_such_host';
  244:     }
  245:     my $answer=reply($cmd,$server);
  246:     if ($answer eq 'con_lost') {
  247: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  248: 	my $answer=reply($cmd,$server);
  249:         if ($answer eq 'con_lost') {
  250:             my $now=time;
  251:             my $middlename=$cmd;
  252:             $middlename=substr($middlename,0,16);
  253:             $middlename=~s/\W//g;
  254:             my $dfilename=
  255:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  256:             $dumpcount++;
  257:             {
  258: 		my $dfh;
  259: 		if (open($dfh,">$dfilename")) {
  260: 		    print $dfh "$cmd\n"; 
  261: 		    close($dfh);
  262: 		}
  263:             }
  264:             sleep 2;
  265:             my $wcmd='';
  266:             {
  267: 		my $dfh;
  268: 		if (open($dfh,"<$dfilename")) {
  269: 		    $wcmd=<$dfh>; 
  270: 		    close($dfh);
  271: 		}
  272:             }
  273:             chomp($wcmd);
  274:             if ($wcmd eq $cmd) {
  275: 		&logthis("<font color=\"blue\">WARNING: ".
  276:                          "Connection buffer $dfilename: $cmd</font>");
  277:                 &logperm("D:$server:$cmd");
  278: 	        return 'con_delayed';
  279:             } else {
  280:                 &logthis("<font color=\"red\">CRITICAL:"
  281:                         ." Critical connection failed: $server $cmd</font>");
  282:                 &logperm("F:$server:$cmd");
  283:                 return 'con_failed';
  284:             }
  285:         }
  286:     }
  287:     return $answer;
  288: }
  289: 
  290: # ------------------------------------------- check if return value is an error
  291: 
  292: sub error {
  293:     my ($result) = @_;
  294:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  295: 	if ($2 == 2) { return undef; }
  296: 	return $1;
  297:     }
  298:     return undef;
  299: }
  300: 
  301: sub convert_and_load_session_env {
  302:     my ($lonidsdir,$handle)=@_;
  303:     my @profile;
  304:     {
  305: 	open(my $idf,"$lonidsdir/$handle.id");
  306: 	flock($idf,LOCK_SH);
  307: 	@profile=<$idf>;
  308: 	close($idf);
  309:     }
  310:     my %temp_env;
  311:     foreach my $line (@profile) {
  312: 	if ($line !~ m/=/) {
  313: 	    return 0;
  314: 	}
  315: 	chomp($line);
  316: 	my ($envname,$envvalue)=split(/=/,$line,2);
  317: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  318:     }
  319:     unlink("$lonidsdir/$handle.id");
  320:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  321: 	    0640)) {
  322: 	%disk_env = %temp_env;
  323: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  324: 	untie(%disk_env);
  325:     }
  326:     return 1;
  327: }
  328: 
  329: # ------------------------------------------- Transfer profile into environment
  330: my $env_loaded;
  331: sub transfer_profile_to_env {
  332:     my ($lonidsdir,$handle,$force_transfer) = @_;
  333:     if (!$force_transfer && $env_loaded) { return; } 
  334: 
  335:     if (!defined($lonidsdir)) {
  336: 	$lonidsdir = $perlvar{'lonIDsDir'};
  337:     }
  338:     if (!defined($handle)) {
  339:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  340:     }
  341: 
  342:     my $convert;
  343:     {
  344:     	open(my $idf,"$lonidsdir/$handle.id");
  345: 	flock($idf,LOCK_SH);
  346: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  347: 		&GDBM_READER(),0640)) {
  348: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  349: 	    untie(%disk_env);
  350: 	} else {
  351: 	    $convert = 1;
  352: 	}
  353:     }
  354:     if ($convert) {
  355: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  356: 	    &logthis("Failed to load session, or convert session.");
  357: 	}
  358:     }
  359: 
  360:     my %remove;
  361:     while ( my $envname = each(%env) ) {
  362:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  363:             if ($time < time-300) {
  364:                 $remove{$key}++;
  365:             }
  366:         }
  367:     }
  368: 
  369:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  370:     $env_loaded=1;
  371:     foreach my $expired_key (keys(%remove)) {
  372:         &delenv($expired_key);
  373:     }
  374: }
  375: 
  376: sub timed_flock {
  377:     my ($file,$lock_type) = @_;
  378:     my $failed=0;
  379:     eval {
  380: 	local $SIG{__DIE__}='DEFAULT';
  381: 	local $SIG{ALRM}=sub {
  382: 	    $failed=1;
  383: 	    die("failed lock");
  384: 	};
  385: 	alarm(13);
  386: 	flock($file,$lock_type);
  387: 	alarm(0);
  388:     };
  389:     if ($failed) {
  390: 	return undef;
  391:     } else {
  392: 	return 1;
  393:     }
  394: }
  395: 
  396: # ---------------------------------------------------------- Append Environment
  397: 
  398: sub appenv {
  399:     my %newenv=@_;
  400:     foreach my $key (keys(%newenv)) {
  401: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  402:             &logthis("<font color=\"blue\">WARNING: ".
  403:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  404:                 .'</font>');
  405: 	    delete($newenv{$key});
  406:         } else {
  407:             $env{$key}=$newenv{$key};
  408:         }
  409:     }
  410:     open(my $env_file,$env{'user.environment'});
  411:     if (&timed_flock($env_file,LOCK_EX)
  412: 	&&
  413: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  414: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  415: 	while (my ($key,$value) = each(%newenv)) {
  416: 	    $disk_env{$key} = $value;
  417: 	}
  418: 	untie(%disk_env);
  419:     }
  420:     return 'ok';
  421: }
  422: # ----------------------------------------------------- Delete from Environment
  423: 
  424: sub delenv {
  425:     my $delthis=shift;
  426:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  427:         &logthis("<font color=\"blue\">WARNING: ".
  428:                 "Attempt to delete from environment ".$delthis);
  429:         return 'error';
  430:     }
  431:     open(my $env_file,$env{'user.environment'});
  432:     if (&timed_flock($env_file,LOCK_EX)
  433: 	&&
  434: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  435: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  436: 	foreach my $key (keys(%disk_env)) {
  437: 	    if ($key=~/^$delthis/) { 
  438:                 delete($env{$key});
  439:                 delete($disk_env{$key});
  440:             }
  441: 	}
  442: 	untie(%disk_env);
  443:     }
  444:     return 'ok';
  445: }
  446: 
  447: sub get_env_multiple {
  448:     my ($name) = @_;
  449:     my @values;
  450:     if (defined($env{$name})) {
  451:         # exists is it an array
  452:         if (ref($env{$name})) {
  453:             @values=@{ $env{$name} };
  454:         } else {
  455:             $values[0]=$env{$name};
  456:         }
  457:     }
  458:     return(@values);
  459: }
  460: 
  461: # ------------------------------------------ Find out current server userload
  462: # there is a copy in lond
  463: sub userload {
  464:     my $numusers=0;
  465:     {
  466: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  467: 	my $filename;
  468: 	my $curtime=time;
  469: 	while ($filename=readdir(LONIDS)) {
  470: 	    if ($filename eq '.' || $filename eq '..') {next;}
  471: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  472: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  473: 	}
  474: 	closedir(LONIDS);
  475:     }
  476:     my $userloadpercent=0;
  477:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  478:     if ($maxuserload) {
  479: 	$userloadpercent=100*$numusers/$maxuserload;
  480:     }
  481:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  482:     return $userloadpercent;
  483: }
  484: 
  485: # ------------------------------------------ Fight off request when overloaded
  486: 
  487: sub overloaderror {
  488:     my ($r,$checkserver)=@_;
  489:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  490:     my $loadavg;
  491:     if ($checkserver eq $perlvar{'lonHostID'}) {
  492:        open(my $loadfile,'/proc/loadavg');
  493:        $loadavg=<$loadfile>;
  494:        $loadavg =~ s/\s.*//g;
  495:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  496:        close($loadfile);
  497:     } else {
  498:        $loadavg=&reply('load',$checkserver);
  499:     }
  500:     my $overload=$loadavg-100;
  501:     if ($overload>0) {
  502: 	$r->err_headers_out->{'Retry-After'}=$overload;
  503:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  504:         return 413;
  505:     }    
  506:     return '';
  507: }
  508: 
  509: # ------------------------------ Find server with least workload from spare.tab
  510: 
  511: sub spareserver {
  512:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  513:     my $spare_server;
  514:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  515:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  516:                                                      :  $userloadpercent;
  517:     
  518:     foreach my $try_server (@{ $spareid{'primary'} }) {
  519: 	($spare_server, $lowest_load) =
  520: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  521:     }
  522: 
  523:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  524: 
  525:     if (!$found_server) {
  526: 	foreach my $try_server (@{ $spareid{'default'} }) {
  527: 	    ($spare_server, $lowest_load) =
  528: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  529: 	}
  530:     }
  531: 
  532:     if (!$want_server_name) {
  533: 	$spare_server="http://".&hostname($spare_server);
  534:     }
  535:     return $spare_server;
  536: }
  537: 
  538: sub compare_server_load {
  539:     my ($try_server, $spare_server, $lowest_load) = @_;
  540: 
  541:     my $loadans     = &reply('load',    $try_server);
  542:     my $userloadans = &reply('userload',$try_server);
  543: 
  544:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  545: 	next; #didn't get a number from the server
  546:     }
  547: 
  548:     my $load;
  549:     if ($loadans =~ /\d/) {
  550: 	if ($userloadans =~ /\d/) {
  551: 	    #both are numbers, pick the bigger one
  552: 	    $load = ($loadans > $userloadans) ? $loadans 
  553: 		                              : $userloadans;
  554: 	} else {
  555: 	    $load = $loadans;
  556: 	}
  557:     } else {
  558: 	$load = $userloadans;
  559:     }
  560: 
  561:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  562: 	$spare_server = $try_server;
  563: 	$lowest_load  = $load;
  564:     }
  565:     return ($spare_server,$lowest_load);
  566: }
  567: # --------------------------------------------- Try to change a user's password
  568: 
  569: sub changepass {
  570:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  571:     $currentpass = &escape($currentpass);
  572:     $newpass     = &escape($newpass);
  573:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  574: 		       $server);
  575:     if (! $answer) {
  576: 	&logthis("No reply on password change request to $server ".
  577: 		 "by $uname in domain $udom.");
  578:     } elsif ($answer =~ "^ok") {
  579:         &logthis("$uname in $udom successfully changed their password ".
  580: 		 "on $server.");
  581:     } elsif ($answer =~ "^pwchange_failure") {
  582: 	&logthis("$uname in $udom was unable to change their password ".
  583: 		 "on $server.  The action was blocked by either lcpasswd ".
  584: 		 "or pwchange");
  585:     } elsif ($answer =~ "^non_authorized") {
  586:         &logthis("$uname in $udom did not get their password correct when ".
  587: 		 "attempting to change it on $server.");
  588:     } elsif ($answer =~ "^auth_mode_error") {
  589:         &logthis("$uname in $udom attempted to change their password despite ".
  590: 		 "not being locally or internally authenticated on $server.");
  591:     } elsif ($answer =~ "^unknown_user") {
  592:         &logthis("$uname in $udom attempted to change their password ".
  593: 		 "on $server but were unable to because $server is not ".
  594: 		 "their home server.");
  595:     } elsif ($answer =~ "^refused") {
  596: 	&logthis("$server refused to change $uname in $udom password because ".
  597: 		 "it was sent an unencrypted request to change the password.");
  598:     }
  599:     return $answer;
  600: }
  601: 
  602: # ----------------------- Try to determine user's current authentication scheme
  603: 
  604: sub queryauthenticate {
  605:     my ($uname,$udom)=@_;
  606:     my $uhome=&homeserver($uname,$udom);
  607:     if (!$uhome) {
  608: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  609: 	return 'no_host';
  610:     }
  611:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  612:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  613: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  614:     }
  615:     return $answer;
  616: }
  617: 
  618: # --------- Try to authenticate user from domain's lib servers (first this one)
  619: 
  620: sub authenticate {
  621:     my ($uname,$upass,$udom)=@_;
  622:     $upass=&escape($upass);
  623:     $uname= &LONCAPA::clean_username($uname);
  624:     my $uhome=&homeserver($uname,$udom,1);
  625:     if ((!$uhome) || ($uhome eq 'no_host')) {
  626: # Maybe the machine was offline and only re-appeared again recently?
  627:         &reconlonc();
  628: # One more
  629: 	my $uhome=&homeserver($uname,$udom,1);
  630: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  631: 	    &logthis("User $uname at $udom is unknown in authenticate");
  632: 	}
  633: 	return 'no_host';
  634:     }
  635:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  636:     if ($answer eq 'authorized') {
  637: 	&logthis("User $uname at $udom authorized by $uhome"); 
  638: 	return $uhome; 
  639:     }
  640:     if ($answer eq 'non_authorized') {
  641: 	&logthis("User $uname at $udom rejected by $uhome");
  642: 	return 'no_host'; 
  643:     }
  644:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  645:     return 'no_host';
  646: }
  647: 
  648: # ---------------------- Find the homebase for a user from domain's lib servers
  649: 
  650: my %homecache;
  651: sub homeserver {
  652:     my ($uname,$udom,$ignoreBadCache)=@_;
  653:     my $index="$uname:$udom";
  654: 
  655:     if (exists($homecache{$index})) { return $homecache{$index}; }
  656: 
  657:     my %servers = &get_servers($udom,'library');
  658:     foreach my $tryserver (keys(%servers)) {
  659:         next if ($ignoreBadCache ne 'true' && 
  660: 		 exists($badServerCache{$tryserver}));
  661: 
  662: 	my $answer=reply("home:$udom:$uname",$tryserver);
  663: 	if ($answer eq 'found') {
  664: 	    delete($badServerCache{$tryserver}); 
  665: 	    return $homecache{$index}=$tryserver;
  666: 	} elsif ($answer eq 'no_host') {
  667: 	    $badServerCache{$tryserver}=1;
  668: 	}
  669:     }    
  670:     return 'no_host';
  671: }
  672: 
  673: # ------------------------------------- Find the usernames behind a list of IDs
  674: 
  675: sub idget {
  676:     my ($udom,@ids)=@_;
  677:     my %returnhash=();
  678:     
  679:     my %servers = &get_servers($udom,'library');
  680:     foreach my $tryserver (keys(%servers)) {
  681: 	my $idlist=join('&',@ids);
  682: 	$idlist=~tr/A-Z/a-z/; 
  683: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  684: 	my @answer=();
  685: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  686: 	    @answer=split(/\&/,$reply);
  687: 	}                    ;
  688: 	my $i;
  689: 	for ($i=0;$i<=$#ids;$i++) {
  690: 	    if ($answer[$i]) {
  691: 		$returnhash{$ids[$i]}=$answer[$i];
  692: 	    } 
  693: 	}
  694:     } 
  695:     return %returnhash;
  696: }
  697: 
  698: # ------------------------------------- Find the IDs behind a list of usernames
  699: 
  700: sub idrget {
  701:     my ($udom,@unames)=@_;
  702:     my %returnhash=();
  703:     foreach my $uname (@unames) {
  704:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  705:     }
  706:     return %returnhash;
  707: }
  708: 
  709: # ------------------------------- Store away a list of names and associated IDs
  710: 
  711: sub idput {
  712:     my ($udom,%ids)=@_;
  713:     my %servers=();
  714:     foreach my $uname (keys(%ids)) {
  715: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  716:         my $uhom=&homeserver($uname,$udom);
  717:         if ($uhom ne 'no_host') {
  718:             my $id=&escape($ids{$uname});
  719:             $id=~tr/A-Z/a-z/;
  720:             my $esc_unam=&escape($uname);
  721: 	    if ($servers{$uhom}) {
  722: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  723:             } else {
  724:                 $servers{$uhom}=$id.'='.$esc_unam;
  725:             }
  726:         }
  727:     }
  728:     foreach my $server (keys(%servers)) {
  729:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  730:     }
  731: }
  732: 
  733: # ------------------------------------------- get items from domain db files   
  734: 
  735: sub get_dom {
  736:     my ($namespace,$storearr,$udom,$uhome)=@_;
  737:     my $items='';
  738:     foreach my $item (@$storearr) {
  739:         $items.=&escape($item).'&';
  740:     }
  741:     $items=~s/\&$//;
  742:     if (!$udom) {
  743:         $udom=$env{'user.domain'};
  744:         if (defined(&domain($udom,'primary'))) {
  745:             $uhome=&domain($udom,'primary');
  746:         } else {
  747:             $uhome eq '';
  748:         }
  749:     } else {
  750:         if (!$uhome) {
  751:             if (defined(&domain($udom,'primary'))) {
  752:                 $uhome=&domain($udom,'primary');
  753:             }
  754:         }
  755:     }
  756:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  757:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  758:         my %returnhash;
  759:         if ($rep =~ /^error: 2 /) {
  760:             return %returnhash;
  761:         }
  762:         my @pairs=split(/\&/,$rep);
  763:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  764:             return @pairs;
  765:         }
  766:         my %returnhash=();
  767:         my $i=0;
  768:         foreach my $item (@$storearr) {
  769:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  770:             $i++;
  771:         }
  772:         return %returnhash;
  773:     } else {
  774:         &logthis("get_dom failed - no homeserver and/or domain");
  775:     }
  776: }
  777: 
  778: # -------------------------------------------- put items in domain db files 
  779: 
  780: sub put_dom {
  781:     my ($namespace,$storehash,$udom,$uhome)=@_;
  782:     if (!$udom) {
  783:         $udom=$env{'user.domain'};
  784:         if (defined(&domain($udom,'primary'))) {
  785:             $uhome=&domain($udom,'primary');
  786:         } else {
  787:             $uhome eq '';
  788:         }
  789:     } else {
  790:         if (!$uhome) {
  791:             if (defined(&domain($udom,'primary'))) {
  792:                 $uhome=&domain($udom,'primary');
  793:             }
  794:         }
  795:     } 
  796:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  797:         my $items='';
  798:         foreach my $item (keys(%$storehash)) {
  799:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  800:         }
  801:         $items=~s/\&$//;
  802:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  803:     } else {
  804:         &logthis("put_dom failed - no homeserver and/or domain");
  805:     }
  806: }
  807: 
  808: sub retrieve_inst_usertypes {
  809:     my ($udom) = @_;
  810:     my (%returnhash,@order);
  811:     if (defined(&domain($udom,'primary'))) {
  812:         my $uhome=&domain($udom,'primary');
  813:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  814:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  815:         my @pairs=split(/\&/,$hashitems);
  816:         foreach my $item (@pairs) {
  817:             my ($key,$value)=split(/=/,$item,2);
  818:             $key = &unescape($key);
  819:             next if ($key =~ /^error: 2 /);
  820:             $returnhash{$key}=&thaw_unescape($value);
  821:         }
  822:         my @esc_order = split(/\&/,$orderitems);
  823:         foreach my $item (@esc_order) {
  824:             push(@order,&unescape($item));
  825:         }
  826:     } else {
  827:         &logthis("get_dom failed - no primary domain server for $udom");
  828:     }
  829:     return (\%returnhash,\@order);
  830: }
  831: 
  832: sub is_domainimage {
  833:     my ($url) = @_;
  834:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  835:         if (&domain($1) ne '') {
  836:             return '1';
  837:         }
  838:     }
  839:     return;
  840: }
  841: 
  842: # --------------------------------------------------- Assign a key to a student
  843: 
  844: sub assign_access_key {
  845: #
  846: # a valid key looks like uname:udom#comments
  847: # comments are being appended
  848: #
  849:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  850:     $kdom=
  851:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  852:     $knum=
  853:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  854:     $cdom=
  855:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  856:     $cnum=
  857:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  858:     $udom=$env{'user.name'} unless (defined($udom));
  859:     $uname=$env{'user.domain'} unless (defined($uname));
  860:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  861:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  862:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  863:                                                   # assigned to this person
  864:                                                   # - this should not happen,
  865:                                                   # unless something went wrong
  866:                                                   # the first time around
  867: # ready to assign
  868:         $logentry=$1.'; '.$logentry;
  869:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  870:                                                  $kdom,$knum) eq 'ok') {
  871: # key now belongs to user
  872: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  873:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  874:                 &appenv('environment.'.$envkey => $ckey);
  875:                 return 'ok';
  876:             } else {
  877:                 return 
  878:   'error: Count not permanently assign key, will need to be re-entered later.';
  879: 	    }
  880:         } else {
  881:             return 'error: Could not assign key, try again later.';
  882:         }
  883:     } elsif (!$existing{$ckey}) {
  884: # the key does not exist
  885: 	return 'error: The key does not exist';
  886:     } else {
  887: # the key is somebody else's
  888: 	return 'error: The key is already in use';
  889:     }
  890: }
  891: 
  892: # ------------------------------------------ put an additional comment on a key
  893: 
  894: sub comment_access_key {
  895: #
  896: # a valid key looks like uname:udom#comments
  897: # comments are being appended
  898: #
  899:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  900:     $cdom=
  901:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  902:     $cnum=
  903:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  904:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  905:     if ($existing{$ckey}) {
  906:         $existing{$ckey}.='; '.$logentry;
  907: # ready to assign
  908:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  909:                                                  $cdom,$cnum) eq 'ok') {
  910: 	    return 'ok';
  911:         } else {
  912: 	    return 'error: Count not store comment.';
  913:         }
  914:     } else {
  915: # the key does not exist
  916: 	return 'error: The key does not exist';
  917:     }
  918: }
  919: 
  920: # ------------------------------------------------------ Generate a set of keys
  921: 
  922: sub generate_access_keys {
  923:     my ($number,$cdom,$cnum,$logentry)=@_;
  924:     $cdom=
  925:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  926:     $cnum=
  927:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  928:     unless (&allowed('mky',$cdom)) { return 0; }
  929:     unless (($cdom) && ($cnum)) { return 0; }
  930:     if ($number>10000) { return 0; }
  931:     sleep(2); # make sure don't get same seed twice
  932:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  933:     my $total=0;
  934:     for (my $i=1;$i<=$number;$i++) {
  935:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  936:                   sprintf("%lx",int(100000*rand)).'-'.
  937:                   sprintf("%lx",int(100000*rand));
  938:        $newkey=~s/1/g/g; # folks mix up 1 and l
  939:        $newkey=~s/0/h/g; # and also 0 and O
  940:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  941:        if ($existing{$newkey}) {
  942:            $i--;
  943:        } else {
  944: 	  if (&put('accesskeys',
  945:               { $newkey => '# generated '.localtime().
  946:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  947:                            '; '.$logentry },
  948: 		   $cdom,$cnum) eq 'ok') {
  949:               $total++;
  950: 	  }
  951:        }
  952:     }
  953:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  954:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  955:     return $total;
  956: }
  957: 
  958: # ------------------------------------------------------- Validate an accesskey
  959: 
  960: sub validate_access_key {
  961:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  962:     $cdom=
  963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  964:     $cnum=
  965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  966:     $udom=$env{'user.domain'} unless (defined($udom));
  967:     $uname=$env{'user.name'} unless (defined($uname));
  968:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  969:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  970: }
  971: 
  972: # ------------------------------------- Find the section of student in a course
  973: sub devalidate_getsection_cache {
  974:     my ($udom,$unam,$courseid)=@_;
  975:     my $hashid="$udom:$unam:$courseid";
  976:     &devalidate_cache_new('getsection',$hashid);
  977: }
  978: 
  979: sub courseid_to_courseurl {
  980:     my ($courseid) = @_;
  981:     #already url style courseid
  982:     return $courseid if ($courseid =~ m{^/});
  983: 
  984:     if (exists($env{'course.'.$courseid.'.num'})) {
  985: 	my $cnum = $env{'course.'.$courseid.'.num'};
  986: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  987: 	return "/$cdom/$cnum";
  988:     }
  989: 
  990:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  991:     if (exists($courseinfo{'num'})) {
  992: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  993:     }
  994: 
  995:     return undef;
  996: }
  997: 
  998: sub getsection {
  999:     my ($udom,$unam,$courseid)=@_;
 1000:     my $cachetime=1800;
 1001: 
 1002:     my $hashid="$udom:$unam:$courseid";
 1003:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1004:     if (defined($cached)) { return $result; }
 1005: 
 1006:     my %Pending; 
 1007:     my %Expired;
 1008:     #
 1009:     # Each role can either have not started yet (pending), be active, 
 1010:     #    or have expired.
 1011:     #
 1012:     # If there is an active role, we are done.
 1013:     #
 1014:     # If there is more than one role which has not started yet, 
 1015:     #     choose the one which will start sooner
 1016:     # If there is one role which has not started yet, return it.
 1017:     #
 1018:     # If there is more than one expired role, choose the one which ended last.
 1019:     # If there is a role which has expired, return it.
 1020:     #
 1021:     $courseid = &courseid_to_courseurl($courseid);
 1022:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1023:     foreach my $key (keys(%roleshash)) {
 1024:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1025:         my $section=$1;
 1026:         if ($key eq $courseid.'_st') { $section=''; }
 1027:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1028:         my $now=time;
 1029:         if (defined($end) && $end && ($now > $end)) {
 1030:             $Expired{$end}=$section;
 1031:             next;
 1032:         }
 1033:         if (defined($start) && $start && ($now < $start)) {
 1034:             $Pending{$start}=$section;
 1035:             next;
 1036:         }
 1037:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1038:     }
 1039:     #
 1040:     # Presumedly there will be few matching roles from the above
 1041:     # loop and the sorting time will be negligible.
 1042:     if (scalar(keys(%Pending))) {
 1043:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1044:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1045:     } 
 1046:     if (scalar(keys(%Expired))) {
 1047:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1048:         my $time = pop(@sorted);
 1049:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1050:     }
 1051:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1052: }
 1053: 
 1054: sub save_cache {
 1055:     &purge_remembered();
 1056:     #&Apache::loncommon::validate_page();
 1057:     undef(%env);
 1058:     undef($env_loaded);
 1059: }
 1060: 
 1061: my $to_remember=-1;
 1062: my %remembered;
 1063: my %accessed;
 1064: my $kicks=0;
 1065: my $hits=0;
 1066: sub make_key {
 1067:     my ($name,$id) = @_;
 1068:     if (length($id) > 65 
 1069: 	&& length(&escape($id)) > 200) {
 1070: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1071:     }
 1072:     return &escape($name.':'.$id);
 1073: }
 1074: 
 1075: sub devalidate_cache_new {
 1076:     my ($name,$id,$debug) = @_;
 1077:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1078:     $id=&make_key($name,$id);
 1079:     $memcache->delete($id);
 1080:     delete($remembered{$id});
 1081:     delete($accessed{$id});
 1082: }
 1083: 
 1084: sub is_cached_new {
 1085:     my ($name,$id,$debug) = @_;
 1086:     $id=&make_key($name,$id);
 1087:     if (exists($remembered{$id})) {
 1088: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1089: 	$accessed{$id}=[&gettimeofday()];
 1090: 	$hits++;
 1091: 	return ($remembered{$id},1);
 1092:     }
 1093:     my $value = $memcache->get($id);
 1094:     if (!(defined($value))) {
 1095: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1096: 	return (undef,undef);
 1097:     }
 1098:     if ($value eq '__undef__') {
 1099: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1100: 	$value=undef;
 1101:     }
 1102:     &make_room($id,$value,$debug);
 1103:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1104:     return ($value,1);
 1105: }
 1106: 
 1107: sub do_cache_new {
 1108:     my ($name,$id,$value,$time,$debug) = @_;
 1109:     $id=&make_key($name,$id);
 1110:     my $setvalue=$value;
 1111:     if (!defined($setvalue)) {
 1112: 	$setvalue='__undef__';
 1113:     }
 1114:     if (!defined($time) ) {
 1115: 	$time=600;
 1116:     }
 1117:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1118:     if (!($memcache->set($id,$setvalue,$time))) {
 1119: 	&logthis("caching of id -> $id  failed");
 1120:     }
 1121:     # need to make a copy of $value
 1122:     #&make_room($id,$value,$debug);
 1123:     return $value;
 1124: }
 1125: 
 1126: sub make_room {
 1127:     my ($id,$value,$debug)=@_;
 1128:     $remembered{$id}=$value;
 1129:     if ($to_remember<0) { return; }
 1130:     $accessed{$id}=[&gettimeofday()];
 1131:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1132:     my $to_kick;
 1133:     my $max_time=0;
 1134:     foreach my $other (keys(%accessed)) {
 1135: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1136: 	    $to_kick=$other;
 1137: 	    $max_time=&tv_interval($accessed{$other});
 1138: 	}
 1139:     }
 1140:     delete($remembered{$to_kick});
 1141:     delete($accessed{$to_kick});
 1142:     $kicks++;
 1143:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1144:     return;
 1145: }
 1146: 
 1147: sub purge_remembered {
 1148:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1149:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1150:     undef(%remembered);
 1151:     undef(%accessed);
 1152: }
 1153: # ------------------------------------- Read an entry from a user's environment
 1154: 
 1155: sub userenvironment {
 1156:     my ($udom,$unam,@what)=@_;
 1157:     my %returnhash=();
 1158:     my @answer=split(/\&/,
 1159:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1160:                       &homeserver($unam,$udom)));
 1161:     my $i;
 1162:     for ($i=0;$i<=$#what;$i++) {
 1163: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1164:     }
 1165:     return %returnhash;
 1166: }
 1167: 
 1168: # ---------------------------------------------------------- Get a studentphoto
 1169: sub studentphoto {
 1170:     my ($udom,$unam,$ext) = @_;
 1171:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1172:     if (defined($env{'request.course.id'})) {
 1173:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1174:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1175:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1176:             } else {
 1177:                 my ($result,$perm_reqd)=
 1178: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1179:                 if ($result eq 'ok') {
 1180:                     if (!($perm_reqd eq 'yes')) {
 1181:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1182:                     }
 1183:                 }
 1184:             }
 1185:         }
 1186:     } else {
 1187:         my ($result,$perm_reqd) = 
 1188: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1189:         if ($result eq 'ok') {
 1190:             if (!($perm_reqd eq 'yes')) {
 1191:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1192:             }
 1193:         }
 1194:     }
 1195:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1196: }
 1197: 
 1198: sub retrievestudentphoto {
 1199:     my ($udom,$unam,$ext,$type) = @_;
 1200:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1201:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1202:     if ($ret eq 'ok') {
 1203:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1204:         if ($type eq 'thumbnail') {
 1205:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1206:         }
 1207:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1208:         return $tokenurl;
 1209:     } else {
 1210:         if ($type eq 'thumbnail') {
 1211:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1212:         } else { 
 1213:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1214:         }
 1215:     }
 1216: }
 1217: 
 1218: # -------------------------------------------------------------------- New chat
 1219: 
 1220: sub chatsend {
 1221:     my ($newentry,$anon,$group)=@_;
 1222:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1223:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1224:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1225:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1226: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1227: 		   &escape($newentry)).':'.$group,$chome);
 1228: }
 1229: 
 1230: # ------------------------------------------ Find current version of a resource
 1231: 
 1232: sub getversion {
 1233:     my $fname=&clutter(shift);
 1234:     unless ($fname=~/^\/res\//) { return -1; }
 1235:     return &currentversion(&filelocation('',$fname));
 1236: }
 1237: 
 1238: sub currentversion {
 1239:     my $fname=shift;
 1240:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1241:     if (defined($cached)) { return $result; }
 1242:     my $author=$fname;
 1243:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1244:     my ($udom,$uname)=split(/\//,$author);
 1245:     my $home=homeserver($uname,$udom);
 1246:     if ($home eq 'no_host') { 
 1247:         return -1; 
 1248:     }
 1249:     my $answer=reply("currentversion:$fname",$home);
 1250:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1251: 	return -1;
 1252:     }
 1253:     return &do_cache_new('resversion',$fname,$answer,600);
 1254: }
 1255: 
 1256: # ----------------------------- Subscribe to a resource, return URL if possible
 1257: 
 1258: sub subscribe {
 1259:     my $fname=shift;
 1260:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1261:     $fname=~s/[\n\r]//g;
 1262:     my $author=$fname;
 1263:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1264:     my ($udom,$uname)=split(/\//,$author);
 1265:     my $home=homeserver($uname,$udom);
 1266:     if ($home eq 'no_host') {
 1267:         return 'not_found';
 1268:     }
 1269:     my $answer=reply("sub:$fname",$home);
 1270:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1271: 	$answer.=' by '.$home;
 1272:     }
 1273:     return $answer;
 1274: }
 1275:     
 1276: # -------------------------------------------------------------- Replicate file
 1277: 
 1278: sub repcopy {
 1279:     my $filename=shift;
 1280:     $filename=~s/\/+/\//g;
 1281:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1282:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1283:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1284: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1285: 	return &repcopy_userfile($filename);
 1286:     }
 1287:     $filename=~s/[\n\r]//g;
 1288:     my $transname="$filename.in.transfer";
 1289: # FIXME: this should flock
 1290:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1291:     my $remoteurl=subscribe($filename);
 1292:     if ($remoteurl =~ /^con_lost by/) {
 1293: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1294:            return 'unavailable';
 1295:     } elsif ($remoteurl eq 'not_found') {
 1296: 	   #&logthis("Subscribe returned not_found: $filename");
 1297: 	   return 'not_found';
 1298:     } elsif ($remoteurl =~ /^rejected by/) {
 1299: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1300:            return 'forbidden';
 1301:     } elsif ($remoteurl eq 'directory') {
 1302:            return 'ok';
 1303:     } else {
 1304:         my $author=$filename;
 1305:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1306:         my ($udom,$uname)=split(/\//,$author);
 1307:         my $home=homeserver($uname,$udom);
 1308:         unless ($home eq $perlvar{'lonHostID'}) {
 1309:            my @parts=split(/\//,$filename);
 1310:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1311:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1312:                &logthis("Malconfiguration for replication: $filename");
 1313: 	       return 'bad_request';
 1314:            }
 1315:            my $count;
 1316:            for ($count=5;$count<$#parts;$count++) {
 1317:                $path.="/$parts[$count]";
 1318:                if ((-e $path)!=1) {
 1319: 		   mkdir($path,0777);
 1320:                }
 1321:            }
 1322:            my $ua=new LWP::UserAgent;
 1323:            my $request=new HTTP::Request('GET',"$remoteurl");
 1324:            my $response=$ua->request($request,$transname);
 1325:            if ($response->is_error()) {
 1326: 	       unlink($transname);
 1327:                my $message=$response->status_line;
 1328:                &logthis("<font color=\"blue\">WARNING:"
 1329:                        ." LWP get: $message: $filename</font>");
 1330:                return 'unavailable';
 1331:            } else {
 1332: 	       if ($remoteurl!~/\.meta$/) {
 1333:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1334:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1335:                   if ($mresponse->is_error()) {
 1336: 		      unlink($filename.'.meta');
 1337:                       &logthis(
 1338:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1339:                   }
 1340: 	       }
 1341:                rename($transname,$filename);
 1342:                return 'ok';
 1343:            }
 1344:        }
 1345:     }
 1346: }
 1347: 
 1348: # ------------------------------------------------ Get server side include body
 1349: sub ssi_body {
 1350:     my ($filelink,%form)=@_;
 1351:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1352:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1353:     }
 1354:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1355:                                      &ssi($filelink,%form));
 1356:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1357:     $output=~s/^.*?\<body[^\>]*\>//si;
 1358:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1359:     return $output;
 1360: }
 1361: 
 1362: # --------------------------------------------------------- Server Side Include
 1363: 
 1364: sub absolute_url {
 1365:     my ($host_name) = @_;
 1366:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1367:     if ($host_name eq '') {
 1368: 	$host_name = $ENV{'SERVER_NAME'};
 1369:     }
 1370:     return $protocol.$host_name;
 1371: }
 1372: 
 1373: sub ssi {
 1374: 
 1375:     my ($fn,%form)=@_;
 1376: 
 1377:     my $ua=new LWP::UserAgent;
 1378:     
 1379:     my $request;
 1380: 
 1381:     $form{'no_update_last_known'}=1;
 1382: 
 1383:     if (%form) {
 1384:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1385:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1386:     } else {
 1387:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1388:     }
 1389: 
 1390:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1391:     my $response=$ua->request($request);
 1392: 
 1393:     return $response->content;
 1394: }
 1395: 
 1396: sub externalssi {
 1397:     my ($url)=@_;
 1398:     my $ua=new LWP::UserAgent;
 1399:     my $request=new HTTP::Request('GET',$url);
 1400:     my $response=$ua->request($request);
 1401:     return $response->content;
 1402: }
 1403: 
 1404: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1405: 
 1406: sub allowuploaded {
 1407:     my ($srcurl,$url)=@_;
 1408:     $url=&clutter(&declutter($url));
 1409:     my $dir=$url;
 1410:     $dir=~s/\/[^\/]+$//;
 1411:     my %httpref=();
 1412:     my $httpurl=&hreflocation('',$url);
 1413:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1414:     &Apache::lonnet::appenv(%httpref);
 1415: }
 1416: 
 1417: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1418: # input: action, courseID, current domain, intended
 1419: #        path to file, source of file, instruction to parse file for objects,
 1420: #        ref to hash for embedded objects,
 1421: #        ref to hash for codebase of java objects.
 1422: #
 1423: # output: url to file (if action was uploaddoc), 
 1424: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1425: #
 1426: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1427: # course.
 1428: #
 1429: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1430: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1431: #          course's home server.
 1432: #
 1433: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1434: #          be copied from $source (current location) to 
 1435: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1436: #         and will then be copied to
 1437: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1438: #         course's home server.
 1439: #
 1440: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1441: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1442: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1443: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1444: #         in course's home server.
 1445: #
 1446: 
 1447: sub process_coursefile {
 1448:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1449:     my $fetchresult;
 1450:     my $home=&homeserver($docuname,$docudom);
 1451:     if ($action eq 'propagate') {
 1452:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1453: 			     $home);
 1454:     } else {
 1455:         my $fpath = '';
 1456:         my $fname = $file;
 1457:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1458:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1459:         my $filepath = &build_filepath($fpath);
 1460:         if ($action eq 'copy') {
 1461:             if ($source eq '') {
 1462:                 $fetchresult = 'no source file';
 1463:                 return $fetchresult;
 1464:             } else {
 1465:                 my $destination = $filepath.'/'.$fname;
 1466:                 rename($source,$destination);
 1467:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1468:                                  $home);
 1469:             }
 1470:         } elsif ($action eq 'uploaddoc') {
 1471:             open(my $fh,'>'.$filepath.'/'.$fname);
 1472:             print $fh $env{'form.'.$source};
 1473:             close($fh);
 1474:             if ($parser eq 'parse') {
 1475:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1476:                 unless ($parse_result eq 'ok') {
 1477:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1478:                 }
 1479:             }
 1480:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1481:                                  $home);
 1482:             if ($fetchresult eq 'ok') {
 1483:                 return '/uploaded/'.$fpath.'/'.$fname;
 1484:             } else {
 1485:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1486:                         ' to host '.$home.': '.$fetchresult);
 1487:                 return '/adm/notfound.html';
 1488:             }
 1489:         }
 1490:     }
 1491:     unless ( $fetchresult eq 'ok') {
 1492:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1493:              ' to host '.$home.': '.$fetchresult);
 1494:     }
 1495:     return $fetchresult;
 1496: }
 1497: 
 1498: sub build_filepath {
 1499:     my ($fpath) = @_;
 1500:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1501:     unless ($fpath eq '') {
 1502:         my @parts=split('/',$fpath);
 1503:         foreach my $part (@parts) {
 1504:             $filepath.= '/'.$part;
 1505:             if ((-e $filepath)!=1) {
 1506:                 mkdir($filepath,0777);
 1507:             }
 1508:         }
 1509:     }
 1510:     return $filepath;
 1511: }
 1512: 
 1513: sub store_edited_file {
 1514:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1515:     my $file = $primary_url;
 1516:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1517:     my $fpath = '';
 1518:     my $fname = $file;
 1519:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1520:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1521:     my $filepath = &build_filepath($fpath);
 1522:     open(my $fh,'>'.$filepath.'/'.$fname);
 1523:     print $fh $content;
 1524:     close($fh);
 1525:     my $home=&homeserver($docuname,$docudom);
 1526:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1527: 			  $home);
 1528:     if ($$fetchresult eq 'ok') {
 1529:         return '/uploaded/'.$fpath.'/'.$fname;
 1530:     } else {
 1531:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1532: 		 ' to host '.$home.': '.$$fetchresult);
 1533:         return '/adm/notfound.html';
 1534:     }
 1535: }
 1536: 
 1537: sub clean_filename {
 1538:     my ($fname,$args)=@_;
 1539: # Replace Windows backslashes by forward slashes
 1540:     $fname=~s/\\/\//g;
 1541:     if (!$args->{'keep_path'}) {
 1542:         # Get rid of everything but the actual filename
 1543: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1544:     }
 1545: # Replace spaces by underscores
 1546:     $fname=~s/\s+/\_/g;
 1547: # Replace all other weird characters by nothing
 1548:     $fname=~s{[^/\w\.\-]}{}g;
 1549: # Replace all .\d. sequences with _\d. so they no longer look like version
 1550: # numbers
 1551:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1552:     return $fname;
 1553: }
 1554: 
 1555: # --------------- Take an uploaded file and put it into the userfiles directory
 1556: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1557: #                    the desired filenam is in $env{"form.$formname.filename"}
 1558: #        $coursedoc - if true up to the current course
 1559: #                     if false
 1560: #        $subdir - directory in userfile to store the file into
 1561: #        $parser - instruction to parse file for objects ($parser = parse)    
 1562: #        $allfiles - reference to hash for embedded objects
 1563: #        $codebase - reference to hash for codebase of java objects
 1564: #        $desuname - username for permanent storage of uploaded file
 1565: #        $dsetudom - domain for permanaent storage of uploaded file
 1566: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1567: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1568: # 
 1569: # output: url of file in userspace, or error: <message> 
 1570: #             or /adm/notfound.html if failure to upload occurse
 1571: 
 1572: 
 1573: sub userfileupload {
 1574:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1575:         $destudom,$thumbwidth,$thumbheight)=@_;
 1576:     if (!defined($subdir)) { $subdir='unknown'; }
 1577:     my $fname=$env{'form.'.$formname.'.filename'};
 1578:     $fname=&clean_filename($fname);
 1579: # See if there is anything left
 1580:     unless ($fname) { return 'error: no uploaded file'; }
 1581:     chop($env{'form.'.$formname});
 1582:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1583:         my $now = time;
 1584:         my $filepath = 'tmp/helprequests/'.$now;
 1585:         my @parts=split(/\//,$filepath);
 1586:         my $fullpath = $perlvar{'lonDaemons'};
 1587:         for (my $i=0;$i<@parts;$i++) {
 1588:             $fullpath .= '/'.$parts[$i];
 1589:             if ((-e $fullpath)!=1) {
 1590:                 mkdir($fullpath,0777);
 1591:             }
 1592:         }
 1593:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1594:         print $fh $env{'form.'.$formname};
 1595:         close($fh);
 1596:         return $fullpath.'/'.$fname;
 1597:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1598:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1599:                        '_'.$env{'user.domain'}.'/pending';
 1600:         my @parts=split(/\//,$filepath);
 1601:         my $fullpath = $perlvar{'lonDaemons'};
 1602:         for (my $i=0;$i<@parts;$i++) {
 1603:             $fullpath .= '/'.$parts[$i];
 1604:             if ((-e $fullpath)!=1) {
 1605:                 mkdir($fullpath,0777);
 1606:             }
 1607:         }
 1608:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1609:         print $fh $env{'form.'.$formname};
 1610:         close($fh);
 1611:         return $fullpath.'/'.$fname;
 1612:     }
 1613:     
 1614: # Create the directory if not present
 1615:     $fname="$subdir/$fname";
 1616:     if ($coursedoc) {
 1617: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1618: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1619:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1620:             return &finishuserfileupload($docuname,$docudom,
 1621: 					 $formname,$fname,$parser,$allfiles,
 1622: 					 $codebase,$thumbwidth,$thumbheight);
 1623:         } else {
 1624:             $fname=$env{'form.folder'}.'/'.$fname;
 1625:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1626: 				       $fname,$formname,$parser,
 1627: 				       $allfiles,$codebase);
 1628:         }
 1629:     } elsif (defined($destuname)) {
 1630:         my $docuname=$destuname;
 1631:         my $docudom=$destudom;
 1632: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1633: 				     $parser,$allfiles,$codebase,
 1634:                                      $thumbwidth,$thumbheight);
 1635:         
 1636:     } else {
 1637:         my $docuname=$env{'user.name'};
 1638:         my $docudom=$env{'user.domain'};
 1639:         if (exists($env{'form.group'})) {
 1640:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1641:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1642:         }
 1643: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1644: 				     $parser,$allfiles,$codebase,
 1645:                                      $thumbwidth,$thumbheight);
 1646:     }
 1647: }
 1648: 
 1649: sub finishuserfileupload {
 1650:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1651:         $thumbwidth,$thumbheight) = @_;
 1652:     my $path=$docudom.'/'.$docuname.'/';
 1653:     my $filepath=$perlvar{'lonDocRoot'};
 1654:     my ($fnamepath,$file,$fetchthumb);
 1655:     $file=$fname;
 1656:     if ($fname=~m|/|) {
 1657:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1658: 	$path.=$fnamepath.'/';
 1659:     }
 1660:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1661:     my $count;
 1662:     for ($count=4;$count<=$#parts;$count++) {
 1663:         $filepath.="/$parts[$count]";
 1664:         if ((-e $filepath)!=1) {
 1665: 	    mkdir($filepath,0777);
 1666:         }
 1667:     }
 1668: # Save the file
 1669:     {
 1670: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1671: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1672: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1673: 	    return '/adm/notfound.html';
 1674: 	}
 1675: 	if (!print FH ($env{'form.'.$formname})) {
 1676: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1677: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1678: 	    return '/adm/notfound.html';
 1679: 	}
 1680: 	close(FH);
 1681:     }
 1682:     if ($parser eq 'parse') {
 1683:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1684: 						   $codebase);
 1685:         unless ($parse_result eq 'ok') {
 1686:             &logthis('Failed to parse '.$filepath.$file.
 1687: 		     ' for embedded media: '.$parse_result); 
 1688:         }
 1689:     }
 1690:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1691:         my $input = $filepath.'/'.$file;
 1692:         my $output = $filepath.'/'.'tn-'.$file;
 1693:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1694:         system("convert -sample $thumbsize $input $output");
 1695:         if (-e $filepath.'/'.'tn-'.$file) {
 1696:             $fetchthumb  = 1; 
 1697:         }
 1698:     }
 1699:  
 1700: # Notify homeserver to grep it
 1701: #
 1702:     my $docuhome=&homeserver($docuname,$docudom);
 1703:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1704:     if ($fetchresult eq 'ok') {
 1705:         if ($fetchthumb) {
 1706:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1707:             if ($thumbresult ne 'ok') {
 1708:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1709:                          $docuhome.': '.$thumbresult);
 1710:             }
 1711:         }
 1712: #
 1713: # Return the URL to it
 1714:         return '/uploaded/'.$path.$file;
 1715:     } else {
 1716:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1717: 		 ': '.$fetchresult);
 1718:         return '/adm/notfound.html';
 1719:     }
 1720: }
 1721: 
 1722: sub extract_embedded_items {
 1723:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1724:     my @state = ();
 1725:     my %javafiles = (
 1726:                       codebase => '',
 1727:                       code => '',
 1728:                       archive => ''
 1729:                     );
 1730:     my %mediafiles = (
 1731:                       src => '',
 1732:                       movie => '',
 1733:                      );
 1734:     my $p;
 1735:     if ($content) {
 1736:         $p = HTML::LCParser->new($content);
 1737:     } else {
 1738:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1739:     }
 1740:     while (my $t=$p->get_token()) {
 1741: 	if ($t->[0] eq 'S') {
 1742: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1743: 	    push (@state, $tagname);
 1744:             if (lc($tagname) eq 'allow') {
 1745:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1746:             }
 1747: 	    if (lc($tagname) eq 'img') {
 1748: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1749: 	    }
 1750:             if (lc($tagname) eq 'script') {
 1751:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1752:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1753:                 } else {
 1754:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1755:                 }
 1756:             }
 1757:             if (lc($tagname) eq 'link') {
 1758:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1759:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1760:                 }
 1761:             }
 1762: 	    if (lc($tagname) eq 'object' ||
 1763: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1764: 		foreach my $item (keys(%javafiles)) {
 1765: 		    $javafiles{$item} = '';
 1766: 		}
 1767: 	    }
 1768: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1769: 		my $name = lc($attr->{'name'});
 1770: 		foreach my $item (keys(%javafiles)) {
 1771: 		    if ($name eq $item) {
 1772: 			$javafiles{$item} = $attr->{'value'};
 1773: 			last;
 1774: 		    }
 1775: 		}
 1776: 		foreach my $item (keys(%mediafiles)) {
 1777: 		    if ($name eq $item) {
 1778: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1779: 			last;
 1780: 		    }
 1781: 		}
 1782: 	    }
 1783: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1784: 		foreach my $item (keys(%javafiles)) {
 1785: 		    if ($attr->{$item}) {
 1786: 			$javafiles{$item} = $attr->{$item};
 1787: 			last;
 1788: 		    }
 1789: 		}
 1790: 		foreach my $item (keys(%mediafiles)) {
 1791: 		    if ($attr->{$item}) {
 1792: 			&add_filetype($allfiles,$attr->{$item},$item);
 1793: 			last;
 1794: 		    }
 1795: 		}
 1796: 	    }
 1797: 	} elsif ($t->[0] eq 'E') {
 1798: 	    my ($tagname) = ($t->[1]);
 1799: 	    if ($javafiles{'codebase'} ne '') {
 1800: 		$javafiles{'codebase'} .= '/';
 1801: 	    }  
 1802: 	    if (lc($tagname) eq 'applet' ||
 1803: 		lc($tagname) eq 'object' ||
 1804: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1805: 		) {
 1806: 		foreach my $item (keys(%javafiles)) {
 1807: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1808: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1809: 			&add_filetype($allfiles,$file,$item);
 1810: 		    }
 1811: 		}
 1812: 	    } 
 1813: 	    pop @state;
 1814: 	}
 1815:     }
 1816:     return 'ok';
 1817: }
 1818: 
 1819: sub add_filetype {
 1820:     my ($allfiles,$file,$type)=@_;
 1821:     if (exists($allfiles->{$file})) {
 1822: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1823: 	    push(@{$allfiles->{$file}}, &escape($type));
 1824: 	}
 1825:     } else {
 1826: 	@{$allfiles->{$file}} = (&escape($type));
 1827:     }
 1828: }
 1829: 
 1830: sub removeuploadedurl {
 1831:     my ($url)=@_;
 1832:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1833:     return &removeuserfile($uname,$udom,$fname);
 1834: }
 1835: 
 1836: sub removeuserfile {
 1837:     my ($docuname,$docudom,$fname)=@_;
 1838:     my $home=&homeserver($docuname,$docudom);
 1839:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1840:     if ($result eq 'ok') {
 1841:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1842:             my $metafile = $fname.'.meta';
 1843:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1844: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1845:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1846:             my $sqlresult = 
 1847:                 &update_portfolio_table($docuname,$docudom,$file,
 1848:                                         'portfolio_metadata',$group,
 1849:                                         'delete');
 1850:         }
 1851:     }
 1852:     return $result;
 1853: }
 1854: 
 1855: sub mkdiruserfile {
 1856:     my ($docuname,$docudom,$dir)=@_;
 1857:     my $home=&homeserver($docuname,$docudom);
 1858:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1859: }
 1860: 
 1861: sub renameuserfile {
 1862:     my ($docuname,$docudom,$old,$new)=@_;
 1863:     my $home=&homeserver($docuname,$docudom);
 1864:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1865:                         &escape("$old").':'.&escape("$new"),$home);
 1866:     if ($result eq 'ok') {
 1867:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1868:             my $oldmeta = $old.'.meta';
 1869:             my $newmeta = $new.'.meta';
 1870:             my $metaresult = 
 1871:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1872: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1873:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1874:             my $sqlresult = 
 1875:                 &update_portfolio_table($docuname,$docudom,$file,
 1876:                                         'portfolio_metadata',$group,
 1877:                                         'delete');
 1878:         }
 1879:     }
 1880:     return $result;
 1881: }
 1882: 
 1883: # ------------------------------------------------------------------------- Log
 1884: 
 1885: sub log {
 1886:     my ($dom,$nam,$hom,$what)=@_;
 1887:     return critical("log:$dom:$nam:$what",$hom);
 1888: }
 1889: 
 1890: # ------------------------------------------------------------------ Course Log
 1891: #
 1892: # This routine flushes several buffers of non-mission-critical nature
 1893: #
 1894: 
 1895: sub flushcourselogs {
 1896:     &logthis('Flushing log buffers');
 1897: #
 1898: # course logs
 1899: # This is a log of all transactions in a course, which can be used
 1900: # for data mining purposes
 1901: #
 1902: # It also collects the courseid database, which lists last transaction
 1903: # times and course titles for all courseids
 1904: #
 1905:     my %courseidbuffer=();
 1906:     foreach my $crsid (keys %courselogs) {
 1907:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1908: 		          &escape($courselogs{$crsid}),
 1909: 		          $coursehombuf{$crsid}) eq 'ok') {
 1910: 	    delete $courselogs{$crsid};
 1911:         } else {
 1912:             &logthis('Failed to flush log buffer for '.$crsid);
 1913:             if (length($courselogs{$crsid})>40000) {
 1914:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1915:                         " exceeded maximum size, deleting.</font>");
 1916:                delete $courselogs{$crsid};
 1917:             }
 1918:         }
 1919:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1920:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1921: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1922:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1923:         } else {
 1924:            $courseidbuffer{$coursehombuf{$crsid}}=
 1925: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1926:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1927:         }
 1928:     }
 1929: #
 1930: # Write course id database (reverse lookup) to homeserver of courses 
 1931: # Is used in pickcourse
 1932: #
 1933:     foreach my $crs_home (keys(%courseidbuffer)) {
 1934:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1935: 		     $crs_home);
 1936:     }
 1937: #
 1938: # File accesses
 1939: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1940: #
 1941:     foreach my $entry (keys(%accesshash)) {
 1942:         if ($entry =~ /___count$/) {
 1943:             my ($dom,$name);
 1944:             ($dom,$name,undef)=
 1945: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1946:             if (! defined($dom) || $dom eq '' || 
 1947:                 ! defined($name) || $name eq '') {
 1948:                 my $cid = $env{'request.course.id'};
 1949:                 $dom  = $env{'request.'.$cid.'.domain'};
 1950:                 $name = $env{'request.'.$cid.'.num'};
 1951:             }
 1952:             my $value = $accesshash{$entry};
 1953:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1954:             my %temphash=($url => $value);
 1955:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1956:             if ($result eq 'ok') {
 1957:                 delete $accesshash{$entry};
 1958:             } elsif ($result eq 'unknown_cmd') {
 1959:                 # Target server has old code running on it.
 1960:                 my %temphash=($entry => $value);
 1961:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1962:                     delete $accesshash{$entry};
 1963:                 }
 1964:             }
 1965:         } else {
 1966:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1967:             my %temphash=($entry => $accesshash{$entry});
 1968:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1969:                 delete $accesshash{$entry};
 1970:             }
 1971:         }
 1972:     }
 1973: #
 1974: # Roles
 1975: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1976: #
 1977:     foreach my $entry (keys(%userrolehash)) {
 1978:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1979: 	    split(/\:/,$entry);
 1980:         if (&Apache::lonnet::put('nohist_userroles',
 1981:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1982:                 $rudom,$runame) eq 'ok') {
 1983: 	    delete $userrolehash{$entry};
 1984:         }
 1985:     }
 1986: #
 1987: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1988: #
 1989:     my %domrolebuffer = ();
 1990:     foreach my $entry (keys %domainrolehash) {
 1991:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1992:         if ($domrolebuffer{$rudom}) {
 1993:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1994:                       '='.&escape($domainrolehash{$entry});
 1995:         } else {
 1996:             $domrolebuffer{$rudom}.=&escape($entry).
 1997:                       '='.&escape($domainrolehash{$entry});
 1998:         }
 1999:         delete $domainrolehash{$entry};
 2000:     }
 2001:     foreach my $dom (keys(%domrolebuffer)) {
 2002: 	my %servers = &get_servers($dom,'library');
 2003: 	foreach my $tryserver (keys(%servers)) {
 2004: 	    unless (&reply('domroleput:'.$dom.':'.
 2005: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2006: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2007: 	    }
 2008:         }
 2009:     }
 2010:     $dumpcount++;
 2011: }
 2012: 
 2013: sub courselog {
 2014:     my $what=shift;
 2015:     $what=time.':'.$what;
 2016:     unless ($env{'request.course.id'}) { return ''; }
 2017:     $coursedombuf{$env{'request.course.id'}}=
 2018:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2019:     $coursenumbuf{$env{'request.course.id'}}=
 2020:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2021:     $coursehombuf{$env{'request.course.id'}}=
 2022:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2023:     $coursedescrbuf{$env{'request.course.id'}}=
 2024:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2025:     $courseinstcodebuf{$env{'request.course.id'}}=
 2026:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2027:     $courseownerbuf{$env{'request.course.id'}}=
 2028:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2029:     $coursetypebuf{$env{'request.course.id'}}=
 2030:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2031:     if (defined $courselogs{$env{'request.course.id'}}) {
 2032: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2033:     } else {
 2034: 	$courselogs{$env{'request.course.id'}}.=$what;
 2035:     }
 2036:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2037: 	&flushcourselogs();
 2038:     }
 2039: }
 2040: 
 2041: sub courseacclog {
 2042:     my $fnsymb=shift;
 2043:     unless ($env{'request.course.id'}) { return ''; }
 2044:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2045:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2046:         $what.=':POST';
 2047:         # FIXME: Probably ought to escape things....
 2048: 	foreach my $key (keys(%env)) {
 2049:             if ($key=~/^form\.(.*)/) {
 2050: 		$what.=':'.$1.'='.$env{$key};
 2051:             }
 2052:         }
 2053:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2054:         # FIXME: We should not be depending on a form parameter that someone
 2055:         # editing lonsearchcat.pm might change in the future.
 2056:         if ($env{'form.phase'} eq 'course_search') {
 2057:             $what.= ':POST';
 2058:             # FIXME: Probably ought to escape things....
 2059:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2060:                                  'crsdiscuss') {
 2061:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2062:             }
 2063:         }
 2064:     }
 2065:     &courselog($what);
 2066: }
 2067: 
 2068: sub countacc {
 2069:     my $url=&declutter(shift);
 2070:     return if (! defined($url) || $url eq '');
 2071:     unless ($env{'request.course.id'}) { return ''; }
 2072:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2073:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2074:     $accesshash{$key}++;
 2075: }
 2076: 
 2077: sub linklog {
 2078:     my ($from,$to)=@_;
 2079:     $from=&declutter($from);
 2080:     $to=&declutter($to);
 2081:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2082:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2083: }
 2084:   
 2085: sub userrolelog {
 2086:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2087:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2088:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2089:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2090:         ($trole=~/^ta/)) {
 2091:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2092:        $userrolehash
 2093:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2094:                     =$tend.':'.$tstart;
 2095:     }
 2096:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2097:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2098:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2099:         ($trole=~/^sc/)) {
 2100:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2101:        $domainrolehash
 2102:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2103:                     = $tend.':'.$tstart;
 2104:     }
 2105: }
 2106: 
 2107: sub get_course_adv_roles {
 2108:     my $cid=shift;
 2109:     $cid=$env{'request.course.id'} unless (defined($cid));
 2110:     my %coursehash=&coursedescription($cid);
 2111:     my %nothide=();
 2112:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2113: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2114:     }
 2115:     my %returnhash=();
 2116:     my %dumphash=
 2117:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2118:     my $now=time;
 2119:     foreach my $entry (keys %dumphash) {
 2120: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2121:         if (($tstart) && ($tstart<0)) { next; }
 2122:         if (($tend) && ($tend<$now)) { next; }
 2123:         if (($tstart) && ($now<$tstart)) { next; }
 2124:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2125: 	if ($username eq '' || $domain eq '') { next; }
 2126: 	if ((&privileged($username,$domain)) && 
 2127: 	    (!$nothide{$username.':'.$domain})) { next; }
 2128: 	if ($role eq 'cr') { next; }
 2129:         my $key=&plaintext($role);
 2130:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2131:         if ($returnhash{$key}) {
 2132: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2133:         } else {
 2134:             $returnhash{$key}=$username.':'.$domain;
 2135:         }
 2136:      }
 2137:     return %returnhash;
 2138: }
 2139: 
 2140: sub get_my_roles {
 2141:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2142:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2143:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2144:     my %dumphash;
 2145:     if ($context eq 'userroles') { 
 2146:         %dumphash = &dump('roles',$udom,$uname);
 2147:     } else {
 2148:         %dumphash=
 2149:             &dump('nohist_userroles',$udom,$uname);
 2150:     }
 2151:     my %returnhash=();
 2152:     my $now=time;
 2153:     foreach my $entry (keys(%dumphash)) {
 2154:         my ($role,$tend,$tstart);
 2155:         if ($context eq 'userroles') {
 2156: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2157:         } else {
 2158:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2159:         }
 2160:         if (($tstart) && ($tstart<0)) { next; }
 2161:         my $status = 'active';
 2162:         if (($tend) && ($tend<$now)) {
 2163:             $status = 'previous';
 2164:         } 
 2165:         if (($tstart) && ($now<$tstart)) {
 2166:             $status = 'future';
 2167:         }
 2168:         if (ref($types) eq 'ARRAY') {
 2169:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2170:                 next;
 2171:             } 
 2172:         } else {
 2173:             if ($status ne 'active') {
 2174:                 next;
 2175:             }
 2176:         }
 2177:         my ($rolecode,$username,$domain,$section,$area);
 2178:         if ($context eq 'userroles') {
 2179:             ($area,$rolecode) = split(/_/,$entry);
 2180:             (undef,$domain,$username,$section) = split(/\//,$area);
 2181:         } else {
 2182:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2183:         }
 2184:         if (ref($roledoms) eq 'ARRAY') {
 2185:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2186:                 next;
 2187:             }
 2188:         }
 2189:         if (ref($roles) eq 'ARRAY') {
 2190:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2191:                 next;
 2192:             }
 2193:         }
 2194: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2195:     }
 2196:     return %returnhash;
 2197: }
 2198: 
 2199: # ----------------------------------------------------- Frontpage Announcements
 2200: #
 2201: #
 2202: 
 2203: sub postannounce {
 2204:     my ($server,$text)=@_;
 2205:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2206:     unless ($text=~/\w/) { $text=''; }
 2207:     return &reply('setannounce:'.&escape($text),$server);
 2208: }
 2209: 
 2210: sub getannounce {
 2211: 
 2212:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2213: 	my $announcement='';
 2214: 	while (my $line = <$fh>) { $announcement .= $line; }
 2215: 	close($fh);
 2216: 	if ($announcement=~/\w/) { 
 2217: 	    return 
 2218:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2219:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2220: 	} else {
 2221: 	    return '';
 2222: 	}
 2223:     } else {
 2224: 	return '';
 2225:     }
 2226: }
 2227: 
 2228: # ---------------------------------------------------------- Course ID routines
 2229: # Deal with domain's nohist_courseid.db files
 2230: #
 2231: 
 2232: sub courseidput {
 2233:     my ($domain,$what,$coursehome)=@_;
 2234:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2235: }
 2236: 
 2237: sub courseiddump {
 2238:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2239:     my %returnhash=();
 2240:     unless ($domfilter) { $domfilter=''; }
 2241:     my %libserv = &all_library();
 2242:     foreach my $tryserver (keys(%libserv)) {
 2243:         if ( (  $hostidflag == 1 
 2244: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2245: 	     || (!defined($hostidflag)) ) {
 2246: 
 2247: 	    if ($domfilter eq ''
 2248: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2249: 	        foreach my $line (
 2250:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2251: 			       $sincefilter.':'.&escape($descfilter).':'.
 2252:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2253:                                $tryserver))) {
 2254: 		    my ($key,$value)=split(/\=/,$line,2);
 2255:                     if (($key) && ($value)) {
 2256: 		        $returnhash{&unescape($key)}=$value;
 2257:                     }
 2258:                 }
 2259:             }
 2260:         }
 2261:     }
 2262:     return %returnhash;
 2263: }
 2264: 
 2265: # ---------------------------------------------------------- DC e-mail
 2266: 
 2267: sub dcmailput {
 2268:     my ($domain,$msgid,$message,$server)=@_;
 2269:     my $status = &Apache::lonnet::critical(
 2270:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2271:        &escape($message),$server);
 2272:     return $status;
 2273: }
 2274: 
 2275: sub dcmaildump {
 2276:     my ($dom,$startdate,$enddate,$senders) = @_;
 2277:     my %returnhash=();
 2278: 
 2279:     if (defined(&domain($dom,'primary'))) {
 2280:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2281:                                                          &escape($enddate).':';
 2282: 	my @esc_senders=map { &escape($_)} @$senders;
 2283: 	$cmd.=&escape(join('&',@esc_senders));
 2284: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2285:             my ($key,$value) = split(/\=/,$line,2);
 2286:             if (($key) && ($value)) {
 2287:                 $returnhash{&unescape($key)} = &unescape($value);
 2288:             }
 2289:         }
 2290:     }
 2291:     return %returnhash;
 2292: }
 2293: # ---------------------------------------------------------- Domain roles
 2294: 
 2295: sub get_domain_roles {
 2296:     my ($dom,$roles,$startdate,$enddate)=@_;
 2297:     if (undef($startdate) || $startdate eq '') {
 2298:         $startdate = '.';
 2299:     }
 2300:     if (undef($enddate) || $enddate eq '') {
 2301:         $enddate = '.';
 2302:     }
 2303:     my $rolelist = join(':',@{$roles});
 2304:     my %personnel = ();
 2305: 
 2306:     my %servers = &get_servers($dom,'library');
 2307:     foreach my $tryserver (keys(%servers)) {
 2308: 	%{$personnel{$tryserver}}=();
 2309: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2310: 					    &escape($startdate).':'.
 2311: 					    &escape($enddate).':'.
 2312: 					    &escape($rolelist), $tryserver))) {
 2313: 	    my ($key,$value) = split(/\=/,$line,2);
 2314: 	    if (($key) && ($value)) {
 2315: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2316: 	    }
 2317: 	}
 2318:     }
 2319:     return %personnel;
 2320: }
 2321: 
 2322: # ----------------------------------------------------------- Check out an item
 2323: 
 2324: sub get_first_access {
 2325:     my ($type,$argsymb)=@_;
 2326:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2327:     if ($argsymb) { $symb=$argsymb; }
 2328:     my ($map,$id,$res)=&decode_symb($symb);
 2329:     if ($type eq 'map') {
 2330: 	$res=&symbread($map);
 2331:     } else {
 2332: 	$res=$symb;
 2333:     }
 2334:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2335:     return $times{"$courseid\0$res"};
 2336: }
 2337: 
 2338: sub set_first_access {
 2339:     my ($type)=@_;
 2340:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2341:     my ($map,$id,$res)=&decode_symb($symb);
 2342:     if ($type eq 'map') {
 2343: 	$res=&symbread($map);
 2344:     } else {
 2345: 	$res=$symb;
 2346:     }
 2347:     my $firstaccess=&get_first_access($type,$symb);
 2348:     if (!$firstaccess) {
 2349: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2350:     }
 2351:     return 'already_set';
 2352: }
 2353: 
 2354: sub checkout {
 2355:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2356:     my $now=time;
 2357:     my $lonhost=$perlvar{'lonHostID'};
 2358:     my $infostr=&escape(
 2359:                  'CHECKOUTTOKEN&'.
 2360:                  $tuname.'&'.
 2361:                  $tudom.'&'.
 2362:                  $tcrsid.'&'.
 2363:                  $symb.'&'.
 2364: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2365:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2366:     if ($token=~/^error\:/) { 
 2367:         &logthis("<font color=\"blue\">WARNING: ".
 2368:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2369:                  "</font>");
 2370:         return ''; 
 2371:     }
 2372: 
 2373:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2374:     $token=~tr/a-z/A-Z/;
 2375: 
 2376:     my %infohash=('resource.0.outtoken' => $token,
 2377:                   'resource.0.checkouttime' => $now,
 2378:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2379: 
 2380:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2381:        return '';
 2382:     } else {
 2383:         &logthis("<font color=\"blue\">WARNING: ".
 2384:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2385:                  "</font>");
 2386:     }    
 2387: 
 2388:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2389:                          &escape('Checkout '.$infostr.' - '.
 2390:                                                  $token)) ne 'ok') {
 2391: 	return '';
 2392:     } else {
 2393:         &logthis("<font color=\"blue\">WARNING: ".
 2394:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2395:                  "</font>");
 2396:     }
 2397:     return $token;
 2398: }
 2399: 
 2400: # ------------------------------------------------------------ Check in an item
 2401: 
 2402: sub checkin {
 2403:     my $token=shift;
 2404:     my $now=time;
 2405:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2406:     $lonhost=~tr/A-Z/a-z/;
 2407:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2408:     $dtoken=~s/\W/\_/g;
 2409:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2410:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2411: 
 2412:     unless (($tuname) && ($tudom)) {
 2413:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2414:         return '';
 2415:     }
 2416:     
 2417:     unless (&allowed('mgr',$tcrsid)) {
 2418:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2419:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2420:         return '';
 2421:     }
 2422: 
 2423:     my %infohash=('resource.0.intoken' => $token,
 2424:                   'resource.0.checkintime' => $now,
 2425:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2426: 
 2427:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2428:        return '';
 2429:     }    
 2430: 
 2431:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2432:                          &escape('Checkin - '.$token)) ne 'ok') {
 2433: 	return '';
 2434:     }
 2435: 
 2436:     return ($symb,$tuname,$tudom,$tcrsid);    
 2437: }
 2438: 
 2439: # --------------------------------------------- Set Expire Date for Spreadsheet
 2440: 
 2441: sub expirespread {
 2442:     my ($uname,$udom,$stype,$usymb)=@_;
 2443:     my $cid=$env{'request.course.id'}; 
 2444:     if ($cid) {
 2445:        my $now=time;
 2446:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2447:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2448:                             $env{'course.'.$cid.'.num'}.
 2449: 	        	    ':nohist_expirationdates:'.
 2450:                             &escape($key).'='.$now,
 2451:                             $env{'course.'.$cid.'.home'})
 2452:     }
 2453:     return 'ok';
 2454: }
 2455: 
 2456: # ----------------------------------------------------- Devalidate Spreadsheets
 2457: 
 2458: sub devalidate {
 2459:     my ($symb,$uname,$udom)=@_;
 2460:     my $cid=$env{'request.course.id'}; 
 2461:     if ($cid) {
 2462:         # delete the stored spreadsheets for
 2463:         # - the student level sheet of this user in course's homespace
 2464:         # - the assessment level sheet for this resource 
 2465:         #   for this user in user's homespace
 2466: 	# - current conditional state info
 2467: 	my $key=$uname.':'.$udom.':';
 2468:         my $status=
 2469: 	    &del('nohist_calculatedsheets',
 2470: 		 [$key.'studentcalc:'],
 2471: 		 $env{'course.'.$cid.'.domain'},
 2472: 		 $env{'course.'.$cid.'.num'})
 2473: 		.' '.
 2474: 	    &del('nohist_calculatedsheets_'.$cid,
 2475: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2476:         unless ($status eq 'ok ok') {
 2477:            &logthis('Could not devalidate spreadsheet '.
 2478:                     $uname.' at '.$udom.' for '.
 2479: 		    $symb.': '.$status);
 2480:         }
 2481: 	&delenv('user.state.'.$cid);
 2482:     }
 2483: }
 2484: 
 2485: sub get_scalar {
 2486:     my ($string,$end) = @_;
 2487:     my $value;
 2488:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2489: 	$value = $1;
 2490:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2491: 	$value = $1;
 2492:     }
 2493:     return &unescape($value);
 2494: }
 2495: 
 2496: sub array2str {
 2497:   my (@array) = @_;
 2498:   my $result=&arrayref2str(\@array);
 2499:   $result=~s/^__ARRAY_REF__//;
 2500:   $result=~s/__END_ARRAY_REF__$//;
 2501:   return $result;
 2502: }
 2503: 
 2504: sub arrayref2str {
 2505:   my ($arrayref) = @_;
 2506:   my $result='__ARRAY_REF__';
 2507:   foreach my $elem (@$arrayref) {
 2508:     if(ref($elem) eq 'ARRAY') {
 2509:       $result.=&arrayref2str($elem).'&';
 2510:     } elsif(ref($elem) eq 'HASH') {
 2511:       $result.=&hashref2str($elem).'&';
 2512:     } elsif(ref($elem)) {
 2513:       #print("Got a ref of ".(ref($elem))." skipping.");
 2514:     } else {
 2515:       $result.=&escape($elem).'&';
 2516:     }
 2517:   }
 2518:   $result=~s/\&$//;
 2519:   $result .= '__END_ARRAY_REF__';
 2520:   return $result;
 2521: }
 2522: 
 2523: sub hash2str {
 2524:   my (%hash) = @_;
 2525:   my $result=&hashref2str(\%hash);
 2526:   $result=~s/^__HASH_REF__//;
 2527:   $result=~s/__END_HASH_REF__$//;
 2528:   return $result;
 2529: }
 2530: 
 2531: sub hashref2str {
 2532:   my ($hashref)=@_;
 2533:   my $result='__HASH_REF__';
 2534:   foreach my $key (sort(keys(%$hashref))) {
 2535:     if (ref($key) eq 'ARRAY') {
 2536:       $result.=&arrayref2str($key).'=';
 2537:     } elsif (ref($key) eq 'HASH') {
 2538:       $result.=&hashref2str($key).'=';
 2539:     } elsif (ref($key)) {
 2540:       $result.='=';
 2541:       #print("Got a ref of ".(ref($key))." skipping.");
 2542:     } else {
 2543: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2544:     }
 2545: 
 2546:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2547:       $result.=&arrayref2str($hashref->{$key}).'&';
 2548:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2549:       $result.=&hashref2str($hashref->{$key}).'&';
 2550:     } elsif(ref($hashref->{$key})) {
 2551:        $result.='&';
 2552:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2553:     } else {
 2554:       $result.=&escape($hashref->{$key}).'&';
 2555:     }
 2556:   }
 2557:   $result=~s/\&$//;
 2558:   $result .= '__END_HASH_REF__';
 2559:   return $result;
 2560: }
 2561: 
 2562: sub str2hash {
 2563:     my ($string)=@_;
 2564:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2565:     return %$hash;
 2566: }
 2567: 
 2568: sub str2hashref {
 2569:   my ($string) = @_;
 2570: 
 2571:   my %hash;
 2572: 
 2573:   if($string !~ /^__HASH_REF__/) {
 2574:       if (! ($string eq '' || !defined($string))) {
 2575: 	  $hash{'error'}='Not hash reference';
 2576:       }
 2577:       return (\%hash, $string);
 2578:   }
 2579: 
 2580:   $string =~ s/^__HASH_REF__//;
 2581: 
 2582:   while($string !~ /^__END_HASH_REF__/) {
 2583:       #key
 2584:       my $key='';
 2585:       if($string =~ /^__HASH_REF__/) {
 2586:           ($key, $string)=&str2hashref($string);
 2587:           if(defined($key->{'error'})) {
 2588:               $hash{'error'}='Bad data';
 2589:               return (\%hash, $string);
 2590:           }
 2591:       } elsif($string =~ /^__ARRAY_REF__/) {
 2592:           ($key, $string)=&str2arrayref($string);
 2593:           if($key->[0] eq 'Array reference error') {
 2594:               $hash{'error'}='Bad data';
 2595:               return (\%hash, $string);
 2596:           }
 2597:       } else {
 2598:           $string =~ s/^(.*?)=//;
 2599: 	  $key=&unescape($1);
 2600:       }
 2601:       $string =~ s/^=//;
 2602: 
 2603:       #value
 2604:       my $value='';
 2605:       if($string =~ /^__HASH_REF__/) {
 2606:           ($value, $string)=&str2hashref($string);
 2607:           if(defined($value->{'error'})) {
 2608:               $hash{'error'}='Bad data';
 2609:               return (\%hash, $string);
 2610:           }
 2611:       } elsif($string =~ /^__ARRAY_REF__/) {
 2612:           ($value, $string)=&str2arrayref($string);
 2613:           if($value->[0] eq 'Array reference error') {
 2614:               $hash{'error'}='Bad data';
 2615:               return (\%hash, $string);
 2616:           }
 2617:       } else {
 2618: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2619:       }
 2620:       $string =~ s/^&//;
 2621: 
 2622:       $hash{$key}=$value;
 2623:   }
 2624: 
 2625:   $string =~ s/^__END_HASH_REF__//;
 2626: 
 2627:   return (\%hash, $string);
 2628: }
 2629: 
 2630: sub str2array {
 2631:     my ($string)=@_;
 2632:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2633:     return @$array;
 2634: }
 2635: 
 2636: sub str2arrayref {
 2637:   my ($string) = @_;
 2638:   my @array;
 2639: 
 2640:   if($string !~ /^__ARRAY_REF__/) {
 2641:       if (! ($string eq '' || !defined($string))) {
 2642: 	  $array[0]='Array reference error';
 2643:       }
 2644:       return (\@array, $string);
 2645:   }
 2646: 
 2647:   $string =~ s/^__ARRAY_REF__//;
 2648: 
 2649:   while($string !~ /^__END_ARRAY_REF__/) {
 2650:       my $value='';
 2651:       if($string =~ /^__HASH_REF__/) {
 2652:           ($value, $string)=&str2hashref($string);
 2653:           if(defined($value->{'error'})) {
 2654:               $array[0] ='Array reference error';
 2655:               return (\@array, $string);
 2656:           }
 2657:       } elsif($string =~ /^__ARRAY_REF__/) {
 2658:           ($value, $string)=&str2arrayref($string);
 2659:           if($value->[0] eq 'Array reference error') {
 2660:               $array[0] ='Array reference error';
 2661:               return (\@array, $string);
 2662:           }
 2663:       } else {
 2664: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2665:       }
 2666:       $string =~ s/^&//;
 2667: 
 2668:       push(@array, $value);
 2669:   }
 2670: 
 2671:   $string =~ s/^__END_ARRAY_REF__//;
 2672: 
 2673:   return (\@array, $string);
 2674: }
 2675: 
 2676: # -------------------------------------------------------------------Temp Store
 2677: 
 2678: sub tmpreset {
 2679:   my ($symb,$namespace,$domain,$stuname) = @_;
 2680:   if (!$symb) {
 2681:     $symb=&symbread();
 2682:     if (!$symb) { $symb= $env{'request.url'}; }
 2683:   }
 2684:   $symb=escape($symb);
 2685: 
 2686:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2687:   $namespace=~s/\//\_/g;
 2688:   $namespace=~s/\W//g;
 2689: 
 2690:   if (!$domain) { $domain=$env{'user.domain'}; }
 2691:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2692:   if ($domain eq 'public' && $stuname eq 'public') {
 2693:       $stuname=$ENV{'REMOTE_ADDR'};
 2694:   }
 2695:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2696:   my %hash;
 2697:   if (tie(%hash,'GDBM_File',
 2698: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2699: 	  &GDBM_WRCREAT(),0640)) {
 2700:     foreach my $key (keys %hash) {
 2701:       if ($key=~ /:$symb/) {
 2702: 	delete($hash{$key});
 2703:       }
 2704:     }
 2705:   }
 2706: }
 2707: 
 2708: sub tmpstore {
 2709:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2710: 
 2711:   if (!$symb) {
 2712:     $symb=&symbread();
 2713:     if (!$symb) { $symb= $env{'request.url'}; }
 2714:   }
 2715:   $symb=escape($symb);
 2716: 
 2717:   if (!$namespace) {
 2718:     # I don't think we would ever want to store this for a course.
 2719:     # it seems this will only be used if we don't have a course.
 2720:     #$namespace=$env{'request.course.id'};
 2721:     #if (!$namespace) {
 2722:       $namespace=$env{'request.state'};
 2723:     #}
 2724:   }
 2725:   $namespace=~s/\//\_/g;
 2726:   $namespace=~s/\W//g;
 2727:   if (!$domain) { $domain=$env{'user.domain'}; }
 2728:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2729:   if ($domain eq 'public' && $stuname eq 'public') {
 2730:       $stuname=$ENV{'REMOTE_ADDR'};
 2731:   }
 2732:   my $now=time;
 2733:   my %hash;
 2734:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2735:   if (tie(%hash,'GDBM_File',
 2736: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2737: 	  &GDBM_WRCREAT(),0640)) {
 2738:     $hash{"version:$symb"}++;
 2739:     my $version=$hash{"version:$symb"};
 2740:     my $allkeys=''; 
 2741:     foreach my $key (keys(%$storehash)) {
 2742:       $allkeys.=$key.':';
 2743:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2744:     }
 2745:     $hash{"$version:$symb:timestamp"}=$now;
 2746:     $allkeys.='timestamp';
 2747:     $hash{"$version:keys:$symb"}=$allkeys;
 2748:     if (untie(%hash)) {
 2749:       return 'ok';
 2750:     } else {
 2751:       return "error:$!";
 2752:     }
 2753:   } else {
 2754:     return "error:$!";
 2755:   }
 2756: }
 2757: 
 2758: # -----------------------------------------------------------------Temp Restore
 2759: 
 2760: sub tmprestore {
 2761:   my ($symb,$namespace,$domain,$stuname) = @_;
 2762: 
 2763:   if (!$symb) {
 2764:     $symb=&symbread();
 2765:     if (!$symb) { $symb= $env{'request.url'}; }
 2766:   }
 2767:   $symb=escape($symb);
 2768: 
 2769:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2770: 
 2771:   if (!$domain) { $domain=$env{'user.domain'}; }
 2772:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2773:   if ($domain eq 'public' && $stuname eq 'public') {
 2774:       $stuname=$ENV{'REMOTE_ADDR'};
 2775:   }
 2776:   my %returnhash;
 2777:   $namespace=~s/\//\_/g;
 2778:   $namespace=~s/\W//g;
 2779:   my %hash;
 2780:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2781:   if (tie(%hash,'GDBM_File',
 2782: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2783: 	  &GDBM_READER(),0640)) {
 2784:     my $version=$hash{"version:$symb"};
 2785:     $returnhash{'version'}=$version;
 2786:     my $scope;
 2787:     for ($scope=1;$scope<=$version;$scope++) {
 2788:       my $vkeys=$hash{"$scope:keys:$symb"};
 2789:       my @keys=split(/:/,$vkeys);
 2790:       my $key;
 2791:       $returnhash{"$scope:keys"}=$vkeys;
 2792:       foreach $key (@keys) {
 2793: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2794: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2795:       }
 2796:     }
 2797:     if (!(untie(%hash))) {
 2798:       return "error:$!";
 2799:     }
 2800:   } else {
 2801:     return "error:$!";
 2802:   }
 2803:   return %returnhash;
 2804: }
 2805: 
 2806: # ----------------------------------------------------------------------- Store
 2807: 
 2808: sub store {
 2809:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2810:     my $home='';
 2811: 
 2812:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2813: 
 2814:     $symb=&symbclean($symb);
 2815:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2816: 
 2817:     if (!$domain) { $domain=$env{'user.domain'}; }
 2818:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2819: 
 2820:     &devalidate($symb,$stuname,$domain);
 2821: 
 2822:     $symb=escape($symb);
 2823:     if (!$namespace) { 
 2824:        unless ($namespace=$env{'request.course.id'}) { 
 2825:           return ''; 
 2826:        } 
 2827:     }
 2828:     if (!$home) { $home=$env{'user.home'}; }
 2829: 
 2830:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2831:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2832: 
 2833:     my $namevalue='';
 2834:     foreach my $key (keys(%$storehash)) {
 2835:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2836:     }
 2837:     $namevalue=~s/\&$//;
 2838:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2839:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2840: }
 2841: 
 2842: # -------------------------------------------------------------- Critical Store
 2843: 
 2844: sub cstore {
 2845:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2846:     my $home='';
 2847: 
 2848:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2849: 
 2850:     $symb=&symbclean($symb);
 2851:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2852: 
 2853:     if (!$domain) { $domain=$env{'user.domain'}; }
 2854:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2855: 
 2856:     &devalidate($symb,$stuname,$domain);
 2857: 
 2858:     $symb=escape($symb);
 2859:     if (!$namespace) { 
 2860:        unless ($namespace=$env{'request.course.id'}) { 
 2861:           return ''; 
 2862:        } 
 2863:     }
 2864:     if (!$home) { $home=$env{'user.home'}; }
 2865: 
 2866:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2867:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2868: 
 2869:     my $namevalue='';
 2870:     foreach my $key (keys(%$storehash)) {
 2871:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2872:     }
 2873:     $namevalue=~s/\&$//;
 2874:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2875:     return critical
 2876:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2877: }
 2878: 
 2879: # --------------------------------------------------------------------- Restore
 2880: 
 2881: sub restore {
 2882:     my ($symb,$namespace,$domain,$stuname) = @_;
 2883:     my $home='';
 2884: 
 2885:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2886: 
 2887:     if (!$symb) {
 2888:       unless ($symb=escape(&symbread())) { return ''; }
 2889:     } else {
 2890:       $symb=&escape(&symbclean($symb));
 2891:     }
 2892:     if (!$namespace) { 
 2893:        unless ($namespace=$env{'request.course.id'}) { 
 2894:           return ''; 
 2895:        } 
 2896:     }
 2897:     if (!$domain) { $domain=$env{'user.domain'}; }
 2898:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2899:     if (!$home) { $home=$env{'user.home'}; }
 2900:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2901: 
 2902:     my %returnhash=();
 2903:     foreach my $line (split(/\&/,$answer)) {
 2904: 	my ($name,$value)=split(/\=/,$line);
 2905:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2906:     }
 2907:     my $version;
 2908:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2909:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2910:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2911:        }
 2912:     }
 2913:     return %returnhash;
 2914: }
 2915: 
 2916: # ---------------------------------------------------------- Course Description
 2917: 
 2918: sub coursedescription {
 2919:     my ($courseid,$args)=@_;
 2920:     $courseid=~s/^\///;
 2921:     $courseid=~s/\_/\//g;
 2922:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2923:     my $chome=&homeserver($cnum,$cdomain);
 2924:     my $normalid=$cdomain.'_'.$cnum;
 2925:     # need to always cache even if we get errors otherwise we keep 
 2926:     # trying and trying and trying to get the course description.
 2927:     my %envhash=();
 2928:     my %returnhash=();
 2929:     
 2930:     my $expiretime=600;
 2931:     if ($env{'request.course.id'} eq $normalid) {
 2932: 	$expiretime=120;
 2933:     }
 2934: 
 2935:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2936:     if (!$args->{'freshen_cache'}
 2937: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2938: 	foreach my $key (keys(%env)) {
 2939: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2940: 	    my ($setting) = $1;
 2941: 	    $returnhash{$setting} = $env{$key};
 2942: 	}
 2943: 	return %returnhash;
 2944:     }
 2945: 
 2946:     # get the data agin
 2947:     if (!$args->{'one_time'}) {
 2948: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2949:     }
 2950: 
 2951:     if ($chome ne 'no_host') {
 2952:        %returnhash=&dump('environment',$cdomain,$cnum);
 2953:        if (!exists($returnhash{'con_lost'})) {
 2954:            $returnhash{'home'}= $chome;
 2955: 	   $returnhash{'domain'} = $cdomain;
 2956: 	   $returnhash{'num'} = $cnum;
 2957:            if (!defined($returnhash{'type'})) {
 2958:                $returnhash{'type'} = 'Course';
 2959:            }
 2960:            while (my ($name,$value) = each %returnhash) {
 2961:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2962:            }
 2963:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2964:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2965: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2966:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2967:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2968:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2969:        }
 2970:     }
 2971:     if (!$args->{'one_time'}) {
 2972: 	&appenv(%envhash);
 2973:     }
 2974:     return %returnhash;
 2975: }
 2976: 
 2977: # -------------------------------------------------See if a user is privileged
 2978: 
 2979: sub privileged {
 2980:     my ($username,$domain)=@_;
 2981:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2982: 			&homeserver($username,$domain));
 2983:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2984:     my $now=time;
 2985:     if ($rolesdump ne '') {
 2986:         foreach my $entry (split(/&/,$rolesdump)) {
 2987: 	    if ($entry!~/^rolesdef_/) {
 2988: 		my ($area,$role)=split(/=/,$entry);
 2989: 		$area=~s/\_\w\w$//;
 2990: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2991: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2992: 		    my $active=1;
 2993: 		    if ($tend) {
 2994: 			if ($tend<$now) { $active=0; }
 2995: 		    }
 2996: 		    if ($tstart) {
 2997: 			if ($tstart>$now) { $active=0; }
 2998: 		    }
 2999: 		    if ($active) { return 1; }
 3000: 		}
 3001: 	    }
 3002: 	}
 3003:     }
 3004:     return 0;
 3005: }
 3006: 
 3007: # -------------------------------------------------------- Get user privileges
 3008: 
 3009: sub rolesinit {
 3010:     my ($domain,$username,$authhost)=@_;
 3011:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3012:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3013:     my %allroles=();
 3014:     my %allgroups=();   
 3015:     my $now=time;
 3016:     my %userroles = ('user.login.time' => $now);
 3017:     my $group_privs;
 3018: 
 3019:     if ($rolesdump ne '') {
 3020:         foreach my $entry (split(/&/,$rolesdump)) {
 3021: 	  if ($entry!~/^rolesdef_/) {
 3022:             my ($area,$role)=split(/=/,$entry);
 3023: 	    $area=~s/\_\w\w$//;
 3024:             my ($trole,$tend,$tstart,$group_privs);
 3025: 	    if ($role=~/^cr/) { 
 3026: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3027: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3028: 		    ($tend,$tstart)=split('_',$trest);
 3029: 		} else {
 3030: 		    $trole=$role;
 3031: 		}
 3032:             } elsif ($role =~ m|^gr/|) {
 3033:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3034:                 ($trole,$group_privs) = split(/\//,$trole);
 3035:                 $group_privs = &unescape($group_privs);
 3036: 	    } else {
 3037: 		($trole,$tend,$tstart)=split(/_/,$role);
 3038: 	    }
 3039: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3040: 					 $username);
 3041: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3042:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3043:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3044:             if (($area ne '') && ($trole ne '')) {
 3045: 		my $spec=$trole.'.'.$area;
 3046: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3047: 		if ($trole =~ /^cr\//) {
 3048:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3049:                 } elsif ($trole eq 'gr') {
 3050:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3051: 		} else {
 3052:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3053: 		}
 3054:             }
 3055:           }
 3056:         }
 3057:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3058:         $userroles{'user.adv'}    = $adv;
 3059: 	$userroles{'user.author'} = $author;
 3060:         $env{'user.adv'}=$adv;
 3061:     }
 3062:     return \%userroles;  
 3063: }
 3064: 
 3065: sub set_arearole {
 3066:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3067: # log the associated role with the area
 3068:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3069:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3070: }
 3071: 
 3072: sub custom_roleprivs {
 3073:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3074:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3075:     my $homsvr=homeserver($rauthor,$rdomain);
 3076:     if (&hostname($homsvr) ne '') {
 3077:         my ($rdummy,$roledef)=
 3078:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3079:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3080:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3081:             if (defined($syspriv)) {
 3082:                 $$allroles{'cm./'}.=':'.$syspriv;
 3083:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3084:             }
 3085:             if ($tdomain ne '') {
 3086:                 if (defined($dompriv)) {
 3087:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3088:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3089:                 }
 3090:                 if (($trest ne '') && (defined($coursepriv))) {
 3091:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3092:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3093:                 }
 3094:             }
 3095:         }
 3096:     }
 3097: }
 3098: 
 3099: sub group_roleprivs {
 3100:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3101:     my $access = 1;
 3102:     my $now = time;
 3103:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3104:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3105:     if ($access) {
 3106:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3107:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3108:     }
 3109: }
 3110: 
 3111: sub standard_roleprivs {
 3112:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3113:     if (defined($pr{$trole.':s'})) {
 3114:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3115:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3116:     }
 3117:     if ($tdomain ne '') {
 3118:         if (defined($pr{$trole.':d'})) {
 3119:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3120:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3121:         }
 3122:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3123:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3124:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3125:         }
 3126:     }
 3127: }
 3128: 
 3129: sub set_userprivs {
 3130:     my ($userroles,$allroles,$allgroups) = @_; 
 3131:     my $author=0;
 3132:     my $adv=0;
 3133:     my %grouproles = ();
 3134:     if (keys(%{$allgroups}) > 0) {
 3135:         foreach my $role (keys %{$allroles}) {
 3136:             my ($trole,$area,$sec,$extendedarea);
 3137:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3138:                 $trole = $1;
 3139:                 $area = $2;
 3140:                 $sec = $3;
 3141:                 $extendedarea = $area.$sec;
 3142:                 if (exists($$allgroups{$area})) {
 3143:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3144:                         my $spec = $trole.'.'.$extendedarea;
 3145:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3146:                                                 $$allgroups{$area}{$group};
 3147:                     }
 3148:                 }
 3149:             }
 3150:         }
 3151:     }
 3152:     foreach my $group (keys(%grouproles)) {
 3153:         $$allroles{$group} = $grouproles{$group};
 3154:     }
 3155:     foreach my $role (keys(%{$allroles})) {
 3156:         my %thesepriv;
 3157:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3158:         foreach my $item (split(/:/,$$allroles{$role})) {
 3159:             if ($item ne '') {
 3160:                 my ($privilege,$restrictions)=split(/&/,$item);
 3161:                 if ($restrictions eq '') {
 3162:                     $thesepriv{$privilege}='F';
 3163:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3164:                     $thesepriv{$privilege}.=$restrictions;
 3165:                 }
 3166:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3167:             }
 3168:         }
 3169:         my $thesestr='';
 3170:         foreach my $priv (keys(%thesepriv)) {
 3171: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3172: 	}
 3173:         $userroles->{'user.priv.'.$role} = $thesestr;
 3174:     }
 3175:     return ($author,$adv);
 3176: }
 3177: 
 3178: # --------------------------------------------------------------- get interface
 3179: 
 3180: sub get {
 3181:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3182:    my $items='';
 3183:    foreach my $item (@$storearr) {
 3184:        $items.=&escape($item).'&';
 3185:    }
 3186:    $items=~s/\&$//;
 3187:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3188:    if (!$uname) { $uname=$env{'user.name'}; }
 3189:    my $uhome=&homeserver($uname,$udomain);
 3190: 
 3191:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3192:    my @pairs=split(/\&/,$rep);
 3193:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3194:      return @pairs;
 3195:    }
 3196:    my %returnhash=();
 3197:    my $i=0;
 3198:    foreach my $item (@$storearr) {
 3199:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3200:       $i++;
 3201:    }
 3202:    return %returnhash;
 3203: }
 3204: 
 3205: # --------------------------------------------------------------- del interface
 3206: 
 3207: sub del {
 3208:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3209:    my $items='';
 3210:    foreach my $item (@$storearr) {
 3211:        $items.=&escape($item).'&';
 3212:    }
 3213:    $items=~s/\&$//;
 3214:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3215:    if (!$uname) { $uname=$env{'user.name'}; }
 3216:    my $uhome=&homeserver($uname,$udomain);
 3217: 
 3218:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3219: }
 3220: 
 3221: # -------------------------------------------------------------- dump interface
 3222: 
 3223: sub dump {
 3224:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3225:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3226:     if (!$uname) { $uname=$env{'user.name'}; }
 3227:     my $uhome=&homeserver($uname,$udomain);
 3228:     if ($regexp) {
 3229: 	$regexp=&escape($regexp);
 3230:     } else {
 3231: 	$regexp='.';
 3232:     }
 3233:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3234:     my @pairs=split(/\&/,$rep);
 3235:     my %returnhash=();
 3236:     foreach my $item (@pairs) {
 3237: 	my ($key,$value)=split(/=/,$item,2);
 3238: 	$key = &unescape($key);
 3239: 	next if ($key =~ /^error: 2 /);
 3240: 	$returnhash{$key}=&thaw_unescape($value);
 3241:     }
 3242:     return %returnhash;
 3243: }
 3244: 
 3245: # --------------------------------------------------------- dumpstore interface
 3246: 
 3247: sub dumpstore {
 3248:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3250:    if (!$uname) { $uname=$env{'user.name'}; }
 3251:    my $uhome=&homeserver($uname,$udomain);
 3252:    if ($regexp) {
 3253:        $regexp=&escape($regexp);
 3254:    } else {
 3255:        $regexp='.';
 3256:    }
 3257:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3258:    my @pairs=split(/\&/,$rep);
 3259:    my %returnhash=();
 3260:    foreach my $item (@pairs) {
 3261:        my ($key,$value)=split(/=/,$item,2);
 3262:        next if ($key =~ /^error: 2 /);
 3263:        $returnhash{$key}=&thaw_unescape($value);
 3264:    }
 3265:    return %returnhash;
 3266: }
 3267: 
 3268: # -------------------------------------------------------------- keys interface
 3269: 
 3270: sub getkeys {
 3271:    my ($namespace,$udomain,$uname)=@_;
 3272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3273:    if (!$uname) { $uname=$env{'user.name'}; }
 3274:    my $uhome=&homeserver($uname,$udomain);
 3275:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3276:    my @keyarray=();
 3277:    foreach my $key (split(/\&/,$rep)) {
 3278:       next if ($key =~ /^error: 2 /);
 3279:       push(@keyarray,&unescape($key));
 3280:    }
 3281:    return @keyarray;
 3282: }
 3283: 
 3284: # --------------------------------------------------------------- currentdump
 3285: sub currentdump {
 3286:    my ($courseid,$sdom,$sname)=@_;
 3287:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3288:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3289:    $sname    = $env{'user.name'}         if (! defined($sname));
 3290:    my $uhome = &homeserver($sname,$sdom);
 3291:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3292:    return if ($rep =~ /^(error:|no_such_host)/);
 3293:    #
 3294:    my %returnhash=();
 3295:    #
 3296:    if ($rep eq "unknown_cmd") { 
 3297:        # an old lond will not know currentdump
 3298:        # Do a dump and make it look like a currentdump
 3299:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3300:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3301:        my %hash = @tmp;
 3302:        @tmp=();
 3303:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3304:    } else {
 3305:        my @pairs=split(/\&/,$rep);
 3306:        foreach my $pair (@pairs) {
 3307:            my ($key,$value)=split(/=/,$pair,2);
 3308:            my ($symb,$param) = split(/:/,$key);
 3309:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3310:                                                         &thaw_unescape($value);
 3311:        }
 3312:    }
 3313:    return %returnhash;
 3314: }
 3315: 
 3316: sub convert_dump_to_currentdump{
 3317:     my %hash = %{shift()};
 3318:     my %returnhash;
 3319:     # Code ripped from lond, essentially.  The only difference
 3320:     # here is the unescaping done by lonnet::dump().  Conceivably
 3321:     # we might run in to problems with parameter names =~ /^v\./
 3322:     while (my ($key,$value) = each(%hash)) {
 3323:         my ($v,$symb,$param) = split(/:/,$key);
 3324: 	$symb  = &unescape($symb);
 3325: 	$param = &unescape($param);
 3326:         next if ($v eq 'version' || $symb eq 'keys');
 3327:         next if (exists($returnhash{$symb}) &&
 3328:                  exists($returnhash{$symb}->{$param}) &&
 3329:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3330:         $returnhash{$symb}->{$param}=$value;
 3331:         $returnhash{$symb}->{'v.'.$param}=$v;
 3332:     }
 3333:     #
 3334:     # Remove all of the keys in the hashes which keep track of
 3335:     # the version of the parameter.
 3336:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3337:         # use a foreach because we are going to delete from the hash.
 3338:         foreach my $key (keys(%$param_hash)) {
 3339:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3340:         }
 3341:     }
 3342:     return \%returnhash;
 3343: }
 3344: 
 3345: # ------------------------------------------------------ critical inc interface
 3346: 
 3347: sub cinc {
 3348:     return &inc(@_,'critical');
 3349: }
 3350: 
 3351: # --------------------------------------------------------------- inc interface
 3352: 
 3353: sub inc {
 3354:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3355:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3356:     if (!$uname) { $uname=$env{'user.name'}; }
 3357:     my $uhome=&homeserver($uname,$udomain);
 3358:     my $items='';
 3359:     if (! ref($store)) {
 3360:         # got a single value, so use that instead
 3361:         $items = &escape($store).'=&';
 3362:     } elsif (ref($store) eq 'SCALAR') {
 3363:         $items = &escape($$store).'=&';        
 3364:     } elsif (ref($store) eq 'ARRAY') {
 3365:         $items = join('=&',map {&escape($_);} @{$store});
 3366:     } elsif (ref($store) eq 'HASH') {
 3367:         while (my($key,$value) = each(%{$store})) {
 3368:             $items.= &escape($key).'='.&escape($value).'&';
 3369:         }
 3370:     }
 3371:     $items=~s/\&$//;
 3372:     if ($critical) {
 3373: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3374:     } else {
 3375: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3376:     }
 3377: }
 3378: 
 3379: # --------------------------------------------------------------- put interface
 3380: 
 3381: sub put {
 3382:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3383:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3384:    if (!$uname) { $uname=$env{'user.name'}; }
 3385:    my $uhome=&homeserver($uname,$udomain);
 3386:    my $items='';
 3387:    foreach my $item (keys(%$storehash)) {
 3388:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3389:    }
 3390:    $items=~s/\&$//;
 3391:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3392: }
 3393: 
 3394: # ------------------------------------------------------------ newput interface
 3395: 
 3396: sub newput {
 3397:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3398:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3399:    if (!$uname) { $uname=$env{'user.name'}; }
 3400:    my $uhome=&homeserver($uname,$udomain);
 3401:    my $items='';
 3402:    foreach my $key (keys(%$storehash)) {
 3403:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3404:    }
 3405:    $items=~s/\&$//;
 3406:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3407: }
 3408: 
 3409: # ---------------------------------------------------------  putstore interface
 3410: 
 3411: sub putstore {
 3412:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3413:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3414:    if (!$uname) { $uname=$env{'user.name'}; }
 3415:    my $uhome=&homeserver($uname,$udomain);
 3416:    my $items='';
 3417:    foreach my $key (keys(%$storehash)) {
 3418:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3419:    }
 3420:    $items=~s/\&$//;
 3421:    my $esc_symb=&escape($symb);
 3422:    my $esc_v=&escape($version);
 3423:    my $reply =
 3424:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3425: 	      $uhome);
 3426:    if ($reply eq 'unknown_cmd') {
 3427:        # gfall back to way things use to be done
 3428:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3429: 			    $uname);
 3430:    }
 3431:    return $reply;
 3432: }
 3433: 
 3434: sub old_putstore {
 3435:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3436:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3437:     if (!$uname) { $uname=$env{'user.name'}; }
 3438:     my $uhome=&homeserver($uname,$udomain);
 3439:     my %newstorehash;
 3440:     foreach my $item (keys(%$storehash)) {
 3441: 	my $key = $version.':'.&escape($symb).':'.$item;
 3442: 	$newstorehash{$key} = $storehash->{$item};
 3443:     }
 3444:     my $items='';
 3445:     my %allitems = ();
 3446:     foreach my $item (keys(%newstorehash)) {
 3447: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3448: 	    my $key = $1.':keys:'.$2;
 3449: 	    $allitems{$key} .= $3.':';
 3450: 	}
 3451: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3452:     }
 3453:     foreach my $item (keys(%allitems)) {
 3454: 	$allitems{$item} =~ s/\:$//;
 3455: 	$items.= $item.'='.$allitems{$item}.'&';
 3456:     }
 3457:     $items=~s/\&$//;
 3458:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3459: }
 3460: 
 3461: # ------------------------------------------------------ critical put interface
 3462: 
 3463: sub cput {
 3464:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3465:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3466:    if (!$uname) { $uname=$env{'user.name'}; }
 3467:    my $uhome=&homeserver($uname,$udomain);
 3468:    my $items='';
 3469:    foreach my $item (keys(%$storehash)) {
 3470:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3471:    }
 3472:    $items=~s/\&$//;
 3473:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3474: }
 3475: 
 3476: # -------------------------------------------------------------- eget interface
 3477: 
 3478: sub eget {
 3479:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3480:    my $items='';
 3481:    foreach my $item (@$storearr) {
 3482:        $items.=&escape($item).'&';
 3483:    }
 3484:    $items=~s/\&$//;
 3485:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3486:    if (!$uname) { $uname=$env{'user.name'}; }
 3487:    my $uhome=&homeserver($uname,$udomain);
 3488:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3489:    my @pairs=split(/\&/,$rep);
 3490:    my %returnhash=();
 3491:    my $i=0;
 3492:    foreach my $item (@$storearr) {
 3493:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3494:       $i++;
 3495:    }
 3496:    return %returnhash;
 3497: }
 3498: 
 3499: # ------------------------------------------------------------ tmpput interface
 3500: sub tmpput {
 3501:     my ($storehash,$server,$context)=@_;
 3502:     my $items='';
 3503:     foreach my $item (keys(%$storehash)) {
 3504: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3505:     }
 3506:     $items=~s/\&$//;
 3507:     if (defined($context)) {
 3508:         $items .= ':'.&escape($context);
 3509:     }
 3510:     return &reply("tmpput:$items",$server);
 3511: }
 3512: 
 3513: # ------------------------------------------------------------ tmpget interface
 3514: sub tmpget {
 3515:     my ($token,$server)=@_;
 3516:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3517:     my $rep=&reply("tmpget:$token",$server);
 3518:     my %returnhash;
 3519:     foreach my $item (split(/\&/,$rep)) {
 3520: 	my ($key,$value)=split(/=/,$item);
 3521: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3522:     }
 3523:     return %returnhash;
 3524: }
 3525: 
 3526: # ------------------------------------------------------------ tmpget interface
 3527: sub tmpdel {
 3528:     my ($token,$server)=@_;
 3529:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3530:     return &reply("tmpdel:$token",$server);
 3531: }
 3532: 
 3533: # -------------------------------------------------- portfolio access checking
 3534: 
 3535: sub portfolio_access {
 3536:     my ($requrl) = @_;
 3537:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3538:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3539:     if ($result) {
 3540:         my %setters;
 3541:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3542:             my ($startblock,$endblock) =
 3543:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3544:             if ($startblock && $endblock) {
 3545:                 return 'B';
 3546:             }
 3547:         } else {
 3548:             my ($startblock,$endblock) =
 3549:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3550:             if ($startblock && $endblock) {
 3551:                 return 'B';
 3552:             }
 3553:         }
 3554:     }
 3555:     if ($result eq 'ok') {
 3556:        return 'F';
 3557:     } elsif ($result =~ /^[^:]+:guest_/) {
 3558:        return 'A';
 3559:     }
 3560:     return '';
 3561: }
 3562: 
 3563: sub get_portfolio_access {
 3564:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3565: 
 3566:     if (!ref($access_hash)) {
 3567: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3568: 	my %access_controls = &get_access_controls($current_perms,$group,
 3569: 						   $file_name);
 3570: 	$access_hash = $access_controls{$file_name};
 3571:     }
 3572: 
 3573:     my ($public,$guest,@domains,@users,@courses,@groups);
 3574:     my $now = time;
 3575:     if (ref($access_hash) eq 'HASH') {
 3576:         foreach my $key (keys(%{$access_hash})) {
 3577:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3578:             if ($start > $now) {
 3579:                 next;
 3580:             }
 3581:             if ($end && $end<$now) {
 3582:                 next;
 3583:             }
 3584:             if ($scope eq 'public') {
 3585:                 $public = $key;
 3586:                 last;
 3587:             } elsif ($scope eq 'guest') {
 3588:                 $guest = $key;
 3589:             } elsif ($scope eq 'domains') {
 3590:                 push(@domains,$key);
 3591:             } elsif ($scope eq 'users') {
 3592:                 push(@users,$key);
 3593:             } elsif ($scope eq 'course') {
 3594:                 push(@courses,$key);
 3595:             } elsif ($scope eq 'group') {
 3596:                 push(@groups,$key);
 3597:             }
 3598:         }
 3599:         if ($public) {
 3600:             return 'ok';
 3601:         }
 3602:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3603:             if ($guest) {
 3604:                 return $guest;
 3605:             }
 3606:         } else {
 3607:             if (@domains > 0) {
 3608:                 foreach my $domkey (@domains) {
 3609:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3610:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3611:                             return 'ok';
 3612:                         }
 3613:                     }
 3614:                 }
 3615:             }
 3616:             if (@users > 0) {
 3617:                 foreach my $userkey (@users) {
 3618:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3619:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3620:                             if (ref($item) eq 'HASH') {
 3621:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3622:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3623:                                     return 'ok';
 3624:                                 }
 3625:                             }
 3626:                         }
 3627:                     } 
 3628:                 }
 3629:             }
 3630:             my %roleshash;
 3631:             my @courses_and_groups = @courses;
 3632:             push(@courses_and_groups,@groups); 
 3633:             if (@courses_and_groups > 0) {
 3634:                 my (%allgroups,%allroles); 
 3635:                 my ($start,$end,$role,$sec,$group);
 3636:                 foreach my $envkey (%env) {
 3637:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3638:                         my $cid = $2.'_'.$3; 
 3639:                         if ($1 eq 'gr') {
 3640:                             $group = $4;
 3641:                             $allgroups{$cid}{$group} = $env{$envkey};
 3642:                         } else {
 3643:                             if ($4 eq '') {
 3644:                                 $sec = 'none';
 3645:                             } else {
 3646:                                 $sec = $4;
 3647:                             }
 3648:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3649:                         }
 3650:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3651:                         my $cid = $2.'_'.$3;
 3652:                         if ($4 eq '') {
 3653:                             $sec = 'none';
 3654:                         } else {
 3655:                             $sec = $4;
 3656:                         }
 3657:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3658:                     }
 3659:                 }
 3660:                 if (keys(%allroles) == 0) {
 3661:                     return;
 3662:                 }
 3663:                 foreach my $key (@courses_and_groups) {
 3664:                     my %content = %{$$access_hash{$key}};
 3665:                     my $cnum = $content{'number'};
 3666:                     my $cdom = $content{'domain'};
 3667:                     my $cid = $cdom.'_'.$cnum;
 3668:                     if (!exists($allroles{$cid})) {
 3669:                         next;
 3670:                     }    
 3671:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3672:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3673:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3674:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3675:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3676:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3677:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3678:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3679:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3680:                                         if (grep/^all$/,@sections) {
 3681:                                             return 'ok';
 3682:                                         } else {
 3683:                                             if (grep/^$sec$/,@sections) {
 3684:                                                 return 'ok';
 3685:                                             }
 3686:                                         }
 3687:                                     }
 3688:                                 }
 3689:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3690:                                     if (grep/^none$/,@groups) {
 3691:                                         return 'ok';
 3692:                                     }
 3693:                                 } else {
 3694:                                     if (grep/^all$/,@groups) {
 3695:                                         return 'ok';
 3696:                                     } 
 3697:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3698:                                         if (grep/^$group$/,@groups) {
 3699:                                             return 'ok';
 3700:                                         }
 3701:                                     }
 3702:                                 } 
 3703:                             }
 3704:                         }
 3705:                     }
 3706:                 }
 3707:             }
 3708:             if ($guest) {
 3709:                 return $guest;
 3710:             }
 3711:         }
 3712:     }
 3713:     return;
 3714: }
 3715: 
 3716: sub course_group_datechecker {
 3717:     my ($dates,$now,$status) = @_;
 3718:     my ($start,$end) = split(/\./,$dates);
 3719:     if (!$start && !$end) {
 3720:         return 'ok';
 3721:     }
 3722:     if (grep/^active$/,@{$status}) {
 3723:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3724:             return 'ok';
 3725:         }
 3726:     }
 3727:     if (grep/^previous$/,@{$status}) {
 3728:         if ($end > $now ) {
 3729:             return 'ok';
 3730:         }
 3731:     }
 3732:     if (grep/^future$/,@{$status}) {
 3733:         if ($start > $now) {
 3734:             return 'ok';
 3735:         }
 3736:     }
 3737:     return; 
 3738: }
 3739: 
 3740: sub parse_portfolio_url {
 3741:     my ($url) = @_;
 3742: 
 3743:     my ($type,$udom,$unum,$group,$file_name);
 3744:     
 3745:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3746: 	$type = 1;
 3747:         $udom = $1;
 3748:         $unum = $2;
 3749:         $file_name = $3;
 3750:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3751: 	$type = 2;
 3752:         $udom = $1;
 3753:         $unum = $2;
 3754:         $group = $3;
 3755:         $file_name = $3.'/'.$4;
 3756:     }
 3757:     if (wantarray) {
 3758: 	return ($type,$udom,$unum,$file_name,$group);
 3759:     }
 3760:     return $type;
 3761: }
 3762: 
 3763: sub is_portfolio_url {
 3764:     my ($url) = @_;
 3765:     return scalar(&parse_portfolio_url($url));
 3766: }
 3767: 
 3768: sub is_portfolio_file {
 3769:     my ($file) = @_;
 3770:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3771:         return 1;
 3772:     }
 3773:     return;
 3774: }
 3775: 
 3776: 
 3777: # ---------------------------------------------- Custom access rule evaluation
 3778: 
 3779: sub customaccess {
 3780:     my ($priv,$uri)=@_;
 3781:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3782:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3783:     $udom = &LONCAPA::clean_domain($udom);
 3784:     $ucrs = &LONCAPA::clean_username($ucrs);
 3785:     my $access=0;
 3786:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3787: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3788:         if ($role) {
 3789: 	   if ($role ne $urole) { next; }
 3790:         }
 3791:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3792:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3793:             if ($tdom) {
 3794: 		if ($tdom ne $udom) { next; }
 3795:             }
 3796:             if ($tcrs) {
 3797: 		if ($tcrs ne $ucrs) { next; }
 3798:             }
 3799:             if ($tsec) {
 3800: 		if ($tsec ne $usec) { next; }
 3801:             }
 3802:             $access=($effect eq 'allow');
 3803:             last;
 3804:         }
 3805: 	if ($realm eq '' && $role eq '') {
 3806:             $access=($effect eq 'allow');
 3807: 	}
 3808:     }
 3809:     return $access;
 3810: }
 3811: 
 3812: # ------------------------------------------------- Check for a user privilege
 3813: 
 3814: sub allowed {
 3815:     my ($priv,$uri,$symb,$role)=@_;
 3816:     my $ver_orguri=$uri;
 3817:     $uri=&deversion($uri);
 3818:     my $orguri=$uri;
 3819:     $uri=&declutter($uri);
 3820: 
 3821:     if ($priv eq 'evb') {
 3822: # Evade communication block restrictions for specified role in a course
 3823:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3824:             return $1;
 3825:         } else {
 3826:             return;
 3827:         }
 3828:     }
 3829: 
 3830:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3831: # Free bre access to adm and meta resources
 3832:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3833: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3834: 	&& ($priv eq 'bre')) {
 3835: 	return 'F';
 3836:     }
 3837: 
 3838: # Free bre access to user's own portfolio contents
 3839:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3840:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3841: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3842:         my %setters;
 3843:         my ($startblock,$endblock) = 
 3844:             &Apache::loncommon::blockcheck(\%setters,'port');
 3845:         if ($startblock && $endblock) {
 3846:             return 'B';
 3847:         } else {
 3848:             return 'F';
 3849:         }
 3850:     }
 3851: 
 3852: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3853:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3854:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3855:         if (exists($env{'request.course.id'})) {
 3856:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3857:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3858:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3859:                 my $courseprivid=$env{'request.course.id'};
 3860:                 $courseprivid=~s/\_/\//;
 3861:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3862:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3863:                     return $1; 
 3864:                 } else {
 3865:                     if ($env{'request.course.sec'}) {
 3866:                         $courseprivid.='/'.$env{'request.course.sec'};
 3867:                     }
 3868:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3869:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3870:                         return $2;
 3871:                     }
 3872:                 }
 3873:             }
 3874:         }
 3875:     }
 3876: 
 3877: # Free bre to public access
 3878: 
 3879:     if ($priv eq 'bre') {
 3880:         my $copyright=&metadata($uri,'copyright');
 3881: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3882:            return 'F'; 
 3883:         }
 3884:         if ($copyright eq 'priv') {
 3885:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3886: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3887: 		return '';
 3888:             }
 3889:         }
 3890:         if ($copyright eq 'domain') {
 3891:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3892: 	    unless (($env{'user.domain'} eq $1) ||
 3893:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3894: 		return '';
 3895:             }
 3896:         }
 3897:         if ($env{'request.role'}=~ /li\.\//) {
 3898:             # Library role, so allow browsing of resources in this domain.
 3899:             return 'F';
 3900:         }
 3901:         if ($copyright eq 'custom') {
 3902: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3903:         }
 3904:     }
 3905:     # Domain coordinator is trying to create a course
 3906:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3907:         # uri is the requested domain in this case.
 3908:         # comparison to 'request.role.domain' shows if the user has selected
 3909:         # a role of dc for the domain in question.
 3910:         return 'F' if ($uri eq $env{'request.role.domain'});
 3911:     }
 3912: 
 3913:     my $thisallowed='';
 3914:     my $statecond=0;
 3915:     my $courseprivid='';
 3916: 
 3917: # Course
 3918: 
 3919:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3920:        $thisallowed.=$1;
 3921:     }
 3922: 
 3923: # Domain
 3924: 
 3925:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3926:        =~/\Q$priv\E\&([^\:]*)/) {
 3927:        $thisallowed.=$1;
 3928:     }
 3929: 
 3930: # Course: uri itself is a course
 3931:     my $courseuri=$uri;
 3932:     $courseuri=~s/\_(\d)/\/$1/;
 3933:     $courseuri=~s/^([^\/])/\/$1/;
 3934: 
 3935:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3936:        =~/\Q$priv\E\&([^\:]*)/) {
 3937:        $thisallowed.=$1;
 3938:     }
 3939: 
 3940: # URI is an uploaded document for this course, default permissions don't matter
 3941: # not allowing 'edit' access (editupload) to uploaded course docs
 3942:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3943: 	$thisallowed='';
 3944:         my ($match)=&is_on_map($uri);
 3945:         if ($match) {
 3946:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3947:                   =~/\Q$priv\E\&([^\:]*)/) {
 3948:                 $thisallowed.=$1;
 3949:             }
 3950:         } else {
 3951:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3952:             if ($refuri) {
 3953:                 if ($refuri =~ m|^/adm/|) {
 3954:                     $thisallowed='F';
 3955:                 } else {
 3956:                     $refuri=&declutter($refuri);
 3957:                     my ($match) = &is_on_map($refuri);
 3958:                     if ($match) {
 3959:                         $thisallowed='F';
 3960:                     }
 3961:                 }
 3962:             }
 3963:         }
 3964:     }
 3965: 
 3966:     if ($priv eq 'bre'
 3967: 	&& $thisallowed ne 'F' 
 3968: 	&& $thisallowed ne '2'
 3969: 	&& &is_portfolio_url($uri)) {
 3970: 	$thisallowed = &portfolio_access($uri);
 3971:     }
 3972:     
 3973: # Full access at system, domain or course-wide level? Exit.
 3974: 
 3975:     if ($thisallowed=~/F/) {
 3976: 	return 'F';
 3977:     }
 3978: 
 3979: # If this is generating or modifying users, exit with special codes
 3980: 
 3981:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3982: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3983: 	    my ($audom,$auname)=split('/',$uri);
 3984: # no author name given, so this just checks on the general right to make a co-author in this domain
 3985: 	    unless ($auname) { return $thisallowed; }
 3986: # an author name is given, so we are about to actually make a co-author for a certain account
 3987: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3988: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3989: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3990: 	}
 3991: 	return $thisallowed;
 3992:     }
 3993: #
 3994: # Gathered so far: system, domain and course wide privileges
 3995: #
 3996: # Course: See if uri or referer is an individual resource that is part of 
 3997: # the course
 3998: 
 3999:     if ($env{'request.course.id'}) {
 4000: 
 4001:        $courseprivid=$env{'request.course.id'};
 4002:        if ($env{'request.course.sec'}) {
 4003:           $courseprivid.='/'.$env{'request.course.sec'};
 4004:        }
 4005:        $courseprivid=~s/\_/\//;
 4006:        my $checkreferer=1;
 4007:        my ($match,$cond)=&is_on_map($uri);
 4008:        if ($match) {
 4009:            $statecond=$cond;
 4010:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4011:                =~/\Q$priv\E\&([^\:]*)/) {
 4012:                $thisallowed.=$1;
 4013:                $checkreferer=0;
 4014:            }
 4015:        }
 4016:        
 4017:        if ($checkreferer) {
 4018: 	  my $refuri=$env{'httpref.'.$orguri};
 4019:             unless ($refuri) {
 4020:                 foreach my $key (keys(%env)) {
 4021: 		    if ($key=~/^httpref\..*\*/) {
 4022: 			my $pattern=$key;
 4023:                         $pattern=~s/^httpref\.\/res\///;
 4024:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4025:                         $pattern=~s/\//\\\//g;
 4026:                         if ($orguri=~/$pattern/) {
 4027: 			    $refuri=$env{$key};
 4028:                         }
 4029:                     }
 4030:                 }
 4031:             }
 4032: 
 4033:          if ($refuri) { 
 4034: 	  $refuri=&declutter($refuri);
 4035:           my ($match,$cond)=&is_on_map($refuri);
 4036:             if ($match) {
 4037:               my $refstatecond=$cond;
 4038:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4039:                   =~/\Q$priv\E\&([^\:]*)/) {
 4040:                   $thisallowed.=$1;
 4041:                   $uri=$refuri;
 4042:                   $statecond=$refstatecond;
 4043:               }
 4044:           }
 4045:         }
 4046:        }
 4047:    }
 4048: 
 4049: #
 4050: # Gathered now: all privileges that could apply, and condition number
 4051: # 
 4052: #
 4053: # Full or no access?
 4054: #
 4055: 
 4056:     if ($thisallowed=~/F/) {
 4057: 	return 'F';
 4058:     }
 4059: 
 4060:     unless ($thisallowed) {
 4061:         return '';
 4062:     }
 4063: 
 4064: # Restrictions exist, deal with them
 4065: #
 4066: #   C:according to course preferences
 4067: #   R:according to resource settings
 4068: #   L:unless locked
 4069: #   X:according to user session state
 4070: #
 4071: 
 4072: # Possibly locked functionality, check all courses
 4073: # Locks might take effect only after 10 minutes cache expiration for other
 4074: # courses, and 2 minutes for current course
 4075: 
 4076:     my $envkey;
 4077:     if ($thisallowed=~/L/) {
 4078:         foreach $envkey (keys %env) {
 4079:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4080:                my $courseid=$2;
 4081:                my $roleid=$1.'.'.$2;
 4082:                $courseid=~s/^\///;
 4083:                my $expiretime=600;
 4084:                if ($env{'request.role'} eq $roleid) {
 4085: 		  $expiretime=120;
 4086:                }
 4087: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4088:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4089:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4090: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4091:                }
 4092:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4093:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4094: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4095:                        &log($env{'user.domain'},$env{'user.name'},
 4096:                             $env{'user.home'},
 4097:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4098:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4099:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4100: 		       return '';
 4101:                    }
 4102:                }
 4103:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4104:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4105: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4106:                        &log($env{'user.domain'},$env{'user.name'},
 4107:                             $env{'user.home'},
 4108:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4109:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4110:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4111: 		       return '';
 4112:                    }
 4113:                }
 4114: 	   }
 4115:        }
 4116:     }
 4117:    
 4118: #
 4119: # Rest of the restrictions depend on selected course
 4120: #
 4121: 
 4122:     unless ($env{'request.course.id'}) {
 4123: 	if ($thisallowed eq 'A') {
 4124: 	    return 'A';
 4125:         } elsif ($thisallowed eq 'B') {
 4126:             return 'B';
 4127: 	} else {
 4128: 	    return '1';
 4129: 	}
 4130:     }
 4131: 
 4132: #
 4133: # Now user is definitely in a course
 4134: #
 4135: 
 4136: 
 4137: # Course preferences
 4138: 
 4139:    if ($thisallowed=~/C/) {
 4140:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4141:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4142:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4143: 	   =~/\Q$rolecode\E/) {
 4144: 	   if ($priv ne 'pch') { 
 4145: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4146: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4147: 			$env{'request.course.id'});
 4148: 	   }
 4149:            return '';
 4150:        }
 4151: 
 4152:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4153: 	   =~/\Q$unamedom\E/) {
 4154: 	   if ($priv ne 'pch') { 
 4155: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4156: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4157: 			$env{'request.course.id'});
 4158: 	   }
 4159:            return '';
 4160:        }
 4161:    }
 4162: 
 4163: # Resource preferences
 4164: 
 4165:    if ($thisallowed=~/R/) {
 4166:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4167:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4168: 	   if ($priv ne 'pch') { 
 4169: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4170: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4171: 	   }
 4172: 	   return '';
 4173:        }
 4174:    }
 4175: 
 4176: # Restricted by state or randomout?
 4177: 
 4178:    if ($thisallowed=~/X/) {
 4179:       if ($env{'acc.randomout'}) {
 4180: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4181:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4182:             return ''; 
 4183:          }
 4184:       }
 4185:       if (&condval($statecond)) {
 4186: 	 return '2';
 4187:       } else {
 4188:          return '';
 4189:       }
 4190:    }
 4191: 
 4192:     if ($thisallowed eq 'A') {
 4193: 	return 'A';
 4194:     } elsif ($thisallowed eq 'B') {
 4195:         return 'B';
 4196:     }
 4197:    return 'F';
 4198: }
 4199: 
 4200: sub split_uri_for_cond {
 4201:     my $uri=&deversion(&declutter(shift));
 4202:     my @uriparts=split(/\//,$uri);
 4203:     my $filename=pop(@uriparts);
 4204:     my $pathname=join('/',@uriparts);
 4205:     return ($pathname,$filename);
 4206: }
 4207: # --------------------------------------------------- Is a resource on the map?
 4208: 
 4209: sub is_on_map {
 4210:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4211:     #Trying to find the conditional for the file
 4212:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4213: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4214:     if ($match) {
 4215: 	return (1,$1);
 4216:     } else {
 4217: 	return (0,0);
 4218:     }
 4219: }
 4220: 
 4221: # --------------------------------------------------------- Get symb from alias
 4222: 
 4223: sub get_symb_from_alias {
 4224:     my $symb=shift;
 4225:     my ($map,$resid,$url)=&decode_symb($symb);
 4226: # Already is a symb
 4227:     if ($url) { return $symb; }
 4228: # Must be an alias
 4229:     my $aliassymb='';
 4230:     my %bighash;
 4231:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4232:                             &GDBM_READER(),0640)) {
 4233:         my $rid=$bighash{'mapalias_'.$symb};
 4234: 	if ($rid) {
 4235: 	    my ($mapid,$resid)=split(/\./,$rid);
 4236: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4237: 				    $resid,$bighash{'src_'.$rid});
 4238: 	}
 4239:         untie %bighash;
 4240:     }
 4241:     return $aliassymb;
 4242: }
 4243: 
 4244: # ----------------------------------------------------------------- Define Role
 4245: 
 4246: sub definerole {
 4247:   if (allowed('mcr','/')) {
 4248:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4249:     foreach my $role (split(':',$sysrole)) {
 4250: 	my ($crole,$cqual)=split(/\&/,$role);
 4251:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4252:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4253: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4254:                return "refused:s:$crole&$cqual"; 
 4255:             }
 4256:         }
 4257:     }
 4258:     foreach my $role (split(':',$domrole)) {
 4259: 	my ($crole,$cqual)=split(/\&/,$role);
 4260:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4261:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4262: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4263:                return "refused:d:$crole&$cqual"; 
 4264:             }
 4265:         }
 4266:     }
 4267:     foreach my $role (split(':',$courole)) {
 4268: 	my ($crole,$cqual)=split(/\&/,$role);
 4269:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4270:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4271: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4272:                return "refused:c:$crole&$cqual"; 
 4273:             }
 4274:         }
 4275:     }
 4276:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4277:                 "$env{'user.domain'}:$env{'user.name'}:".
 4278: 	        "rolesdef_$rolename=".
 4279:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4280:     return reply($command,$env{'user.home'});
 4281:   } else {
 4282:     return 'refused';
 4283:   }
 4284: }
 4285: 
 4286: # ---------------- Make a metadata query against the network of library servers
 4287: 
 4288: sub metadata_query {
 4289:     my ($query,$custom,$customshow,$server_array)=@_;
 4290:     my %rhash;
 4291:     my %libserv = &all_library();
 4292:     my @server_list = (defined($server_array) ? @$server_array
 4293:                                               : keys(%libserv) );
 4294:     for my $server (@server_list) {
 4295: 	unless ($custom or $customshow) {
 4296: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4297: 	    $rhash{$server}=$reply;
 4298: 	}
 4299: 	else {
 4300: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4301: 			     &escape($custom).':'.&escape($customshow),
 4302: 			     $server);
 4303: 	    $rhash{$server}=$reply;
 4304: 	}
 4305:     }
 4306:     return \%rhash;
 4307: }
 4308: 
 4309: # ----------------------------------------- Send log queries and wait for reply
 4310: 
 4311: sub log_query {
 4312:     my ($uname,$udom,$query,%filters)=@_;
 4313:     my $uhome=&homeserver($uname,$udom);
 4314:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4315:     my $uhost=&hostname($uhome);
 4316:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4317:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4318:                        $uhome);
 4319:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4320:     return get_query_reply($queryid);
 4321: }
 4322: 
 4323: # -------------------------- Update MySQL table for portfolio file
 4324: 
 4325: sub update_portfolio_table {
 4326:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4327:     my $homeserver = &homeserver($uname,$udom);
 4328:     my $queryid=
 4329:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4330:                ':'.&escape($file_name).':'.$action,$homeserver);
 4331:     my $reply = &get_query_reply($queryid);
 4332:     return $reply;
 4333: }
 4334: 
 4335: # ------- Request retrieval of institutional classlists for course(s)
 4336: 
 4337: sub fetch_enrollment_query {
 4338:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4339:     my $homeserver;
 4340:     my $maxtries = 1;
 4341:     if ($context eq 'automated') {
 4342:         $homeserver = $perlvar{'lonHostID'};
 4343:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4344:     } else {
 4345:         $homeserver = &homeserver($cnum,$dom);
 4346:     }
 4347:     my $host=&hostname($homeserver);
 4348:     my $cmd = '';
 4349:     foreach my $affiliate (keys %{$affiliatesref}) {
 4350:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4351:     }
 4352:     $cmd =~ s/%%$//;
 4353:     $cmd = &escape($cmd);
 4354:     my $query = 'fetchenrollment';
 4355:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4356:     unless ($queryid=~/^\Q$host\E\_/) { 
 4357:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4358:         return 'error: '.$queryid;
 4359:     }
 4360:     my $reply = &get_query_reply($queryid);
 4361:     my $tries = 1;
 4362:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4363:         $reply = &get_query_reply($queryid);
 4364:         $tries ++;
 4365:     }
 4366:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4367:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4368:     } else {
 4369:         my @responses = split/:/,$reply;
 4370:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4371:             foreach my $line (@responses) {
 4372:                 my ($key,$value) = split(/=/,$line,2);
 4373:                 $$replyref{$key} = $value;
 4374:             }
 4375:         } else {
 4376:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4377:             foreach my $line (@responses) {
 4378:                 my ($key,$value) = split(/=/,$line);
 4379:                 $$replyref{$key} = $value;
 4380:                 if ($value > 0) {
 4381:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4382:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4383:                         my $destname = $pathname.'/'.$filename;
 4384:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4385:                         if ($xml_classlist =~ /^error/) {
 4386:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4387:                         } else {
 4388:                             if ( open(FILE,">$destname") ) {
 4389:                                 print FILE &unescape($xml_classlist);
 4390:                                 close(FILE);
 4391:                             } else {
 4392:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4393:                             }
 4394:                         }
 4395:                     }
 4396:                 }
 4397:             }
 4398:         }
 4399:         return 'ok';
 4400:     }
 4401:     return 'error';
 4402: }
 4403: 
 4404: sub get_query_reply {
 4405:     my $queryid=shift;
 4406:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4407:     my $reply='';
 4408:     for (1..100) {
 4409: 	sleep 2;
 4410:         if (-e $replyfile.'.end') {
 4411: 	    if (open(my $fh,$replyfile)) {
 4412:                $reply.=<$fh>;
 4413:                close($fh);
 4414: 	   } else { return 'error: reply_file_error'; }
 4415:            return &unescape($reply);
 4416: 	}
 4417:     }
 4418:     return 'timeout:'.$queryid;
 4419: }
 4420: 
 4421: sub courselog_query {
 4422: #
 4423: # possible filters:
 4424: # url: url or symb
 4425: # username
 4426: # domain
 4427: # action: view, submit, grade
 4428: # start: timestamp
 4429: # end: timestamp
 4430: #
 4431:     my (%filters)=@_;
 4432:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4433:     if ($filters{'url'}) {
 4434: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4435:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4436:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4437:     }
 4438:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4439:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4440:     return &log_query($cname,$cdom,'courselog',%filters);
 4441: }
 4442: 
 4443: sub userlog_query {
 4444: #
 4445: # possible filters:
 4446: # action: log check role
 4447: # start: timestamp
 4448: # end: timestamp
 4449: #
 4450:     my ($uname,$udom,%filters)=@_;
 4451:     return &log_query($uname,$udom,'userlog',%filters);
 4452: }
 4453: 
 4454: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4455: 
 4456: sub auto_run {
 4457:     my ($cnum,$cdom) = @_;
 4458:     my $homeserver = &homeserver($cnum,$cdom);
 4459:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4460:     return $response;
 4461: }
 4462: 
 4463: sub auto_get_sections {
 4464:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4465:     my $homeserver = &homeserver($cnum,$cdom);
 4466:     my @secs = ();
 4467:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4468:     unless ($response eq 'refused') {
 4469:         @secs = split/:/,$response;
 4470:     }
 4471:     return @secs;
 4472: }
 4473: 
 4474: sub auto_new_course {
 4475:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4476:     my $homeserver = &homeserver($cnum,$cdom);
 4477:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4478:     return $response;
 4479: }
 4480: 
 4481: sub auto_validate_courseID {
 4482:     my ($cnum,$cdom,$inst_course_id) = @_;
 4483:     my $homeserver = &homeserver($cnum,$cdom);
 4484:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4485:     return $response;
 4486: }
 4487: 
 4488: sub auto_create_password {
 4489:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4490:     my ($homeserver,$response);
 4491:     my $create_passwd = 0;
 4492:     my $authchk = '';
 4493:     if ($udom =~ /^$match_domain$/) {
 4494:         $homeserver = &domain($udom,'primary');
 4495:     }
 4496:     if ($homeserver eq '') {
 4497:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4498:             $homeserver = &homeserver($cnum,$cdom);
 4499:         }
 4500:     }
 4501:     if ($homeserver eq '') {
 4502:         $authchk = 'nodomain';
 4503:     } else {
 4504:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4505:         if ($response eq 'refused') {
 4506:             $authchk = 'refused';
 4507:         } else {
 4508:             ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4509:         }
 4510:     }
 4511:     return ($authparam,$create_passwd,$authchk);
 4512: }
 4513: 
 4514: sub auto_photo_permission {
 4515:     my ($cnum,$cdom,$students) = @_;
 4516:     my $homeserver = &homeserver($cnum,$cdom);
 4517:     my ($outcome,$perm_reqd,$conditions) = 
 4518: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4519:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4520: 	return (undef,undef);
 4521:     }
 4522:     return ($outcome,$perm_reqd,$conditions);
 4523: }
 4524: 
 4525: sub auto_checkphotos {
 4526:     my ($uname,$udom,$pid) = @_;
 4527:     my $homeserver = &homeserver($uname,$udom);
 4528:     my ($result,$resulttype);
 4529:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4530: 				   &escape($uname).':'.&escape($pid),
 4531: 				   $homeserver));
 4532:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4533: 	return (undef,undef);
 4534:     }
 4535:     if ($outcome) {
 4536:         ($result,$resulttype) = split(/:/,$outcome);
 4537:     } 
 4538:     return ($result,$resulttype);
 4539: }
 4540: 
 4541: sub auto_photochoice {
 4542:     my ($cnum,$cdom) = @_;
 4543:     my $homeserver = &homeserver($cnum,$cdom);
 4544:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4545: 						       &escape($cdom),
 4546: 						       $homeserver)));
 4547:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4548: 	return (undef,undef);
 4549:     }
 4550:     return ($update,$comment);
 4551: }
 4552: 
 4553: sub auto_photoupdate {
 4554:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4555:     my $homeserver = &homeserver($cnum,$dom);
 4556:     my $host=&hostname($homeserver);
 4557:     my $cmd = '';
 4558:     my $maxtries = 1;
 4559:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4560:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4561:     }
 4562:     $cmd =~ s/%%$//;
 4563:     $cmd = &escape($cmd);
 4564:     my $query = 'institutionalphotos';
 4565:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4566:     unless ($queryid=~/^\Q$host\E\_/) {
 4567:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4568:         return 'error: '.$queryid;
 4569:     }
 4570:     my $reply = &get_query_reply($queryid);
 4571:     my $tries = 1;
 4572:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4573:         $reply = &get_query_reply($queryid);
 4574:         $tries ++;
 4575:     }
 4576:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4577:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4578:     } else {
 4579:         my @responses = split(/:/,$reply);
 4580:         my $outcome = shift(@responses); 
 4581:         foreach my $item (@responses) {
 4582:             my ($key,$value) = split(/=/,$item);
 4583:             $$photo{$key} = $value;
 4584:         }
 4585:         return $outcome;
 4586:     }
 4587:     return 'error';
 4588: }
 4589: 
 4590: sub auto_instcode_format {
 4591:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4592: 	$cat_order) = @_;
 4593:     my $courses = '';
 4594:     my @homeservers;
 4595:     if ($caller eq 'global') {
 4596: 	my %servers = &get_servers($codedom,'library');
 4597: 	foreach my $tryserver (keys(%servers)) {
 4598: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4599: 		push(@homeservers,$tryserver);
 4600: 	    }
 4601:         }
 4602:     } else {
 4603:         push(@homeservers,&homeserver($caller,$codedom));
 4604:     }
 4605:     foreach my $code (keys(%{$instcodes})) {
 4606:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4607:     }
 4608:     chop($courses);
 4609:     my $ok_response = 0;
 4610:     my $response;
 4611:     while (@homeservers > 0 && $ok_response == 0) {
 4612:         my $server = shift(@homeservers); 
 4613:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4614:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4615:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4616: 		split/:/,$response;
 4617:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4618:             push(@{$codetitles},&str2array($codetitles_str));
 4619:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4620:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4621:             $ok_response = 1;
 4622:         }
 4623:     }
 4624:     if ($ok_response) {
 4625:         return 'ok';
 4626:     } else {
 4627:         return $response;
 4628:     }
 4629: }
 4630: 
 4631: sub auto_instcode_defaults {
 4632:     my ($domain,$returnhash,$code_order) = @_;
 4633:     my @homeservers;
 4634: 
 4635:     my %servers = &get_servers($domain,'library');
 4636:     foreach my $tryserver (keys(%servers)) {
 4637: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4638: 	    push(@homeservers,$tryserver);
 4639: 	}
 4640:     }
 4641: 
 4642:     my $response;
 4643:     foreach my $server (@homeservers) {
 4644:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4645:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4646: 	
 4647: 	foreach my $pair (split(/\&/,$response)) {
 4648: 	    my ($name,$value)=split(/\=/,$pair);
 4649: 	    if ($name eq 'code_order') {
 4650: 		@{$code_order} = split(/\&/,&unescape($value));
 4651: 	    } else {
 4652: 		$returnhash->{&unescape($name)}=&unescape($value);
 4653: 	    }
 4654: 	}
 4655: 	return 'ok';
 4656:     }
 4657: 
 4658:     return $response;
 4659: } 
 4660: 
 4661: sub auto_validate_class_sec {
 4662:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4663:     my $homeserver = &homeserver($cnum,$cdom);
 4664:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4665:                         &escape($owner).':'.$cdom,$homeserver);
 4666:     return $response;
 4667: }
 4668: 
 4669: # ------------------------------------------------------- Course Group routines
 4670: 
 4671: sub get_coursegroups {
 4672:     my ($cdom,$cnum,$group,$namespace) = @_;
 4673:     return(&dump($namespace,$cdom,$cnum,$group));
 4674: }
 4675: 
 4676: sub modify_coursegroup {
 4677:     my ($cdom,$cnum,$groupsettings) = @_;
 4678:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4679: }
 4680: 
 4681: sub toggle_coursegroup_status {
 4682:     my ($cdom,$cnum,$group,$action) = @_;
 4683:     my ($from_namespace,$to_namespace);
 4684:     if ($action eq 'delete') {
 4685:         $from_namespace = 'coursegroups';
 4686:         $to_namespace = 'deleted_groups';
 4687:     } else {
 4688:         $from_namespace = 'deleted_groups';
 4689:         $to_namespace = 'coursegroups';
 4690:     }
 4691:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4692:     if (my $tmp = &error(%curr_group)) {
 4693:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4694:         return ('read error',$tmp);
 4695:     } else {
 4696:         my %savedsettings = %curr_group; 
 4697:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4698:         my $deloutcome;
 4699:         if ($result eq 'ok') {
 4700:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4701:         } else {
 4702:             return ('write error',$result);
 4703:         }
 4704:         if ($deloutcome eq 'ok') {
 4705:             return 'ok';
 4706:         } else {
 4707:             return ('delete error',$deloutcome);
 4708:         }
 4709:     }
 4710: }
 4711: 
 4712: sub modify_group_roles {
 4713:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4714:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4715:     my $role = 'gr/'.&escape($userprivs);
 4716:     my ($uname,$udom) = split(/:/,$user);
 4717:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4718:     if ($result eq 'ok') {
 4719:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4720:     }
 4721:     return $result;
 4722: }
 4723: 
 4724: sub modify_coursegroup_membership {
 4725:     my ($cdom,$cnum,$membership) = @_;
 4726:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4727:     return $result;
 4728: }
 4729: 
 4730: sub get_active_groups {
 4731:     my ($udom,$uname,$cdom,$cnum) = @_;
 4732:     my $now = time;
 4733:     my %groups = ();
 4734:     foreach my $key (keys(%env)) {
 4735:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4736:             my ($start,$end) = split(/\./,$env{$key});
 4737:             if (($end!=0) && ($end<$now)) { next; }
 4738:             if (($start!=0) && ($start>$now)) { next; }
 4739:             if ($1 eq $cdom && $2 eq $cnum) {
 4740:                 $groups{$3} = $env{$key} ;
 4741:             }
 4742:         }
 4743:     }
 4744:     return %groups;
 4745: }
 4746: 
 4747: sub get_group_membership {
 4748:     my ($cdom,$cnum,$group) = @_;
 4749:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4750: }
 4751: 
 4752: sub get_users_groups {
 4753:     my ($udom,$uname,$courseid) = @_;
 4754:     my @usersgroups;
 4755:     my $cachetime=1800;
 4756: 
 4757:     my $hashid="$udom:$uname:$courseid";
 4758:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4759:     if (defined($cached)) {
 4760:         @usersgroups = split(/:/,$grouplist);
 4761:     } else {  
 4762:         $grouplist = '';
 4763:         my $courseurl = &courseid_to_courseurl($courseid);
 4764:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4765:         my $access_end = $env{'course.'.$courseid.
 4766:                               '.default_enrollment_end_date'};
 4767:         my $now = time;
 4768:         foreach my $key (keys(%roleshash)) {
 4769:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4770:                 my $group = $1;
 4771:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4772:                     my $start = $2;
 4773:                     my $end = $1;
 4774:                     if ($start == -1) { next; } # deleted from group
 4775:                     if (($start!=0) && ($start>$now)) { next; }
 4776:                     if (($end!=0) && ($end<$now)) {
 4777:                         if ($access_end && $access_end < $now) {
 4778:                             if ($access_end - $end < 86400) {
 4779:                                 push(@usersgroups,$group);
 4780:                             }
 4781:                         }
 4782:                         next;
 4783:                     }
 4784:                     push(@usersgroups,$group);
 4785:                 }
 4786:             }
 4787:         }
 4788:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4789:         $grouplist = join(':',@usersgroups);
 4790:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4791:     }
 4792:     return @usersgroups;
 4793: }
 4794: 
 4795: sub devalidate_getgroups_cache {
 4796:     my ($udom,$uname,$cdom,$cnum)=@_;
 4797:     my $courseid = $cdom.'_'.$cnum;
 4798: 
 4799:     my $hashid="$udom:$uname:$courseid";
 4800:     &devalidate_cache_new('getgroups',$hashid);
 4801: }
 4802: 
 4803: # ------------------------------------------------------------------ Plain Text
 4804: 
 4805: sub plaintext {
 4806:     my ($short,$type,$cid) = @_;
 4807:     if ($short =~ /^cr/) {
 4808: 	return (split('/',$short))[-1];
 4809:     }
 4810:     if (!defined($cid)) {
 4811:         $cid = $env{'request.course.id'};
 4812:     }
 4813:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4814:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4815:                                           '.plaintext'});
 4816:     }
 4817:     my %rolenames = (
 4818:                       Course => 'std',
 4819:                       Group => 'alt1',
 4820:                     );
 4821:     if (defined($type) && 
 4822:          defined($rolenames{$type}) && 
 4823:          defined($prp{$short}{$rolenames{$type}})) {
 4824:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4825:     } else {
 4826:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4827:     }
 4828: }
 4829: 
 4830: # ----------------------------------------------------------------- Assign Role
 4831: 
 4832: sub assignrole {
 4833:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4834:     my $mrole;
 4835:     if ($role =~ /^cr\//) {
 4836:         my $cwosec=$url;
 4837:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4838: 	unless (&allowed('ccr',$cwosec)) {
 4839:            &logthis('Refused custom assignrole: '.
 4840:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4841: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4842:            return 'refused'; 
 4843:         }
 4844:         $mrole='cr';
 4845:     } elsif ($role =~ /^gr\//) {
 4846:         my $cwogrp=$url;
 4847:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4848:         unless (&allowed('mdg',$cwogrp)) {
 4849:             &logthis('Refused group assignrole: '.
 4850:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4851:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4852:             return 'refused';
 4853:         }
 4854:         $mrole='gr';
 4855:     } else {
 4856:         my $cwosec=$url;
 4857:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4858:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4859:            &logthis('Refused assignrole: '.
 4860:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4861: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4862:            return 'refused'; 
 4863:         }
 4864:         $mrole=$role;
 4865:     }
 4866:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4867:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4868:     if ($end) { $command.='_'.$end; }
 4869:     if ($start) {
 4870: 	if ($end) { 
 4871:            $command.='_'.$start; 
 4872:         } else {
 4873:            $command.='_0_'.$start;
 4874:         }
 4875:     }
 4876:     my $origstart = $start;
 4877:     my $origend = $end;
 4878: # actually delete
 4879:     if ($deleteflag) {
 4880: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4881: # modify command to delete the role
 4882:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4883:                 "$udom:$uname:$url".'_'."$mrole";
 4884: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4885: # set start and finish to negative values for userrolelog
 4886:            $start=-1;
 4887:            $end=-1;
 4888:         }
 4889:     }
 4890: # send command
 4891:     my $answer=&reply($command,&homeserver($uname,$udom));
 4892: # log new user role if status is ok
 4893:     if ($answer eq 'ok') {
 4894: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4895: # for course roles, perform group memberships changes triggered by role change.
 4896:         unless ($role =~ /^gr/) {
 4897:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4898:                                              $origstart);
 4899:         }
 4900:     }
 4901:     return $answer;
 4902: }
 4903: 
 4904: # -------------------------------------------------- Modify user authentication
 4905: # Overrides without validation
 4906: 
 4907: sub modifyuserauth {
 4908:     my ($udom,$uname,$umode,$upass)=@_;
 4909:     my $uhome=&homeserver($uname,$udom);
 4910:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4911:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4912:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4913:              ' in domain '.$env{'request.role.domain'});  
 4914:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4915: 		     &escape($upass),$uhome);
 4916:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4917:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4918:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4919:     &log($udom,,$uname,$uhome,
 4920:         'Authentication changed by '.$env{'user.domain'}.', '.
 4921:                                      $env{'user.name'}.', '.$umode.
 4922:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4923:     unless ($reply eq 'ok') {
 4924:         &logthis('Authentication mode error: '.$reply);
 4925: 	return 'error: '.$reply;
 4926:     }   
 4927:     return 'ok';
 4928: }
 4929: 
 4930: # --------------------------------------------------------------- Modify a user
 4931: 
 4932: sub modifyuser {
 4933:     my ($udom,    $uname, $uid,
 4934:         $umode,   $upass, $first,
 4935:         $middle,  $last,  $gene,
 4936:         $forceid, $desiredhome, $email)=@_;
 4937:     $udom= &LONCAPA::clean_domain($udom);
 4938:     $uname=&LONCAPA::clean_username($uname);
 4939:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4940:              $umode.', '.$first.', '.$middle.', '.
 4941: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4942:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4943:                                      ' desiredhome not specified'). 
 4944:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4945:              ' in domain '.$env{'request.role.domain'});
 4946:     my $uhome=&homeserver($uname,$udom,'true');
 4947: # ----------------------------------------------------------------- Create User
 4948:     if (($uhome eq 'no_host') && 
 4949: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4950:         my $unhome='';
 4951:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4952:             $unhome = $desiredhome;
 4953: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4954: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4955:         } else { # load balancing routine for determining $unhome
 4956:             my $loadm=10000000;
 4957: 	    my %servers = &get_servers($udom,'library');
 4958: 	    foreach my $tryserver (keys(%servers)) {
 4959: 		my $answer=reply('load',$tryserver);
 4960: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4961: 		    $loadm=$answer;
 4962: 		    $unhome=$tryserver;
 4963: 		}
 4964: 	    }
 4965:         }
 4966:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4967: 	    return 'error: unable to find a home server for '.$uname.
 4968:                    ' in domain '.$udom;
 4969:         }
 4970:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4971:                          &escape($upass),$unhome);
 4972: 	unless ($reply eq 'ok') {
 4973:             return 'error: '.$reply;
 4974:         }   
 4975:         $uhome=&homeserver($uname,$udom,'true');
 4976:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4977: 	    return 'error: unable verify users home machine.';
 4978:         }
 4979:     }   # End of creation of new user
 4980: # ---------------------------------------------------------------------- Add ID
 4981:     if ($uid) {
 4982:        $uid=~tr/A-Z/a-z/;
 4983:        my %uidhash=&idrget($udom,$uname);
 4984:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4985:          && (!$forceid)) {
 4986: 	  unless ($uid eq $uidhash{$uname}) {
 4987: 	      return 'error: user id "'.$uid.'" does not match '.
 4988:                   'current user id "'.$uidhash{$uname}.'".';
 4989:           }
 4990:        } else {
 4991: 	  &idput($udom,($uname => $uid));
 4992:        }
 4993:     }
 4994: # -------------------------------------------------------------- Add names, etc
 4995:     my @tmp=&get('environment',
 4996: 		   ['firstname','middlename','lastname','generation'],
 4997: 		   $udom,$uname);
 4998:     my %names;
 4999:     if ($tmp[0] =~ m/^error:.*/) { 
 5000:         %names=(); 
 5001:     } else {
 5002:         %names = @tmp;
 5003:     }
 5004: #
 5005: # Make sure to not trash student environment if instructor does not bother
 5006: # to supply name and email information
 5007: #
 5008:     if ($first)  { $names{'firstname'}  = $first; }
 5009:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5010:     if ($last)   { $names{'lastname'}   = $last; }
 5011:     if (defined($gene))   { $names{'generation'} = $gene; }
 5012:     if ($email) {
 5013:        $email=~s/[^\w\@\.\-\,]//gs;
 5014:        if ($email=~/\@/) { $names{'notification'} = $email;
 5015: 			   $names{'critnotification'} = $email;
 5016: 			   $names{'permanentemail'} = $email; }
 5017:     }
 5018:     my $reply = &put('environment', \%names, $udom,$uname);
 5019:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5020:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5021:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5022:              $umode.', '.$first.', '.$middle.', '.
 5023: 	     $last.', '.$gene.' by '.
 5024:              $env{'user.name'}.' at '.$env{'user.domain'});
 5025:     return 'ok';
 5026: }
 5027: 
 5028: # -------------------------------------------------------------- Modify student
 5029: 
 5030: sub modifystudent {
 5031:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5032:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5033:     if (!$cid) {
 5034: 	unless ($cid=$env{'request.course.id'}) {
 5035: 	    return 'not_in_class';
 5036: 	}
 5037:     }
 5038: # --------------------------------------------------------------- Make the user
 5039:     my $reply=&modifyuser
 5040: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5041:          $desiredhome,$email);
 5042:     unless ($reply eq 'ok') { return $reply; }
 5043:     # This will cause &modify_student_enrollment to get the uid from the
 5044:     # students environment
 5045:     $uid = undef if (!$forceid);
 5046:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5047: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5048:     return $reply;
 5049: }
 5050: 
 5051: sub modify_student_enrollment {
 5052:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5053:     my ($cdom,$cnum,$chome);
 5054:     if (!$cid) {
 5055: 	unless ($cid=$env{'request.course.id'}) {
 5056: 	    return 'not_in_class';
 5057: 	}
 5058: 	$cdom=$env{'course.'.$cid.'.domain'};
 5059: 	$cnum=$env{'course.'.$cid.'.num'};
 5060:     } else {
 5061: 	($cdom,$cnum)=split(/_/,$cid);
 5062:     }
 5063:     $chome=$env{'course.'.$cid.'.home'};
 5064:     if (!$chome) {
 5065: 	$chome=&homeserver($cnum,$cdom);
 5066:     }
 5067:     if (!$chome) { return 'unknown_course'; }
 5068:     # Make sure the user exists
 5069:     my $uhome=&homeserver($uname,$udom);
 5070:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5071: 	return 'error: no such user';
 5072:     }
 5073:     # Get student data if we were not given enough information
 5074:     if (!defined($first)  || $first  eq '' || 
 5075:         !defined($last)   || $last   eq '' || 
 5076:         !defined($uid)    || $uid    eq '' || 
 5077:         !defined($middle) || $middle eq '' || 
 5078:         !defined($gene)   || $gene   eq '') {
 5079:         # They did not supply us with enough data to enroll the student, so
 5080:         # we need to pick up more information.
 5081:         my %tmp = &get('environment',
 5082:                        ['firstname','middlename','lastname', 'generation','id']
 5083:                        ,$udom,$uname);
 5084: 
 5085:         #foreach my $key (keys(%tmp)) {
 5086:         #    &logthis("key $key = ".$tmp{$key});
 5087:         #}
 5088:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5089:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5090:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5091:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5092:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5093:     }
 5094:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5095:     my $reply=cput('classlist',
 5096: 		   {"$uname:$udom" => 
 5097: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5098: 		   $cdom,$cnum);
 5099:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5100: 	return 'error: '.$reply;
 5101:     } else {
 5102: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5103:     }
 5104:     # Add student role to user
 5105:     my $uurl='/'.$cid;
 5106:     $uurl=~s/\_/\//g;
 5107:     if ($usec) {
 5108: 	$uurl.='/'.$usec;
 5109:     }
 5110:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5111: }
 5112: 
 5113: sub format_name {
 5114:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5115:     my $name;
 5116:     if ($first ne 'lastname') {
 5117: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5118:     } else {
 5119: 	if ($lastname=~/\S/) {
 5120: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5121: 	    $name=~s/\s+,/,/;
 5122: 	} else {
 5123: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5124: 	}
 5125:     }
 5126:     $name=~s/^\s+//;
 5127:     $name=~s/\s+$//;
 5128:     $name=~s/\s+/ /g;
 5129:     return $name;
 5130: }
 5131: 
 5132: # ------------------------------------------------- Write to course preferences
 5133: 
 5134: sub writecoursepref {
 5135:     my ($courseid,%prefs)=@_;
 5136:     $courseid=~s/^\///;
 5137:     $courseid=~s/\_/\//g;
 5138:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5139:     my $chome=homeserver($cnum,$cdomain);
 5140:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5141: 	return 'error: no such course';
 5142:     }
 5143:     my $cstring='';
 5144:     foreach my $pref (keys(%prefs)) {
 5145: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5146:     }
 5147:     $cstring=~s/\&$//;
 5148:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5149: }
 5150: 
 5151: # ---------------------------------------------------------- Make/modify course
 5152: 
 5153: sub createcourse {
 5154:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5155:         $course_owner,$crstype)=@_;
 5156:     $url=&declutter($url);
 5157:     my $cid='';
 5158:     unless (&allowed('ccc',$udom)) {
 5159:         return 'refused';
 5160:     }
 5161: # ------------------------------------------------------------------- Create ID
 5162:    my $uname=int(1+rand(9)).
 5163:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5164:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5165:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5166: # ----------------------------------------------- Make sure that does not exist
 5167:    my $uhome=&homeserver($uname,$udom,'true');
 5168:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5169:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5170:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5171:        $uhome=&homeserver($uname,$udom,'true');       
 5172:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5173:            return 'error: unable to generate unique course-ID';
 5174:        } 
 5175:    }
 5176: # ------------------------------------------------ Check supplied server name
 5177:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5178:     if (! &is_library($course_server)) {
 5179:         return 'error:bad server name '.$course_server;
 5180:     }
 5181: # ------------------------------------------------------------- Make the course
 5182:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5183:                       $course_server);
 5184:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5185:     $uhome=&homeserver($uname,$udom,'true');
 5186:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5187: 	return 'error: no such course';
 5188:     }
 5189: # ----------------------------------------------------------------- Course made
 5190: # log existence
 5191:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5192:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5193:                   &escape($crstype),$uhome);
 5194:     &flushcourselogs();
 5195: # set toplevel url
 5196:     my $topurl=$url;
 5197:     unless ($nonstandard) {
 5198: # ------------------------------------------ For standard courses, make top url
 5199:         my $mapurl=&clutter($url);
 5200:         if ($mapurl eq '/res/') { $mapurl=''; }
 5201:         $env{'form.initmap'}=(<<ENDINITMAP);
 5202: <map>
 5203: <resource id="1" type="start"></resource>
 5204: <resource id="2" src="$mapurl"></resource>
 5205: <resource id="3" type="finish"></resource>
 5206: <link index="1" from="1" to="2"></link>
 5207: <link index="2" from="2" to="3"></link>
 5208: </map>
 5209: ENDINITMAP
 5210:         $topurl=&declutter(
 5211:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5212:                           );
 5213:     }
 5214: # ----------------------------------------------------------- Write preferences
 5215:     &writecoursepref($udom.'_'.$uname,
 5216:                      ('description' => $description,
 5217:                       'url'         => $topurl));
 5218:     return '/'.$udom.'/'.$uname;
 5219: }
 5220: 
 5221: sub is_course {
 5222:     my ($cdom,$cnum) = @_;
 5223:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5224: 				undef,'.');
 5225:     if (exists($courses{$cdom.'_'.$cnum})) {
 5226:         return 1;
 5227:     }
 5228:     return 0;
 5229: }
 5230: 
 5231: # ---------------------------------------------------------- Assign Custom Role
 5232: 
 5233: sub assigncustomrole {
 5234:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5235:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5236:                        $end,$start,$deleteflag);
 5237: }
 5238: 
 5239: # ----------------------------------------------------------------- Revoke Role
 5240: 
 5241: sub revokerole {
 5242:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5243:     my $now=time;
 5244:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5245: }
 5246: 
 5247: # ---------------------------------------------------------- Revoke Custom Role
 5248: 
 5249: sub revokecustomrole {
 5250:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5251:     my $now=time;
 5252:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5253:            $deleteflag);
 5254: }
 5255: 
 5256: # ------------------------------------------------------------ Disk usage
 5257: sub diskusage {
 5258:     my ($udom,$uname,$directoryRoot)=@_;
 5259:     $directoryRoot =~ s/\/$//;
 5260:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5261:     return $listing;
 5262: }
 5263: 
 5264: sub is_locked {
 5265:     my ($file_name, $domain, $user) = @_;
 5266:     my @check;
 5267:     my $is_locked;
 5268:     push @check, $file_name;
 5269:     my %locked = &get('file_permissions',\@check,
 5270: 		      $env{'user.domain'},$env{'user.name'});
 5271:     my ($tmp)=keys(%locked);
 5272:     if ($tmp=~/^error:/) { undef(%locked); }
 5273:     
 5274:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5275:         $is_locked = 'false';
 5276:         foreach my $entry (@{$locked{$file_name}}) {
 5277:            if (ref($entry) eq 'ARRAY') { 
 5278:                $is_locked = 'true';
 5279:                last;
 5280:            }
 5281:        }
 5282:     } else {
 5283:         $is_locked = 'false';
 5284:     }
 5285: }
 5286: 
 5287: sub declutter_portfile {
 5288:     my ($file) = @_;
 5289:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5290:     return $file;
 5291: }
 5292: 
 5293: # ------------------------------------------------------------- Mark as Read Only
 5294: 
 5295: sub mark_as_readonly {
 5296:     my ($domain,$user,$files,$what) = @_;
 5297:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5298:     my ($tmp)=keys(%current_permissions);
 5299:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5300:     foreach my $file (@{$files}) {
 5301: 	$file = &declutter_portfile($file);
 5302:         push(@{$current_permissions{$file}},$what);
 5303:     }
 5304:     &put('file_permissions',\%current_permissions,$domain,$user);
 5305:     return;
 5306: }
 5307: 
 5308: # ------------------------------------------------------------Save Selected Files
 5309: 
 5310: sub save_selected_files {
 5311:     my ($user, $path, @files) = @_;
 5312:     my $filename = $user."savedfiles";
 5313:     my @other_files = &files_not_in_path($user, $path);
 5314:     open (OUT, '>'.$tmpdir.$filename);
 5315:     foreach my $file (@files) {
 5316:         print (OUT $env{'form.currentpath'}.$file."\n");
 5317:     }
 5318:     foreach my $file (@other_files) {
 5319:         print (OUT $file."\n");
 5320:     }
 5321:     close (OUT);
 5322:     return 'ok';
 5323: }
 5324: 
 5325: sub clear_selected_files {
 5326:     my ($user) = @_;
 5327:     my $filename = $user."savedfiles";
 5328:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5329:     print (OUT undef);
 5330:     close (OUT);
 5331:     return ("ok");    
 5332: }
 5333: 
 5334: sub files_in_path {
 5335:     my ($user, $path) = @_;
 5336:     my $filename = $user."savedfiles";
 5337:     my %return_files;
 5338:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5339:     while (my $line_in = <IN>) {
 5340:         chomp ($line_in);
 5341:         my @paths_and_file = split (m!/!, $line_in);
 5342:         my $file_part = pop (@paths_and_file);
 5343:         my $path_part = join ('/', @paths_and_file);
 5344:         $path_part.='/';
 5345:         my $path_and_file = $path_part.$file_part;
 5346:         if ($path_part eq $path) {
 5347:             $return_files{$file_part}= 'selected';
 5348:         }
 5349:     }
 5350:     close (IN);
 5351:     return (\%return_files);
 5352: }
 5353: 
 5354: # called in portfolio select mode, to show files selected NOT in current directory
 5355: sub files_not_in_path {
 5356:     my ($user, $path) = @_;
 5357:     my $filename = $user."savedfiles";
 5358:     my @return_files;
 5359:     my $path_part;
 5360:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5361:     while (my $line = <IN>) {
 5362:         #ok, I know it's clunky, but I want it to work
 5363:         my @paths_and_file = split(m|/|, $line);
 5364:         my $file_part = pop(@paths_and_file);
 5365:         chomp($file_part);
 5366:         my $path_part = join('/', @paths_and_file);
 5367:         $path_part .= '/';
 5368:         my $path_and_file = $path_part.$file_part;
 5369:         if ($path_part ne $path) {
 5370:             push(@return_files, ($path_and_file));
 5371:         }
 5372:     }
 5373:     close(OUT);
 5374:     return (@return_files);
 5375: }
 5376: 
 5377: #----------------------------------------------Get portfolio file permissions
 5378: 
 5379: sub get_portfile_permissions {
 5380:     my ($domain,$user) = @_;
 5381:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5382:     my ($tmp)=keys(%current_permissions);
 5383:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5384:     return \%current_permissions;
 5385: }
 5386: 
 5387: #---------------------------------------------Get portfolio file access controls
 5388: 
 5389: sub get_access_controls {
 5390:     my ($current_permissions,$group,$file) = @_;
 5391:     my %access;
 5392:     my $real_file = $file;
 5393:     $file =~ s/\.meta$//;
 5394:     if (defined($file)) {
 5395:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5396:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5397:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5398:             }
 5399:         }
 5400:     } else {
 5401:         foreach my $key (keys(%{$current_permissions})) {
 5402:             if ($key =~ /\0accesscontrol$/) {
 5403:                 if (defined($group)) {
 5404:                     if ($key !~ m-^\Q$group\E/-) {
 5405:                         next;
 5406:                     }
 5407:                 }
 5408:                 my ($fullpath) = split(/\0/,$key);
 5409:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5410:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5411:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5412:                     }
 5413:                 }
 5414:             }
 5415:         }
 5416:     }
 5417:     return %access;
 5418: }
 5419: 
 5420: sub modify_access_controls {
 5421:     my ($file_name,$changes,$domain,$user)=@_;
 5422:     my ($outcome,$deloutcome);
 5423:     my %store_permissions;
 5424:     my %new_values;
 5425:     my %new_control;
 5426:     my %translation;
 5427:     my @deletions = ();
 5428:     my $now = time;
 5429:     if (exists($$changes{'activate'})) {
 5430:         if (ref($$changes{'activate'}) eq 'HASH') {
 5431:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5432:             my $numnew = scalar(@newitems);
 5433:             for (my $i=0; $i<$numnew; $i++) {
 5434:                 my $newkey = $newitems[$i];
 5435:                 my $newid = &Apache::loncommon::get_cgi_id();
 5436:                 if ($newkey =~ /^\d+:/) { 
 5437:                     $newkey =~ s/^(\d+)/$newid/;
 5438:                     $translation{$1} = $newid;
 5439:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5440:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5441:                     $translation{$1} = $newid;
 5442:                 }
 5443:                 $new_values{$file_name."\0".$newkey} = 
 5444:                                           $$changes{'activate'}{$newitems[$i]};
 5445:                 $new_control{$newkey} = $now;
 5446:             }
 5447:         }
 5448:     }
 5449:     my %todelete;
 5450:     my %changed_items;
 5451:     foreach my $action ('delete','update') {
 5452:         if (exists($$changes{$action})) {
 5453:             if (ref($$changes{$action}) eq 'HASH') {
 5454:                 foreach my $key (keys(%{$$changes{$action}})) {
 5455:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5456:                     if ($action eq 'delete') { 
 5457:                         $todelete{$itemnum} = 1;
 5458:                     } else {
 5459:                         $changed_items{$itemnum} = $key;
 5460:                     }
 5461:                 }
 5462:             }
 5463:         }
 5464:     }
 5465:     # get lock on access controls for file.
 5466:     my $lockhash = {
 5467:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5468:                                                        ':'.$env{'user.domain'},
 5469:                    }; 
 5470:     my $tries = 0;
 5471:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5472:    
 5473:     while (($gotlock ne 'ok') && $tries <3) {
 5474:         $tries ++;
 5475:         sleep 1;
 5476:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5477:     }
 5478:     if ($gotlock eq 'ok') {
 5479:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5480:         my ($tmp)=keys(%curr_permissions);
 5481:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5482:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5483:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5484:             if (ref($curr_controls) eq 'HASH') {
 5485:                 foreach my $control_item (keys(%{$curr_controls})) {
 5486:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5487:                     if (defined($todelete{$itemnum})) {
 5488:                         push(@deletions,$file_name."\0".$control_item);
 5489:                     } else {
 5490:                         if (defined($changed_items{$itemnum})) {
 5491:                             $new_control{$changed_items{$itemnum}} = $now;
 5492:                             push(@deletions,$file_name."\0".$control_item);
 5493:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5494:                         } else {
 5495:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5496:                         }
 5497:                     }
 5498:                 }
 5499:             }
 5500:         }
 5501:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5502:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5503:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5504:         #  remove lock
 5505:         my @del_lock = ($file_name."\0".'locked_access_records');
 5506:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5507:         my ($file,$group);
 5508:         if (&is_course($domain,$user)) {
 5509:             ($group,$file) = split(/\//,$file_name,2);
 5510:         } else {
 5511:             $file = $file_name;
 5512:         }
 5513:         my $sqlresult =
 5514:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5515:                                     $group);
 5516:     } else {
 5517:         $outcome = "error: could not obtain lockfile\n";  
 5518:     }
 5519:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5520: }
 5521: 
 5522: sub make_public_indefinitely {
 5523:     my ($requrl) = @_;
 5524:     my $now = time;
 5525:     my $action = 'activate';
 5526:     my $aclnum = 0;
 5527:     if (&is_portfolio_url($requrl)) {
 5528:         my (undef,$udom,$unum,$file_name,$group) =
 5529:             &parse_portfolio_url($requrl);
 5530:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5531:         my %access_controls = &get_access_controls($current_perms,
 5532:                                                    $group,$file_name);
 5533:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5534:             my ($num,$scope,$end,$start) = 
 5535:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5536:             if ($scope eq 'public') {
 5537:                 if ($start <= $now && $end == 0) {
 5538:                     $action = 'none';
 5539:                 } else {
 5540:                     $action = 'update';
 5541:                     $aclnum = $num;
 5542:                 }
 5543:                 last;
 5544:             }
 5545:         }
 5546:         if ($action eq 'none') {
 5547:              return 'ok';
 5548:         } else {
 5549:             my %changes;
 5550:             my $newend = 0;
 5551:             my $newstart = $now;
 5552:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5553:             $changes{$action}{$newkey} = {
 5554:                 type => 'public',
 5555:                 time => {
 5556:                     start => $newstart,
 5557:                     end   => $newend,
 5558:                 },
 5559:             };
 5560:             my ($outcome,$deloutcome,$new_values,$translation) =
 5561:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5562:             return $outcome;
 5563:         }
 5564:     } else {
 5565:         return 'invalid';
 5566:     }
 5567: }
 5568: 
 5569: #------------------------------------------------------Get Marked as Read Only
 5570: 
 5571: sub get_marked_as_readonly {
 5572:     my ($domain,$user,$what,$group) = @_;
 5573:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5574:     my @readonly_files;
 5575:     my $cmp1=$what;
 5576:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5577:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5578:         if (defined($group)) {
 5579:             if ($file_name !~ m-^\Q$group\E/-) {
 5580:                 next;
 5581:             }
 5582:         }
 5583:         if (ref($value) eq "ARRAY"){
 5584:             foreach my $stored_what (@{$value}) {
 5585:                 my $cmp2=$stored_what;
 5586:                 if (ref($stored_what) eq 'ARRAY') {
 5587:                     $cmp2=join('',@{$stored_what});
 5588:                 }
 5589:                 if ($cmp1 eq $cmp2) {
 5590:                     push(@readonly_files, $file_name);
 5591:                     last;
 5592:                 } elsif (!defined($what)) {
 5593:                     push(@readonly_files, $file_name);
 5594:                     last;
 5595:                 }
 5596:             }
 5597:         }
 5598:     }
 5599:     return @readonly_files;
 5600: }
 5601: #-----------------------------------------------------------Get Marked as Read Only Hash
 5602: 
 5603: sub get_marked_as_readonly_hash {
 5604:     my ($current_permissions,$group,$what) = @_;
 5605:     my %readonly_files;
 5606:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5607:         if (defined($group)) {
 5608:             if ($file_name !~ m-^\Q$group\E/-) {
 5609:                 next;
 5610:             }
 5611:         }
 5612:         if (ref($value) eq "ARRAY"){
 5613:             foreach my $stored_what (@{$value}) {
 5614:                 if (ref($stored_what) eq 'ARRAY') {
 5615:                     foreach my $lock_descriptor(@{$stored_what}) {
 5616:                         if ($lock_descriptor eq 'graded') {
 5617:                             $readonly_files{$file_name} = 'graded';
 5618:                         } elsif ($lock_descriptor eq 'handback') {
 5619:                             $readonly_files{$file_name} = 'handback';
 5620:                         } else {
 5621:                             if (!exists($readonly_files{$file_name})) {
 5622:                                 $readonly_files{$file_name} = 'locked';
 5623:                             }
 5624:                         }
 5625:                     }
 5626:                 } 
 5627:             }
 5628:         } 
 5629:     }
 5630:     return %readonly_files;
 5631: }
 5632: # ------------------------------------------------------------ Unmark as Read Only
 5633: 
 5634: sub unmark_as_readonly {
 5635:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5636:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5637:     my ($domain,$user,$what,$file_name,$group) = @_;
 5638:     $file_name = &declutter_portfile($file_name);
 5639:     my $symb_crs = $what;
 5640:     if (ref($what)) { $symb_crs=join('',@$what); }
 5641:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5642:     my ($tmp)=keys(%current_permissions);
 5643:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5644:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5645:     foreach my $file (@readonly_files) {
 5646: 	my $clean_file = &declutter_portfile($file);
 5647: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5648: 	my $current_locks = $current_permissions{$file};
 5649:         my @new_locks;
 5650:         my @del_keys;
 5651:         if (ref($current_locks) eq "ARRAY"){
 5652:             foreach my $locker (@{$current_locks}) {
 5653:                 my $compare=$locker;
 5654:                 if (ref($locker) eq 'ARRAY') {
 5655:                     $compare=join('',@{$locker});
 5656:                     if ($compare ne $symb_crs) {
 5657:                         push(@new_locks, $locker);
 5658:                     }
 5659:                 }
 5660:             }
 5661:             if (scalar(@new_locks) > 0) {
 5662:                 $current_permissions{$file} = \@new_locks;
 5663:             } else {
 5664:                 push(@del_keys, $file);
 5665:                 &del('file_permissions',\@del_keys, $domain, $user);
 5666:                 delete($current_permissions{$file});
 5667:             }
 5668:         }
 5669:     }
 5670:     &put('file_permissions',\%current_permissions,$domain,$user);
 5671:     return;
 5672: }
 5673: 
 5674: # ------------------------------------------------------------ Directory lister
 5675: 
 5676: sub dirlist {
 5677:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5678: 
 5679:     $uri=~s/^\///;
 5680:     $uri=~s/\/$//;
 5681:     my ($udom, $uname);
 5682:     (undef,$udom,$uname)=split(/\//,$uri);
 5683:     if(defined($userdomain)) {
 5684:         $udom = $userdomain;
 5685:     }
 5686:     if(defined($username)) {
 5687:         $uname = $username;
 5688:     }
 5689: 
 5690:     my $dirRoot = $perlvar{'lonDocRoot'};
 5691:     if(defined($alternateDirectoryRoot)) {
 5692:         $dirRoot = $alternateDirectoryRoot;
 5693:         $dirRoot =~ s/\/$//;
 5694:     }
 5695: 
 5696:     if($udom) {
 5697:         if($uname) {
 5698:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5699: 				 &homeserver($uname,$udom));
 5700:             my @listing_results;
 5701:             if ($listing eq 'unknown_cmd') {
 5702:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5703: 				  &homeserver($uname,$udom));
 5704:                 @listing_results = split(/:/,$listing);
 5705:             } else {
 5706:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5707:             }
 5708:             return @listing_results;
 5709:         } elsif(!defined($alternateDirectoryRoot)) {
 5710:             my %allusers;
 5711: 	    my %servers = &get_servers($udom,'library');
 5712: 	    foreach my $tryserver (keys(%servers)) {
 5713: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5714: 				     $udom, $tryserver);
 5715: 		my @listing_results;
 5716: 		if ($listing eq 'unknown_cmd') {
 5717: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5718: 				      $udom, $tryserver);
 5719: 		    @listing_results = split(/:/,$listing);
 5720: 		} else {
 5721: 		    @listing_results =
 5722: 			map { &unescape($_); } split(/:/,$listing);
 5723: 		}
 5724: 		if ($listing_results[0] ne 'no_such_dir' && 
 5725: 		    $listing_results[0] ne 'empty'       &&
 5726: 		    $listing_results[0] ne 'con_lost') {
 5727: 		    foreach my $line (@listing_results) {
 5728: 			my ($entry) = split(/&/,$line,2);
 5729: 			$allusers{$entry} = 1;
 5730: 		    }
 5731: 		}
 5732:             }
 5733:             my $alluserstr='';
 5734:             foreach my $user (sort(keys(%allusers))) {
 5735:                 $alluserstr.=$user.'&user:';
 5736:             }
 5737:             $alluserstr=~s/:$//;
 5738:             return split(/:/,$alluserstr);
 5739:         } else {
 5740:             return ('missing user name');
 5741:         }
 5742:     } elsif(!defined($alternateDirectoryRoot)) {
 5743:         my @all_domains = sort(&all_domains());
 5744:          foreach my $domain (@all_domains) {
 5745:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5746:          }
 5747:          return @all_domains;
 5748:      } else {
 5749:         return ('missing domain');
 5750:     }
 5751: }
 5752: 
 5753: # --------------------------------------------- GetFileTimestamp
 5754: # This function utilizes dirlist and returns the date stamp for
 5755: # when it was last modified.  It will also return an error of -1
 5756: # if an error occurs
 5757: 
 5758: ##
 5759: ## FIXME: This subroutine assumes its caller knows something about the
 5760: ## directory structure of the home server for the student ($root).
 5761: ## Not a good assumption to make.  Since this is for looking up files
 5762: ## in user directories, the full path should be constructed by lond, not
 5763: ## whatever machine we request data from.
 5764: ##
 5765: sub GetFileTimestamp {
 5766:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5767:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5768:     $studentName   = &LONCAPA::clean_username($studentName);
 5769:     my $subdir=$studentName.'__';
 5770:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5771:     my $proname="$studentDomain/$subdir/$studentName";
 5772:     $proname .= '/'.$filename;
 5773:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5774:                                               $studentName, $root);
 5775:     my @stats = split('&', $fileStat);
 5776:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5777:         # @stats contains first the filename, then the stat output
 5778:         return $stats[10]; # so this is 10 instead of 9.
 5779:     } else {
 5780:         return -1;
 5781:     }
 5782: }
 5783: 
 5784: sub stat_file {
 5785:     my ($uri) = @_;
 5786:     $uri = &clutter_with_no_wrapper($uri);
 5787: 
 5788:     my ($udom,$uname,$file,$dir);
 5789:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5790: 	($udom,$uname,$file) =
 5791: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5792: 	$file = 'userfiles/'.$file;
 5793: 	$dir = &propath($udom,$uname);
 5794:     }
 5795:     if ($uri =~ m-^/res/-) {
 5796: 	($udom,$uname) = 
 5797: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5798: 	$file = $uri;
 5799:     }
 5800: 
 5801:     if (!$udom || !$uname || !$file) {
 5802: 	# unable to handle the uri
 5803: 	return ();
 5804:     }
 5805: 
 5806:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5807:     my @stats = split('&', $result);
 5808:     
 5809:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5810: 	shift(@stats); #filename is first
 5811: 	return @stats;
 5812:     }
 5813:     return ();
 5814: }
 5815: 
 5816: # -------------------------------------------------------- Value of a Condition
 5817: 
 5818: # gets the value of a specific preevaluated condition
 5819: #    stored in the string  $env{user.state.<cid>}
 5820: # or looks up a condition reference in the bighash and if if hasn't
 5821: # already been evaluated recurses into docondval to get the value of
 5822: # the condition, then memoizing it to 
 5823: #   $env{user.state.<cid>.<condition>}
 5824: sub directcondval {
 5825:     my $number=shift;
 5826:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5827: 	&Apache::lonuserstate::evalstate();
 5828:     }
 5829:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5830: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5831:     } elsif ($number =~ /^_/) {
 5832: 	my $sub_condition;
 5833: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5834: 		&GDBM_READER(),0640)) {
 5835: 	    $sub_condition=$bighash{'conditions'.$number};
 5836: 	    untie(%bighash);
 5837: 	}
 5838: 	my $value = &docondval($sub_condition);
 5839: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5840: 	return $value;
 5841:     }
 5842:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5843:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5844:     } else {
 5845:        return 2;
 5846:     }
 5847: }
 5848: 
 5849: # get the collection of conditions for this resource
 5850: sub condval {
 5851:     my $condidx=shift;
 5852:     my $allpathcond='';
 5853:     foreach my $cond (split(/\|/,$condidx)) {
 5854: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5855: 	    $allpathcond.=
 5856: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5857: 	}
 5858:     }
 5859:     $allpathcond=~s/\|$//;
 5860:     return &docondval($allpathcond);
 5861: }
 5862: 
 5863: #evaluates an expression of conditions
 5864: sub docondval {
 5865:     my ($allpathcond) = @_;
 5866:     my $result=0;
 5867:     if ($env{'request.course.id'}
 5868: 	&& defined($allpathcond)) {
 5869: 	my $operand='|';
 5870: 	my @stack;
 5871: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5872: 	    if ($chunk eq '(') {
 5873: 		push @stack,($operand,$result);
 5874: 	    } elsif ($chunk eq ')') {
 5875: 		my $before=pop @stack;
 5876: 		if (pop @stack eq '&') {
 5877: 		    $result=$result>$before?$before:$result;
 5878: 		} else {
 5879: 		    $result=$result>$before?$result:$before;
 5880: 		}
 5881: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5882: 		$operand=$chunk;
 5883: 	    } else {
 5884: 		my $new=directcondval($chunk);
 5885: 		if ($operand eq '&') {
 5886: 		    $result=$result>$new?$new:$result;
 5887: 		} else {
 5888: 		    $result=$result>$new?$result:$new;
 5889: 		}
 5890: 	    }
 5891: 	}
 5892:     }
 5893:     return $result;
 5894: }
 5895: 
 5896: # ---------------------------------------------------- Devalidate courseresdata
 5897: 
 5898: sub devalidatecourseresdata {
 5899:     my ($coursenum,$coursedomain)=@_;
 5900:     my $hashid=$coursenum.':'.$coursedomain;
 5901:     &devalidate_cache_new('courseres',$hashid);
 5902: }
 5903: 
 5904: 
 5905: # --------------------------------------------------- Course Resourcedata Query
 5906: 
 5907: sub get_courseresdata {
 5908:     my ($coursenum,$coursedomain)=@_;
 5909:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5910:     my $hashid=$coursenum.':'.$coursedomain;
 5911:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5912:     my %dumpreply;
 5913:     unless (defined($cached)) {
 5914: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5915: 	$result=\%dumpreply;
 5916: 	my ($tmp) = keys(%dumpreply);
 5917: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5918: 	    &do_cache_new('courseres',$hashid,$result,600);
 5919: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5920: 	    return $tmp;
 5921: 	} elsif ($tmp =~ /^(error)/) {
 5922: 	    $result=undef;
 5923: 	    &do_cache_new('courseres',$hashid,$result,600);
 5924: 	}
 5925:     }
 5926:     return $result;
 5927: }
 5928: 
 5929: sub devalidateuserresdata {
 5930:     my ($uname,$udom)=@_;
 5931:     my $hashid="$udom:$uname";
 5932:     &devalidate_cache_new('userres',$hashid);
 5933: }
 5934: 
 5935: sub get_userresdata {
 5936:     my ($uname,$udom)=@_;
 5937:     #most student don\'t have any data set, check if there is some data
 5938:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5939: 
 5940:     my $hashid="$udom:$uname";
 5941:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5942:     if (!defined($cached)) {
 5943: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5944: 	$result=\%resourcedata;
 5945: 	&do_cache_new('userres',$hashid,$result,600);
 5946:     }
 5947:     my ($tmp)=keys(%$result);
 5948:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5949: 	return $result;
 5950:     }
 5951:     #error 2 occurs when the .db doesn't exist
 5952:     if ($tmp!~/error: 2 /) {
 5953: 	&logthis("<font color=\"blue\">WARNING:".
 5954: 		 " Trying to get resource data for ".
 5955: 		 $uname." at ".$udom.": ".
 5956: 		 $tmp."</font>");
 5957:     } elsif ($tmp=~/error: 2 /) {
 5958: 	#&EXT_cache_set($udom,$uname);
 5959: 	&do_cache_new('userres',$hashid,undef,600);
 5960: 	undef($tmp); # not really an error so don't send it back
 5961:     }
 5962:     return $tmp;
 5963: }
 5964: 
 5965: sub resdata {
 5966:     my ($name,$domain,$type,@which)=@_;
 5967:     my $result;
 5968:     if ($type eq 'course') {
 5969: 	$result=&get_courseresdata($name,$domain);
 5970:     } elsif ($type eq 'user') {
 5971: 	$result=&get_userresdata($name,$domain);
 5972:     }
 5973:     if (!ref($result)) { return $result; }    
 5974:     foreach my $item (@which) {
 5975: 	if (defined($result->{$item})) {
 5976: 	    return $result->{$item};
 5977: 	}
 5978:     }
 5979:     return undef;
 5980: }
 5981: 
 5982: #
 5983: # EXT resource caching routines
 5984: #
 5985: 
 5986: sub clear_EXT_cache_status {
 5987:     &delenv('cache.EXT.');
 5988: }
 5989: 
 5990: sub EXT_cache_status {
 5991:     my ($target_domain,$target_user) = @_;
 5992:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5993:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5994:         # We know already the user has no data
 5995:         return 1;
 5996:     } else {
 5997:         return 0;
 5998:     }
 5999: }
 6000: 
 6001: sub EXT_cache_set {
 6002:     my ($target_domain,$target_user) = @_;
 6003:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6004:     #&appenv($cachename => time);
 6005: }
 6006: 
 6007: # --------------------------------------------------------- Value of a Variable
 6008: sub EXT {
 6009: 
 6010:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6011:     unless ($varname) { return ''; }
 6012:     #get real user name/domain, courseid and symb
 6013:     my $courseid;
 6014:     my $publicuser;
 6015:     if ($symbparm) {
 6016: 	$symbparm=&get_symb_from_alias($symbparm);
 6017:     }
 6018:     if (!($uname && $udom)) {
 6019:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6020:       if (!$symbparm) {	$symbparm=$cursymb; }
 6021:     } else {
 6022: 	$courseid=$env{'request.course.id'};
 6023:     }
 6024:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6025:     my $rest;
 6026:     if (defined($therest[0])) {
 6027:        $rest=join('.',@therest);
 6028:     } else {
 6029:        $rest='';
 6030:     }
 6031: 
 6032:     my $qualifierrest=$qualifier;
 6033:     if ($rest) { $qualifierrest.='.'.$rest; }
 6034:     my $spacequalifierrest=$space;
 6035:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6036:     if ($realm eq 'user') {
 6037: # --------------------------------------------------------------- user.resource
 6038: 	if ($space eq 'resource') {
 6039: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6040: 		  || defined($Apache::lonhomework::parsing_a_task))
 6041: 		 &&
 6042: 		 ($symbparm eq &symbread()) ) {	
 6043: 		# if we are in the middle of processing the resource the
 6044: 		# get the value we are planning on committing
 6045:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6046:                     return $Apache::lonhomework::results{$qualifierrest};
 6047:                 } else {
 6048:                     return $Apache::lonhomework::history{$qualifierrest};
 6049:                 }
 6050: 	    } else {
 6051: 		my %restored;
 6052: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6053: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6054: 		} else {
 6055: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6056: 		}
 6057: 		return $restored{$qualifierrest};
 6058: 	    }
 6059: # ----------------------------------------------------------------- user.access
 6060:         } elsif ($space eq 'access') {
 6061: 	    # FIXME - not supporting calls for a specific user
 6062:             return &allowed($qualifier,$rest);
 6063: # ------------------------------------------ user.preferences, user.environment
 6064:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6065: 	    if (($uname eq $env{'user.name'}) &&
 6066: 		($udom eq $env{'user.domain'})) {
 6067: 		return $env{join('.',('environment',$qualifierrest))};
 6068: 	    } else {
 6069: 		my %returnhash;
 6070: 		if (!$publicuser) {
 6071: 		    %returnhash=&userenvironment($udom,$uname,
 6072: 						 $qualifierrest);
 6073: 		}
 6074: 		return $returnhash{$qualifierrest};
 6075: 	    }
 6076: # ----------------------------------------------------------------- user.course
 6077:         } elsif ($space eq 'course') {
 6078: 	    # FIXME - not supporting calls for a specific user
 6079:             return $env{join('.',('request.course',$qualifier))};
 6080: # ------------------------------------------------------------------- user.role
 6081:         } elsif ($space eq 'role') {
 6082: 	    # FIXME - not supporting calls for a specific user
 6083:             my ($role,$where)=split(/\./,$env{'request.role'});
 6084:             if ($qualifier eq 'value') {
 6085: 		return $role;
 6086:             } elsif ($qualifier eq 'extent') {
 6087:                 return $where;
 6088:             }
 6089: # ----------------------------------------------------------------- user.domain
 6090:         } elsif ($space eq 'domain') {
 6091:             return $udom;
 6092: # ------------------------------------------------------------------- user.name
 6093:         } elsif ($space eq 'name') {
 6094:             return $uname;
 6095: # ---------------------------------------------------- Any other user namespace
 6096:         } else {
 6097: 	    my %reply;
 6098: 	    if (!$publicuser) {
 6099: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6100: 	    }
 6101: 	    return $reply{$qualifierrest};
 6102:         }
 6103:     } elsif ($realm eq 'query') {
 6104: # ---------------------------------------------- pull stuff out of query string
 6105:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6106: 						[$spacequalifierrest]);
 6107: 	return $env{'form.'.$spacequalifierrest}; 
 6108:    } elsif ($realm eq 'request') {
 6109: # ------------------------------------------------------------- request.browser
 6110:         if ($space eq 'browser') {
 6111: 	    if ($qualifier eq 'textremote') {
 6112: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6113: 		    return 1;
 6114: 		} else {
 6115: 		    return 0;
 6116: 		}
 6117: 	    } else {
 6118: 		return $env{'browser.'.$qualifier};
 6119: 	    }
 6120: # ------------------------------------------------------------ request.filename
 6121:         } else {
 6122:             return $env{'request.'.$spacequalifierrest};
 6123:         }
 6124:     } elsif ($realm eq 'course') {
 6125: # ---------------------------------------------------------- course.description
 6126:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6127:     } elsif ($realm eq 'resource') {
 6128: 
 6129: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6130: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6131: 	}
 6132: 
 6133: 	if ($space eq 'title') {
 6134: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6135: 	    return &gettitle($symbparm);
 6136: 	}
 6137: 	
 6138: 	if ($space eq 'map') {
 6139: 	    my ($map) = &decode_symb($symbparm);
 6140: 	    return &symbread($map);
 6141: 	}
 6142: 
 6143: 	my ($section, $group, @groups);
 6144: 	my ($courselevelm,$courselevel);
 6145: 	if ($symbparm && defined($courseid) && 
 6146: 	    $courseid eq $env{'request.course.id'}) {
 6147: 
 6148: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6149: 
 6150: # ----------------------------------------------------- Cascading lookup scheme
 6151: 	    my $symbp=$symbparm;
 6152: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6153: 
 6154: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6155: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6156: 
 6157: 	    if (($env{'user.name'} eq $uname) &&
 6158: 		($env{'user.domain'} eq $udom)) {
 6159: 		$section=$env{'request.course.sec'};
 6160:                 @groups = split(/:/,$env{'request.course.groups'});  
 6161:                 @groups=&sort_course_groups($courseid,@groups); 
 6162: 	    } else {
 6163: 		if (! defined($usection)) {
 6164: 		    $section=&getsection($udom,$uname,$courseid);
 6165: 		} else {
 6166: 		    $section = $usection;
 6167: 		}
 6168:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6169: 	    }
 6170: 
 6171: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6172: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6173: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6174: 
 6175: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6176: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6177: 	    $courselevelm=$courseid.'.'.$mapparm;
 6178: 
 6179: # ----------------------------------------------------------- first, check user
 6180: 
 6181: 	    my $userreply=&resdata($uname,$udom,'user',
 6182: 				       ($courselevelr,$courselevelm,
 6183: 					$courselevel));
 6184: 	    if (defined($userreply)) { return $userreply; }
 6185: 
 6186: # ------------------------------------------------ second, check some of course
 6187:             my $coursereply;
 6188:             if (@groups > 0) {
 6189:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6190:                                        $mapparm,$spacequalifierrest);
 6191:                 if (defined($coursereply)) { return $coursereply; }
 6192:             }
 6193: 
 6194: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6195: 				     $env{'course.'.$courseid.'.domain'},
 6196: 				     'course',
 6197: 				     ($seclevelr,$seclevelm,$seclevel,
 6198: 				      $courselevelr));
 6199: 	    if (defined($coursereply)) { return $coursereply; }
 6200: 
 6201: # ------------------------------------------------------ third, check map parms
 6202: 	    my %parmhash=();
 6203: 	    my $thisparm='';
 6204: 	    if (tie(%parmhash,'GDBM_File',
 6205: 		    $env{'request.course.fn'}.'_parms.db',
 6206: 		    &GDBM_READER(),0640)) {
 6207: 		$thisparm=$parmhash{$symbparm};
 6208: 		untie(%parmhash);
 6209: 	    }
 6210: 	    if ($thisparm) { return $thisparm; }
 6211: 	}
 6212: # ------------------------------------------ fourth, look in resource metadata
 6213: 
 6214: 	$spacequalifierrest=~s/\./\_/;
 6215: 	my $filename;
 6216: 	if (!$symbparm) { $symbparm=&symbread(); }
 6217: 	if ($symbparm) {
 6218: 	    $filename=(&decode_symb($symbparm))[2];
 6219: 	} else {
 6220: 	    $filename=$env{'request.filename'};
 6221: 	}
 6222: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6223: 	if (defined($metadata)) { return $metadata; }
 6224: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6225: 	if (defined($metadata)) { return $metadata; }
 6226: 
 6227: # ---------------------------------------------- fourth, look in rest pf course
 6228: 	if ($symbparm && defined($courseid) && 
 6229: 	    $courseid eq $env{'request.course.id'}) {
 6230: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6231: 				     $env{'course.'.$courseid.'.domain'},
 6232: 				     'course',
 6233: 				     ($courselevelm,$courselevel));
 6234: 	    if (defined($coursereply)) { return $coursereply; }
 6235: 	}
 6236: # ------------------------------------------------------------------ Cascade up
 6237: 	unless ($space eq '0') {
 6238: 	    my @parts=split(/_/,$space);
 6239: 	    my $id=pop(@parts);
 6240: 	    my $part=join('_',@parts);
 6241: 	    if ($part eq '') { $part='0'; }
 6242: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6243: 				 $symbparm,$udom,$uname,$section,1);
 6244: 	    if (defined($partgeneral)) { return $partgeneral; }
 6245: 	}
 6246: 	if ($recurse) { return undef; }
 6247: 	my $pack_def=&packages_tab_default($filename,$varname);
 6248: 	if (defined($pack_def)) { return $pack_def; }
 6249: 
 6250: # ---------------------------------------------------- Any other user namespace
 6251:     } elsif ($realm eq 'environment') {
 6252: # ----------------------------------------------------------------- environment
 6253: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6254: 	    return $env{'environment.'.$spacequalifierrest};
 6255: 	} else {
 6256: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6257: 		return '';
 6258: 	    }
 6259: 	    my %returnhash=&userenvironment($udom,$uname,
 6260: 					    $spacequalifierrest);
 6261: 	    return $returnhash{$spacequalifierrest};
 6262: 	}
 6263:     } elsif ($realm eq 'system') {
 6264: # ----------------------------------------------------------------- system.time
 6265: 	if ($space eq 'time') {
 6266: 	    return time;
 6267:         }
 6268:     } elsif ($realm eq 'server') {
 6269: # ----------------------------------------------------------------- system.time
 6270: 	if ($space eq 'name') {
 6271: 	    return $ENV{'SERVER_NAME'};
 6272:         }
 6273:     }
 6274:     return '';
 6275: }
 6276: 
 6277: sub check_group_parms {
 6278:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6279:     my @groupitems = ();
 6280:     my $resultitem;
 6281:     my @levels = ($symbparm,$mapparm,$what);
 6282:     foreach my $group (@{$groups}) {
 6283:         foreach my $level (@levels) {
 6284:              my $item = $courseid.'.['.$group.'].'.$level;
 6285:              push(@groupitems,$item);
 6286:         }
 6287:     }
 6288:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6289:                             $env{'course.'.$courseid.'.domain'},
 6290:                                      'course',@groupitems);
 6291:     return $coursereply;
 6292: }
 6293: 
 6294: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6295:     my ($courseid,@groups) = @_;
 6296:     @groups = sort(@groups);
 6297:     return @groups;
 6298: }
 6299: 
 6300: sub packages_tab_default {
 6301:     my ($uri,$varname)=@_;
 6302:     my (undef,$part,$name)=split(/\./,$varname);
 6303: 
 6304:     my (@extension,@specifics,$do_default);
 6305:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6306: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6307: 	if ($pack_type eq 'default') {
 6308: 	    $do_default=1;
 6309: 	} elsif ($pack_type eq 'extension') {
 6310: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6311: 	} elsif ($pack_part eq $part) {
 6312: 	    # only look at packages defaults for packages that this id is
 6313: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6314: 	}
 6315:     }
 6316:     # first look for a package that matches the requested part id
 6317:     foreach my $package (@specifics) {
 6318: 	my (undef,$pack_type,$pack_part)=@{$package};
 6319: 	next if ($pack_part ne $part);
 6320: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6321: 	    return $packagetab{"$pack_type&$name&default"};
 6322: 	}
 6323:     }
 6324:     # look for any possible matching non extension_ package
 6325:     foreach my $package (@specifics) {
 6326: 	my (undef,$pack_type,$pack_part)=@{$package};
 6327: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6328: 	    return $packagetab{"$pack_type&$name&default"};
 6329: 	}
 6330: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6331: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6332: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6333: 	}
 6334:     }
 6335:     # look for any posible extension_ match
 6336:     foreach my $package (@extension) {
 6337: 	my ($package,$pack_type)=@{$package};
 6338: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6339: 	    return $packagetab{"$pack_type&$name&default"};
 6340: 	}
 6341: 	if (defined($packagetab{$package."&$name&default"})) {
 6342: 	    return $packagetab{$package."&$name&default"};
 6343: 	}
 6344:     }
 6345:     # look for a global default setting
 6346:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6347: 	return $packagetab{"default&$name&default"};
 6348:     }
 6349:     return undef;
 6350: }
 6351: 
 6352: sub add_prefix_and_part {
 6353:     my ($prefix,$part)=@_;
 6354:     my $keyroot;
 6355:     if (defined($prefix) && $prefix !~ /^__/) {
 6356: 	# prefix that has a part already
 6357: 	$keyroot=$prefix;
 6358:     } elsif (defined($prefix)) {
 6359: 	# prefix that is missing a part
 6360: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6361:     } else {
 6362: 	# no prefix at all
 6363: 	if (defined($part)) { $keyroot='_'.$part; }
 6364:     }
 6365:     return $keyroot;
 6366: }
 6367: 
 6368: # ---------------------------------------------------------------- Get metadata
 6369: 
 6370: my %metaentry;
 6371: sub metadata {
 6372:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6373:     $uri=&declutter($uri);
 6374:     # if it is a non metadata possible uri return quickly
 6375:     if (($uri eq '') || 
 6376: 	(($uri =~ m|^/*adm/|) && 
 6377: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6378:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6379: 	($uri =~ m|home/$match_username/public_html/|)) {
 6380: 	return undef;
 6381:     }
 6382:     my $filename=$uri;
 6383:     $uri=~s/\.meta$//;
 6384: #
 6385: # Is the metadata already cached?
 6386: # Look at timestamp of caching
 6387: # Everything is cached by the main uri, libraries are never directly cached
 6388: #
 6389:     if (!defined($liburi)) {
 6390: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6391: 	if (defined($cached)) { return $result->{':'.$what}; }
 6392:     }
 6393:     {
 6394: #
 6395: # Is this a recursive call for a library?
 6396: #
 6397: #	if (! exists($metacache{$uri})) {
 6398: #	    $metacache{$uri}={};
 6399: #	}
 6400:         if ($liburi) {
 6401: 	    $liburi=&declutter($liburi);
 6402:             $filename=$liburi;
 6403:         } else {
 6404: 	    &devalidate_cache_new('meta',$uri);
 6405: 	    undef(%metaentry);
 6406: 	}
 6407:         my %metathesekeys=();
 6408:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6409: 	my $metastring;
 6410: 	if ($uri !~ m -^(editupload)/-) {
 6411: 	    my $file=&filelocation('',&clutter($filename));
 6412: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6413: 	    $metastring=&getfile($file);
 6414: 	}
 6415:         my $parser=HTML::LCParser->new(\$metastring);
 6416:         my $token;
 6417:         undef %metathesekeys;
 6418:         while ($token=$parser->get_token) {
 6419: 	    if ($token->[0] eq 'S') {
 6420: 		if (defined($token->[2]->{'package'})) {
 6421: #
 6422: # This is a package - get package info
 6423: #
 6424: 		    my $package=$token->[2]->{'package'};
 6425: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6426: 		    if (defined($token->[2]->{'id'})) { 
 6427: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6428: 		    }
 6429: 		    if ($metaentry{':packages'}) {
 6430: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6431: 		    } else {
 6432: 			$metaentry{':packages'}=$package.$keyroot;
 6433: 		    }
 6434: 		    foreach my $pack_entry (keys(%packagetab)) {
 6435: 			my $part=$keyroot;
 6436: 			$part=~s/^\_//;
 6437: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6438: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6439: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6440: 			    # ignore package.tab specified default values
 6441:                             # here &package_tab_default() will fetch those
 6442: 			    if ($subp eq 'default') { next; }
 6443: 			    my $value=$packagetab{$pack_entry};
 6444: 			    my $unikey;
 6445: 			    if ($pack =~ /_0$/) {
 6446: 				$unikey='parameter_0_'.$name;
 6447: 				$part=0;
 6448: 			    } else {
 6449: 				$unikey='parameter'.$keyroot.'_'.$name;
 6450: 			    }
 6451: 			    if ($subp eq 'display') {
 6452: 				$value.=' [Part: '.$part.']';
 6453: 			    }
 6454: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6455: 			    $metathesekeys{$unikey}=1;
 6456: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6457: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6458: 			    }
 6459: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6460: 				$metaentry{':'.$unikey}=
 6461: 				    $metaentry{':'.$unikey.'.default'};
 6462: 			    }
 6463: 			}
 6464: 		    }
 6465: 		} else {
 6466: #
 6467: # This is not a package - some other kind of start tag
 6468: #
 6469: 		    my $entry=$token->[1];
 6470: 		    my $unikey;
 6471: 		    if ($entry eq 'import') {
 6472: 			$unikey='';
 6473: 		    } else {
 6474: 			$unikey=$entry;
 6475: 		    }
 6476: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6477: 
 6478: 		    if (defined($token->[2]->{'id'})) { 
 6479: 			$unikey.='_'.$token->[2]->{'id'}; 
 6480: 		    }
 6481: 
 6482: 		    if ($entry eq 'import') {
 6483: #
 6484: # Importing a library here
 6485: #
 6486: 			if ($depthcount<20) {
 6487: 			    my $location=$parser->get_text('/import');
 6488: 			    my $dir=$filename;
 6489: 			    $dir=~s|[^/]*$||;
 6490: 			    $location=&filelocation($dir,$location);
 6491: 			    my $metadata = 
 6492: 				&metadata($uri,'keys', $location,$unikey,
 6493: 					  $depthcount+1);
 6494: 			    foreach my $meta (split(',',$metadata)) {
 6495: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6496: 				$metathesekeys{$meta}=1;
 6497: 			    }
 6498: 			}
 6499: 		    } else { 
 6500: 			
 6501: 			if (defined($token->[2]->{'name'})) { 
 6502: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6503: 			}
 6504: 			$metathesekeys{$unikey}=1;
 6505: 			foreach my $param (@{$token->[3]}) {
 6506: 			    $metaentry{':'.$unikey.'.'.$param} =
 6507: 				$token->[2]->{$param};
 6508: 			}
 6509: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6510: 			my $default=$metaentry{':'.$unikey.'.default'};
 6511: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6512: 		 # only ws inside the tag, and not in default, so use default
 6513: 		 # as value
 6514: 			    $metaentry{':'.$unikey}=$default;
 6515: 			} else {
 6516: 		  # either something interesting inside the tag or default
 6517:                   # uninteresting
 6518: 			    $metaentry{':'.$unikey}=$internaltext;
 6519: 			}
 6520: # end of not-a-package not-a-library import
 6521: 		    }
 6522: # end of not-a-package start tag
 6523: 		}
 6524: # the next is the end of "start tag"
 6525: 	    }
 6526: 	}
 6527: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6528: 	foreach my $key (keys(%packagetab)) {
 6529: 	    #no specific packages #how's our extension
 6530: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6531: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6532: 					 \%metathesekeys);
 6533: 	}
 6534: 	if (!exists($metaentry{':packages'})) {
 6535: 	    foreach my $key (keys(%packagetab)) {
 6536: 		#no specific packages well let's get default then
 6537: 		if ($key!~/^default&/) { next; }
 6538: 		&metadata_create_package_def($uri,$key,'default',
 6539: 					     \%metathesekeys);
 6540: 	    }
 6541: 	}
 6542: # are there custom rights to evaluate
 6543: 	if ($metaentry{':copyright'} eq 'custom') {
 6544: 
 6545:     #
 6546:     # Importing a rights file here
 6547:     #
 6548: 	    unless ($depthcount) {
 6549: 		my $location=$metaentry{':customdistributionfile'};
 6550: 		my $dir=$filename;
 6551: 		$dir=~s|[^/]*$||;
 6552: 		$location=&filelocation($dir,$location);
 6553: 		my $rights_metadata =
 6554: 		    &metadata($uri,'keys',$location,'_rights',
 6555: 			      $depthcount+1);
 6556: 		foreach my $rights (split(',',$rights_metadata)) {
 6557: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6558: 		    $metathesekeys{$rights}=1;
 6559: 		}
 6560: 	    }
 6561: 	}
 6562: 	# uniqifiy package listing
 6563: 	my %seen;
 6564: 	my @uniq_packages =
 6565: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6566: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6567: 
 6568: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6569: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6570: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6571: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6572: # this is the end of "was not already recently cached
 6573:     }
 6574:     return $metaentry{':'.$what};
 6575: }
 6576: 
 6577: sub metadata_create_package_def {
 6578:     my ($uri,$key,$package,$metathesekeys)=@_;
 6579:     my ($pack,$name,$subp)=split(/\&/,$key);
 6580:     if ($subp eq 'default') { next; }
 6581:     
 6582:     if (defined($metaentry{':packages'})) {
 6583: 	$metaentry{':packages'}.=','.$package;
 6584:     } else {
 6585: 	$metaentry{':packages'}=$package;
 6586:     }
 6587:     my $value=$packagetab{$key};
 6588:     my $unikey;
 6589:     $unikey='parameter_0_'.$name;
 6590:     $metaentry{':'.$unikey.'.part'}=0;
 6591:     $$metathesekeys{$unikey}=1;
 6592:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6593: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6594:     }
 6595:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6596: 	$metaentry{':'.$unikey}=
 6597: 	    $metaentry{':'.$unikey.'.default'};
 6598:     }
 6599: }
 6600: 
 6601: sub metadata_generate_part0 {
 6602:     my ($metadata,$metacache,$uri) = @_;
 6603:     my %allnames;
 6604:     foreach my $metakey (keys(%$metadata)) {
 6605: 	if ($metakey=~/^parameter\_(.*)/) {
 6606: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6607: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6608: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6609: 	    $allnames{$name}=$part;
 6610: 	  }
 6611: 	}
 6612:     }
 6613:     foreach my $name (keys(%allnames)) {
 6614:       $$metadata{"parameter_0_$name"}=1;
 6615:       my $key=":parameter_0_$name";
 6616:       $$metacache{"$key.part"}='0';
 6617:       $$metacache{"$key.name"}=$name;
 6618:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6619: 					   $allnames{$name}.'_'.$name.
 6620: 					   '.type'};
 6621:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6622: 			     '.display'};
 6623:       my $expr='[Part: '.$allnames{$name}.']';
 6624:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6625:       $$metacache{"$key.display"}=$olddis;
 6626:     }
 6627: }
 6628: 
 6629: # ------------------------------------------------------ Devalidate title cache
 6630: 
 6631: sub devalidate_title_cache {
 6632:     my ($url)=@_;
 6633:     if (!$env{'request.course.id'}) { return; }
 6634:     my $symb=&symbread($url);
 6635:     if (!$symb) { return; }
 6636:     my $key=$env{'request.course.id'}."\0".$symb;
 6637:     &devalidate_cache_new('title',$key);
 6638: }
 6639: 
 6640: # ------------------------------------------------- Get the title of a resource
 6641: 
 6642: sub gettitle {
 6643:     my $urlsymb=shift;
 6644:     my $symb=&symbread($urlsymb);
 6645:     if ($symb) {
 6646: 	my $key=$env{'request.course.id'}."\0".$symb;
 6647: 	my ($result,$cached)=&is_cached_new('title',$key);
 6648: 	if (defined($cached)) { 
 6649: 	    return $result;
 6650: 	}
 6651: 	my ($map,$resid,$url)=&decode_symb($symb);
 6652: 	my $title='';
 6653: 	my %bighash;
 6654: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6655: 		&GDBM_READER(),0640)) {
 6656: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6657: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6658: 	    untie %bighash;
 6659: 	}
 6660: 	$title=~s/\&colon\;/\:/gs;
 6661: 	if ($title) {
 6662: 	    return &do_cache_new('title',$key,$title,600);
 6663: 	}
 6664: 	$urlsymb=$url;
 6665:     }
 6666:     my $title=&metadata($urlsymb,'title');
 6667:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6668:     return $title;
 6669: }
 6670: 
 6671: sub get_slot {
 6672:     my ($which,$cnum,$cdom)=@_;
 6673:     if (!$cnum || !$cdom) {
 6674: 	(undef,my $courseid)=&whichuser();
 6675: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6676: 	$cnum=$env{'course.'.$courseid.'.num'};
 6677:     }
 6678:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6679:     my %slotinfo;
 6680:     if (exists($remembered{$key})) {
 6681: 	$slotinfo{$which} = $remembered{$key};
 6682:     } else {
 6683: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6684: 	&Apache::lonhomework::showhash(%slotinfo);
 6685: 	my ($tmp)=keys(%slotinfo);
 6686: 	if ($tmp=~/^error:/) { return (); }
 6687: 	$remembered{$key} = $slotinfo{$which};
 6688:     }
 6689:     if (ref($slotinfo{$which}) eq 'HASH') {
 6690: 	return %{$slotinfo{$which}};
 6691:     }
 6692:     return $slotinfo{$which};
 6693: }
 6694: # ------------------------------------------------- Update symbolic store links
 6695: 
 6696: sub symblist {
 6697:     my ($mapname,%newhash)=@_;
 6698:     $mapname=&deversion(&declutter($mapname));
 6699:     my %hash;
 6700:     if (($env{'request.course.fn'}) && (%newhash)) {
 6701:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6702:                       &GDBM_WRCREAT(),0640)) {
 6703: 	    foreach my $url (keys %newhash) {
 6704: 		next if ($url eq 'last_known'
 6705: 			 && $env{'form.no_update_last_known'});
 6706: 		$hash{declutter($url)}=&encode_symb($mapname,
 6707: 						    $newhash{$url}->[1],
 6708: 						    $newhash{$url}->[0]);
 6709:             }
 6710:             if (untie(%hash)) {
 6711: 		return 'ok';
 6712:             }
 6713:         }
 6714:     }
 6715:     return 'error';
 6716: }
 6717: 
 6718: # --------------------------------------------------------------- Verify a symb
 6719: 
 6720: sub symbverify {
 6721:     my ($symb,$thisurl)=@_;
 6722:     my $thisfn=$thisurl;
 6723:     $thisfn=&declutter($thisfn);
 6724: # direct jump to resource in page or to a sequence - will construct own symbs
 6725:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6726: # check URL part
 6727:     my ($map,$resid,$url)=&decode_symb($symb);
 6728: 
 6729:     unless ($url eq $thisfn) { return 0; }
 6730: 
 6731:     $symb=&symbclean($symb);
 6732:     $thisurl=&deversion($thisurl);
 6733:     $thisfn=&deversion($thisfn);
 6734: 
 6735:     my %bighash;
 6736:     my $okay=0;
 6737: 
 6738:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6739:                             &GDBM_READER(),0640)) {
 6740:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6741:         unless ($ids) { 
 6742:            $ids=$bighash{'ids_/'.$thisurl};
 6743:         }
 6744:         if ($ids) {
 6745: # ------------------------------------------------------------------- Has ID(s)
 6746: 	    foreach my $id (split(/\,/,$ids)) {
 6747: 	       my ($mapid,$resid)=split(/\./,$id);
 6748:                if (
 6749:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6750:    eq $symb) { 
 6751: 		   if (($env{'request.role.adv'}) ||
 6752: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6753: 		       $okay=1; 
 6754: 		   }
 6755: 	       }
 6756: 	   }
 6757:         }
 6758: 	untie(%bighash);
 6759:     }
 6760:     return $okay;
 6761: }
 6762: 
 6763: # --------------------------------------------------------------- Clean-up symb
 6764: 
 6765: sub symbclean {
 6766:     my $symb=shift;
 6767:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6768: # remove version from map
 6769:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6770: 
 6771: # remove version from URL
 6772:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6773: 
 6774: # remove wrapper
 6775: 
 6776:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6777:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6778:     return $symb;
 6779: }
 6780: 
 6781: # ---------------------------------------------- Split symb to find map and url
 6782: 
 6783: sub encode_symb {
 6784:     my ($map,$resid,$url)=@_;
 6785:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6786: }
 6787: 
 6788: sub decode_symb {
 6789:     my $symb=shift;
 6790:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6791:     my ($map,$resid,$url)=split(/___/,$symb);
 6792:     return (&fixversion($map),$resid,&fixversion($url));
 6793: }
 6794: 
 6795: sub fixversion {
 6796:     my $fn=shift;
 6797:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6798:     my %bighash;
 6799:     my $uri=&clutter($fn);
 6800:     my $key=$env{'request.course.id'}.'_'.$uri;
 6801: # is this cached?
 6802:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6803:     if (defined($cached)) { return $result; }
 6804: # unfortunately not cached, or expired
 6805:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6806: 	    &GDBM_READER(),0640)) {
 6807:  	if ($bighash{'version_'.$uri}) {
 6808:  	    my $version=$bighash{'version_'.$uri};
 6809:  	    unless (($version eq 'mostrecent') || 
 6810: 		    ($version==&getversion($uri))) {
 6811:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6812:  	    }
 6813:  	}
 6814:  	untie %bighash;
 6815:     }
 6816:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6817: }
 6818: 
 6819: sub deversion {
 6820:     my $url=shift;
 6821:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6822:     return $url;
 6823: }
 6824: 
 6825: # ------------------------------------------------------ Return symb list entry
 6826: 
 6827: sub symbread {
 6828:     my ($thisfn,$donotrecurse)=@_;
 6829:     my $cache_str='request.symbread.cached.'.$thisfn;
 6830:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6831: # no filename provided? try from environment
 6832:     unless ($thisfn) {
 6833:         if ($env{'request.symb'}) {
 6834: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6835: 	}
 6836: 	$thisfn=$env{'request.filename'};
 6837:     }
 6838:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6839: # is that filename actually a symb? Verify, clean, and return
 6840:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6841: 	if (&symbverify($thisfn,$1)) {
 6842: 	    return $env{$cache_str}=&symbclean($thisfn);
 6843: 	}
 6844:     }
 6845:     $thisfn=declutter($thisfn);
 6846:     my %hash;
 6847:     my %bighash;
 6848:     my $syval='';
 6849:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6850:         my $targetfn = $thisfn;
 6851:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6852:             $targetfn = 'adm/wrapper/'.$thisfn;
 6853:         }
 6854: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6855: 	    $targetfn=$1;
 6856: 	}
 6857:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6858:                       &GDBM_READER(),0640)) {
 6859: 	    $syval=$hash{$targetfn};
 6860:             untie(%hash);
 6861:         }
 6862: # ---------------------------------------------------------- There was an entry
 6863:         if ($syval) {
 6864: 	    #unless ($syval=~/\_\d+$/) {
 6865: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6866: 		    #&appenv('request.ambiguous' => $thisfn);
 6867: 		    #return $env{$cache_str}='';
 6868: 		#}    
 6869: 		#$syval.=$1;
 6870: 	    #}
 6871:         } else {
 6872: # ------------------------------------------------------- Was not in symb table
 6873:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6874:                             &GDBM_READER(),0640)) {
 6875: # ---------------------------------------------- Get ID(s) for current resource
 6876:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6877:               unless ($ids) { 
 6878:                  $ids=$bighash{'ids_/'.$thisfn};
 6879:               }
 6880:               unless ($ids) {
 6881: # alias?
 6882: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6883:               }
 6884:               if ($ids) {
 6885: # ------------------------------------------------------------------- Has ID(s)
 6886:                  my @possibilities=split(/\,/,$ids);
 6887:                  if ($#possibilities==0) {
 6888: # ----------------------------------------------- There is only one possibility
 6889: 		     my ($mapid,$resid)=split(/\./,$ids);
 6890: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6891: 						    $resid,$thisfn);
 6892:                  } elsif (!$donotrecurse) {
 6893: # ------------------------------------------ There is more than one possibility
 6894:                      my $realpossible=0;
 6895:                      foreach my $id (@possibilities) {
 6896: 			 my $file=$bighash{'src_'.$id};
 6897:                          if (&allowed('bre',$file)) {
 6898:          		    my ($mapid,$resid)=split(/\./,$id);
 6899:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6900: 				$realpossible++;
 6901:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6902: 						    $resid,$thisfn);
 6903:                             }
 6904: 			 }
 6905:                      }
 6906: 		     if ($realpossible!=1) { $syval=''; }
 6907:                  } else {
 6908:                      $syval='';
 6909:                  }
 6910: 	      }
 6911:               untie(%bighash)
 6912:            }
 6913:         }
 6914:         if ($syval) {
 6915: 	    return $env{$cache_str}=$syval;
 6916:         }
 6917:     }
 6918:     &appenv('request.ambiguous' => $thisfn);
 6919:     return $env{$cache_str}='';
 6920: }
 6921: 
 6922: # ---------------------------------------------------------- Return random seed
 6923: 
 6924: sub numval {
 6925:     my $txt=shift;
 6926:     $txt=~tr/A-J/0-9/;
 6927:     $txt=~tr/a-j/0-9/;
 6928:     $txt=~tr/K-T/0-9/;
 6929:     $txt=~tr/k-t/0-9/;
 6930:     $txt=~tr/U-Z/0-5/;
 6931:     $txt=~tr/u-z/0-5/;
 6932:     $txt=~s/\D//g;
 6933:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6934:     return int($txt);
 6935: }
 6936: 
 6937: sub numval2 {
 6938:     my $txt=shift;
 6939:     $txt=~tr/A-J/0-9/;
 6940:     $txt=~tr/a-j/0-9/;
 6941:     $txt=~tr/K-T/0-9/;
 6942:     $txt=~tr/k-t/0-9/;
 6943:     $txt=~tr/U-Z/0-5/;
 6944:     $txt=~tr/u-z/0-5/;
 6945:     $txt=~s/\D//g;
 6946:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6947:     my $total;
 6948:     foreach my $val (@txts) { $total+=$val; }
 6949:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6950:     return int($total);
 6951: }
 6952: 
 6953: sub numval3 {
 6954:     use integer;
 6955:     my $txt=shift;
 6956:     $txt=~tr/A-J/0-9/;
 6957:     $txt=~tr/a-j/0-9/;
 6958:     $txt=~tr/K-T/0-9/;
 6959:     $txt=~tr/k-t/0-9/;
 6960:     $txt=~tr/U-Z/0-5/;
 6961:     $txt=~tr/u-z/0-5/;
 6962:     $txt=~s/\D//g;
 6963:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6964:     my $total;
 6965:     foreach my $val (@txts) { $total+=$val; }
 6966:     if ($_64bit) { $total=(($total<<32)>>32); }
 6967:     return $total;
 6968: }
 6969: 
 6970: sub digest {
 6971:     my ($data)=@_;
 6972:     my $digest=&Digest::MD5::md5($data);
 6973:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6974:     my ($e,$f);
 6975:     {
 6976:         use integer;
 6977:         $e=($a+$b);
 6978:         $f=($c+$d);
 6979:         if ($_64bit) {
 6980:             $e=(($e<<32)>>32);
 6981:             $f=(($f<<32)>>32);
 6982:         }
 6983:     }
 6984:     if (wantarray) {
 6985: 	return ($e,$f);
 6986:     } else {
 6987: 	my $g;
 6988: 	{
 6989: 	    use integer;
 6990: 	    $g=($e+$f);
 6991: 	    if ($_64bit) {
 6992: 		$g=(($g<<32)>>32);
 6993: 	    }
 6994: 	}
 6995: 	return $g;
 6996:     }
 6997: }
 6998: 
 6999: sub latest_rnd_algorithm_id {
 7000:     return '64bit5';
 7001: }
 7002: 
 7003: sub get_rand_alg {
 7004:     my ($courseid)=@_;
 7005:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7006:     if ($courseid) {
 7007: 	return $env{"course.$courseid.rndseed"};
 7008:     }
 7009:     return &latest_rnd_algorithm_id();
 7010: }
 7011: 
 7012: sub validCODE {
 7013:     my ($CODE)=@_;
 7014:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7015:     return 0;
 7016: }
 7017: 
 7018: sub getCODE {
 7019:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7020:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7021: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7022: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7023: 	return $Apache::lonhomework::history{'resource.CODE'};
 7024:     }
 7025:     return undef;
 7026: }
 7027: 
 7028: sub rndseed {
 7029:     my ($symb,$courseid,$domain,$username)=@_;
 7030:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7031:     if (!$symb) {
 7032: 	unless ($symb=$wsymb) { return time; }
 7033:     }
 7034:     if (!$courseid) { $courseid=$wcourseid; }
 7035:     if (!$domain) { $domain=$wdomain; }
 7036:     if (!$username) { $username=$wusername }
 7037:     my $which=&get_rand_alg();
 7038: 
 7039:     if (defined(&getCODE())) {
 7040: 	if ($which eq '64bit5') {
 7041: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7042: 	} elsif ($which eq '64bit4') {
 7043: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7044: 	} else {
 7045: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7046: 	}
 7047:     } elsif ($which eq '64bit5') {
 7048: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7049:     } elsif ($which eq '64bit4') {
 7050: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7051:     } elsif ($which eq '64bit3') {
 7052: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7053:     } elsif ($which eq '64bit2') {
 7054: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7055:     } elsif ($which eq '64bit') {
 7056: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7057:     }
 7058:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7059: }
 7060: 
 7061: sub rndseed_32bit {
 7062:     my ($symb,$courseid,$domain,$username)=@_;
 7063:     {
 7064: 	use integer;
 7065: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7066: 	my $symbseed=numval($symb) << 22;
 7067: 	my $namechck=unpack("%32C*",$username) << 17;
 7068: 	my $nameseed=numval($username) << 12;
 7069: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7070: 	my $courseseed=unpack("%32C*",$courseid);
 7071: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7073: 	#&logthis("rndseed :$num:$symb");
 7074: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7075: 	return $num;
 7076:     }
 7077: }
 7078: 
 7079: sub rndseed_64bit {
 7080:     my ($symb,$courseid,$domain,$username)=@_;
 7081:     {
 7082: 	use integer;
 7083: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7084: 	my $symbseed=numval($symb) << 10;
 7085: 	my $namechck=unpack("%32S*",$username);
 7086: 	
 7087: 	my $nameseed=numval($username) << 21;
 7088: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7089: 	my $courseseed=unpack("%32S*",$courseid);
 7090: 	
 7091: 	my $num1=$symbchck+$symbseed+$namechck;
 7092: 	my $num2=$nameseed+$domainseed+$courseseed;
 7093: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7094: 	#&logthis("rndseed :$num:$symb");
 7095: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7096: 	return "$num1,$num2";
 7097:     }
 7098: }
 7099: 
 7100: sub rndseed_64bit2 {
 7101:     my ($symb,$courseid,$domain,$username)=@_;
 7102:     {
 7103: 	use integer;
 7104: 	# strings need to be an even # of cahracters long, it it is odd the
 7105:         # last characters gets thrown away
 7106: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7107: 	my $symbseed=numval($symb) << 10;
 7108: 	my $namechck=unpack("%32S*",$username.' ');
 7109: 	
 7110: 	my $nameseed=numval($username) << 21;
 7111: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7112: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7113: 	
 7114: 	my $num1=$symbchck+$symbseed+$namechck;
 7115: 	my $num2=$nameseed+$domainseed+$courseseed;
 7116: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7117: 	#&logthis("rndseed :$num:$symb");
 7118: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7119: 	return "$num1,$num2";
 7120:     }
 7121: }
 7122: 
 7123: sub rndseed_64bit3 {
 7124:     my ($symb,$courseid,$domain,$username)=@_;
 7125:     {
 7126: 	use integer;
 7127: 	# strings need to be an even # of cahracters long, it it is odd the
 7128:         # last characters gets thrown away
 7129: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7130: 	my $symbseed=numval2($symb) << 10;
 7131: 	my $namechck=unpack("%32S*",$username.' ');
 7132: 	
 7133: 	my $nameseed=numval2($username) << 21;
 7134: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7135: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7136: 	
 7137: 	my $num1=$symbchck+$symbseed+$namechck;
 7138: 	my $num2=$nameseed+$domainseed+$courseseed;
 7139: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7140: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7141: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7142: 	
 7143: 	return "$num1:$num2";
 7144:     }
 7145: }
 7146: 
 7147: sub rndseed_64bit4 {
 7148:     my ($symb,$courseid,$domain,$username)=@_;
 7149:     {
 7150: 	use integer;
 7151: 	# strings need to be an even # of cahracters long, it it is odd the
 7152:         # last characters gets thrown away
 7153: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7154: 	my $symbseed=numval3($symb) << 10;
 7155: 	my $namechck=unpack("%32S*",$username.' ');
 7156: 	
 7157: 	my $nameseed=numval3($username) << 21;
 7158: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7159: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7160: 	
 7161: 	my $num1=$symbchck+$symbseed+$namechck;
 7162: 	my $num2=$nameseed+$domainseed+$courseseed;
 7163: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7164: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7165: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7166: 	
 7167: 	return "$num1:$num2";
 7168:     }
 7169: }
 7170: 
 7171: sub rndseed_64bit5 {
 7172:     my ($symb,$courseid,$domain,$username)=@_;
 7173:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7174:     return "$num1:$num2";
 7175: }
 7176: 
 7177: sub rndseed_CODE_64bit {
 7178:     my ($symb,$courseid,$domain,$username)=@_;
 7179:     {
 7180: 	use integer;
 7181: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7182: 	my $symbseed=numval2($symb);
 7183: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7184: 	my $CODEseed=numval(&getCODE());
 7185: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7186: 	my $num1=$symbseed+$CODEchck;
 7187: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7188: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7189: 	#&logthis("rndseed :$num1:$num2:$symb");
 7190: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7191: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7192: 	return "$num1:$num2";
 7193:     }
 7194: }
 7195: 
 7196: sub rndseed_CODE_64bit4 {
 7197:     my ($symb,$courseid,$domain,$username)=@_;
 7198:     {
 7199: 	use integer;
 7200: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7201: 	my $symbseed=numval3($symb);
 7202: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7203: 	my $CODEseed=numval3(&getCODE());
 7204: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7205: 	my $num1=$symbseed+$CODEchck;
 7206: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7207: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7208: 	#&logthis("rndseed :$num1:$num2:$symb");
 7209: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7210: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7211: 	return "$num1:$num2";
 7212:     }
 7213: }
 7214: 
 7215: sub rndseed_CODE_64bit5 {
 7216:     my ($symb,$courseid,$domain,$username)=@_;
 7217:     my $code = &getCODE();
 7218:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7219:     return "$num1:$num2";
 7220: }
 7221: 
 7222: sub setup_random_from_rndseed {
 7223:     my ($rndseed)=@_;
 7224:     if ($rndseed =~/([,:])/) {
 7225: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7226: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7227:     } else {
 7228: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7229:     }
 7230: }
 7231: 
 7232: sub latest_receipt_algorithm_id {
 7233:     return 'receipt3';
 7234: }
 7235: 
 7236: sub recunique {
 7237:     my $fucourseid=shift;
 7238:     my $unique;
 7239:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7240: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7241: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7242:     } else {
 7243: 	$unique=$perlvar{'lonReceipt'};
 7244:     }
 7245:     return unpack("%32C*",$unique);
 7246: }
 7247: 
 7248: sub recprefix {
 7249:     my $fucourseid=shift;
 7250:     my $prefix;
 7251:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7252: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7253: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7254:     } else {
 7255: 	$prefix=$perlvar{'lonHostID'};
 7256:     }
 7257:     return unpack("%32C*",$prefix);
 7258: }
 7259: 
 7260: sub ireceipt {
 7261:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7262: 
 7263:     my $return =&recprefix($fucourseid).'-';
 7264: 
 7265:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7266: 	$env{'request.state'} eq 'construct') {
 7267: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7268: 	return $return;
 7269:     }
 7270: 
 7271:     my $cuname=unpack("%32C*",$funame);
 7272:     my $cudom=unpack("%32C*",$fudom);
 7273:     my $cucourseid=unpack("%32C*",$fucourseid);
 7274:     my $cusymb=unpack("%32C*",$fusymb);
 7275:     my $cunique=&recunique($fucourseid);
 7276:     my $cpart=unpack("%32S*",$part);
 7277:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7278: 
 7279: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7280: 			       
 7281: 	$return.= ($cunique%$cuname+
 7282: 		   $cunique%$cudom+
 7283: 		   $cusymb%$cuname+
 7284: 		   $cusymb%$cudom+
 7285: 		   $cucourseid%$cuname+
 7286: 		   $cucourseid%$cudom+
 7287: 		   $cpart%$cuname+
 7288: 		   $cpart%$cudom);
 7289:     } else {
 7290: 	$return.= ($cunique%$cuname+
 7291: 		   $cunique%$cudom+
 7292: 		   $cusymb%$cuname+
 7293: 		   $cusymb%$cudom+
 7294: 		   $cucourseid%$cuname+
 7295: 		   $cucourseid%$cudom);
 7296:     }
 7297:     return $return;
 7298: }
 7299: 
 7300: sub receipt {
 7301:     my ($part)=@_;
 7302:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7303:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7304: }
 7305: 
 7306: sub whichuser {
 7307:     my ($passedsymb)=@_;
 7308:     my ($symb,$courseid,$domain,$name,$publicuser);
 7309:     if (defined($env{'form.grade_symb'})) {
 7310: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7311: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7312: 	if (!$allowed &&
 7313: 	    exists($env{'request.course.sec'}) &&
 7314: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7315: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7316: 			      '/'.$env{'request.course.sec'});
 7317: 	}
 7318: 	if ($allowed) {
 7319: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7320: 	    $courseid=$tmp_courseid;
 7321: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7322: 	    ($name)=&get_env_multiple('form.grade_username');
 7323: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7324: 	}
 7325:     }
 7326:     if (!$passedsymb) {
 7327: 	$symb=&symbread();
 7328:     } else {
 7329: 	$symb=$passedsymb;
 7330:     }
 7331:     $courseid=$env{'request.course.id'};
 7332:     $domain=$env{'user.domain'};
 7333:     $name=$env{'user.name'};
 7334:     if ($name eq 'public' && $domain eq 'public') {
 7335: 	if (!defined($env{'form.username'})) {
 7336: 	    $env{'form.username'}.=time.rand(10000000);
 7337: 	}
 7338: 	$name.=$env{'form.username'};
 7339:     }
 7340:     return ($symb,$courseid,$domain,$name,$publicuser);
 7341: 
 7342: }
 7343: 
 7344: # ------------------------------------------------------------ Serves up a file
 7345: # returns either the contents of the file or 
 7346: # -1 if the file doesn't exist
 7347: #
 7348: # if the target is a file that was uploaded via DOCS, 
 7349: # a check will be made to see if a current copy exists on the local server,
 7350: # if it does this will be served, otherwise a copy will be retrieved from
 7351: # the home server for the course and stored in /home/httpd/html/userfiles on
 7352: # the local server.   
 7353: 
 7354: sub getfile {
 7355:     my ($file) = @_;
 7356:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7357:     &repcopy($file);
 7358:     return &readfile($file);
 7359: }
 7360: 
 7361: sub repcopy_userfile {
 7362:     my ($file)=@_;
 7363:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7364:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7365:     my ($cdom,$cnum,$filename) = 
 7366: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7367:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7368:     if (-e "$file") {
 7369: # we already have a local copy, check it out
 7370: 	my @fileinfo = stat($file);
 7371: 	my $rtncode;
 7372: 	my $info;
 7373: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7374: 	if ($lwpresp ne 'ok') {
 7375: # there is no such file anymore, even though we had a local copy
 7376: 	    if ($rtncode eq '404') {
 7377: 		unlink($file);
 7378: 	    }
 7379: 	    return -1;
 7380: 	}
 7381: 	if ($info < $fileinfo[9]) {
 7382: # nice, the file we have is up-to-date, just say okay
 7383: 	    return 'ok';
 7384: 	} else {
 7385: # the file is outdated, get rid of it
 7386: 	    unlink($file);
 7387: 	}
 7388:     }
 7389: # one way or the other, at this point, we don't have the file
 7390: # construct the correct path for the file
 7391:     my @parts = ($cdom,$cnum); 
 7392:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7393: 	push @parts, split(/\//,$1);
 7394:     }
 7395:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7396:     foreach my $part (@parts) {
 7397: 	$path .= '/'.$part;
 7398: 	if (!-e $path) {
 7399: 	    mkdir($path,0770);
 7400: 	}
 7401:     }
 7402: # now the path exists for sure
 7403: # get a user agent
 7404:     my $ua=new LWP::UserAgent;
 7405:     my $transferfile=$file.'.in.transfer';
 7406: # FIXME: this should flock
 7407:     if (-e $transferfile) { return 'ok'; }
 7408:     my $request;
 7409:     $uri=~s/^\///;
 7410:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7411:     my $response=$ua->request($request,$transferfile);
 7412: # did it work?
 7413:     if ($response->is_error()) {
 7414: 	unlink($transferfile);
 7415: 	&logthis("Userfile repcopy failed for $uri");
 7416: 	return -1;
 7417:     }
 7418: # worked, rename the transfer file
 7419:     rename($transferfile,$file);
 7420:     return 'ok';
 7421: }
 7422: 
 7423: sub tokenwrapper {
 7424:     my $uri=shift;
 7425:     $uri=~s|^http\://([^/]+)||;
 7426:     $uri=~s|^/||;
 7427:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7428:     my $token=$1;
 7429:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7430:     if ($udom && $uname && $file) {
 7431: 	$file=~s|(\?\.*)*$||;
 7432:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7433:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7434:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7435:                                '&tokenissued='.$perlvar{'lonHostID'};
 7436:     } else {
 7437:         return '/adm/notfound.html';
 7438:     }
 7439: }
 7440: 
 7441: # call with reqtype HEAD: get last modification time
 7442: # call with reqtype GET: get the file contents
 7443: # Do not call this with reqtype GET for large files! It loads everything into memory
 7444: #
 7445: sub getuploaded {
 7446:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7447:     $uri=~s/^\///;
 7448:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7449:     my $ua=new LWP::UserAgent;
 7450:     my $request=new HTTP::Request($reqtype,$uri);
 7451:     my $response=$ua->request($request);
 7452:     $$rtncode = $response->code;
 7453:     if (! $response->is_success()) {
 7454: 	return 'failed';
 7455:     }      
 7456:     if ($reqtype eq 'HEAD') {
 7457: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7458:     } elsif ($reqtype eq 'GET') {
 7459: 	$$info = $response->content;
 7460:     }
 7461:     return 'ok';
 7462: }
 7463: 
 7464: sub readfile {
 7465:     my $file = shift;
 7466:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7467:     my $fh;
 7468:     open($fh,"<$file");
 7469:     my $a='';
 7470:     while (my $line = <$fh>) { $a .= $line; }
 7471:     return $a;
 7472: }
 7473: 
 7474: sub filelocation {
 7475:     my ($dir,$file) = @_;
 7476:     my $location;
 7477:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7478: 
 7479:     if ($file =~ m-^/adm/-) {
 7480: 	$file=~s-^/adm/wrapper/-/-;
 7481: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7482:     }
 7483:     if ($file=~m:^/~:) { # is a contruction space reference
 7484:         $location = $file;
 7485:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7486:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7487: 	# is a correct contruction space reference
 7488:         $location = $file;
 7489:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7490:         my ($udom,$uname,$filename)=
 7491:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7492:         my $home=&homeserver($uname,$udom);
 7493:         my $is_me=0;
 7494:         my @ids=&current_machine_ids();
 7495:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7496:         if ($is_me) {
 7497:   	    $location=&propath($udom,$uname).
 7498:   	      '/userfiles/'.$filename;
 7499:         } else {
 7500:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7501:   	      $udom.'/'.$uname.'/'.$filename;
 7502:         }
 7503:     } else {
 7504:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7505:         $file=~s:^/res/:/:;
 7506:         if ( !( $file =~ m:^/:) ) {
 7507:             $location = $dir. '/'.$file;
 7508:         } else {
 7509:             $location = '/home/httpd/html/res'.$file;
 7510:         }
 7511:     }
 7512:     $location=~s://+:/:g; # remove duplicate /
 7513:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7514:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7515:     return $location;
 7516: }
 7517: 
 7518: sub hreflocation {
 7519:     my ($dir,$file)=@_;
 7520:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7521: 	$file=filelocation($dir,$file);
 7522:     } elsif ($file=~m-^/adm/-) {
 7523: 	$file=~s-^/adm/wrapper/-/-;
 7524: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7525:     }
 7526:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7527: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7528:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7529: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7530:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7531: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7532: 	    -/uploaded/$1/$2/-x;
 7533:     }
 7534:     return $file;
 7535: }
 7536: 
 7537: sub current_machine_domains {
 7538:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7539: }
 7540: 
 7541: sub machine_domains {
 7542:     my ($hostname) = @_;
 7543:     my @domains;
 7544:     my %hostname = &all_hostnames();
 7545:     while( my($id, $name) = each(%hostname)) {
 7546: #	&logthis("-$id-$name-$hostname-");
 7547: 	if ($hostname eq $name) {
 7548: 	    push(@domains,&host_domain($id));
 7549: 	}
 7550:     }
 7551:     return @domains;
 7552: }
 7553: 
 7554: sub current_machine_ids {
 7555:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7556: }
 7557: 
 7558: sub machine_ids {
 7559:     my ($hostname) = @_;
 7560:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7561:     my @ids;
 7562:     my %hostname = &all_hostnames();
 7563:     while( my($id, $name) = each(%hostname)) {
 7564: #	&logthis("-$id-$name-$hostname-");
 7565: 	if ($hostname eq $name) {
 7566: 	    push(@ids,$id);
 7567: 	}
 7568:     }
 7569:     return @ids;
 7570: }
 7571: 
 7572: sub additional_machine_domains {
 7573:     my @domains;
 7574:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7575:     while( my $line = <$fh>) {
 7576:         $line =~ s/\s//g;
 7577:         push(@domains,$line);
 7578:     }
 7579:     return @domains;
 7580: }
 7581: 
 7582: sub default_login_domain {
 7583:     my $domain = $perlvar{'lonDefDomain'};
 7584:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7585:     foreach my $posdom (&current_machine_domains(),
 7586:                         &additional_machine_domains()) {
 7587:         if (lc($posdom) eq lc($testdomain)) {
 7588:             $domain=$posdom;
 7589:             last;
 7590:         }
 7591:     }
 7592:     return $domain;
 7593: }
 7594: 
 7595: # ------------------------------------------------------------- Declutters URLs
 7596: 
 7597: sub declutter {
 7598:     my $thisfn=shift;
 7599:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7600:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7601:     $thisfn=~s/^\///;
 7602:     $thisfn=~s|^adm/wrapper/||;
 7603:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7604:     $thisfn=~s/^res\///;
 7605:     $thisfn=~s/\?.+$//;
 7606:     return $thisfn;
 7607: }
 7608: 
 7609: # ------------------------------------------------------------- Clutter up URLs
 7610: 
 7611: sub clutter {
 7612:     my $thisfn='/'.&declutter(shift);
 7613:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7614:        $thisfn='/res'.$thisfn; 
 7615:     }
 7616:     if ($thisfn !~m|/adm|) {
 7617: 	if ($thisfn =~ m|/ext/|) {
 7618: 	    $thisfn='/adm/wrapper'.$thisfn;
 7619: 	} else {
 7620: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7621: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7622: 	    if ($embstyle eq 'ssi'
 7623: 		|| ($embstyle eq 'hdn')
 7624: 		|| ($embstyle eq 'rat')
 7625: 		|| ($embstyle eq 'prv')
 7626: 		|| ($embstyle eq 'ign')) {
 7627: 		#do nothing with these
 7628: 	    } elsif (($embstyle eq 'img') 
 7629: 		|| ($embstyle eq 'emb')
 7630: 		|| ($embstyle eq 'wrp')) {
 7631: 		$thisfn='/adm/wrapper'.$thisfn;
 7632: 	    } elsif ($embstyle eq 'unk'
 7633: 		     && $thisfn!~/\.(sequence|page)$/) {
 7634: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7635: 	    } else {
 7636: #		&logthis("Got a blank emb style");
 7637: 	    }
 7638: 	}
 7639:     }
 7640:     return $thisfn;
 7641: }
 7642: 
 7643: sub clutter_with_no_wrapper {
 7644:     my $uri = &clutter(shift);
 7645:     if ($uri =~ m-^/adm/-) {
 7646: 	$uri =~ s-^/adm/wrapper/-/-;
 7647: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7648:     }
 7649:     return $uri;
 7650: }
 7651: 
 7652: sub freeze_escape {
 7653:     my ($value)=@_;
 7654:     if (ref($value)) {
 7655: 	$value=&nfreeze($value);
 7656: 	return '__FROZEN__'.&escape($value);
 7657:     }
 7658:     return &escape($value);
 7659: }
 7660: 
 7661: 
 7662: sub thaw_unescape {
 7663:     my ($value)=@_;
 7664:     if ($value =~ /^__FROZEN__/) {
 7665: 	substr($value,0,10,undef);
 7666: 	$value=&unescape($value);
 7667: 	return &thaw($value);
 7668:     }
 7669:     return &unescape($value);
 7670: }
 7671: 
 7672: sub correct_line_ends {
 7673:     my ($result)=@_;
 7674:     $$result =~s/\r\n/\n/mg;
 7675:     $$result =~s/\r/\n/mg;
 7676: }
 7677: # ================================================================ Main Program
 7678: 
 7679: sub goodbye {
 7680:    &logthis("Starting Shut down");
 7681: #not converted to using infrastruture and probably shouldn't be
 7682:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 7683: #converted
 7684: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7685:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 7686: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 7687: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 7688: #1.1 only
 7689: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 7690: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 7691: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 7692: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 7693:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 7694:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7695:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7696:    &flushcourselogs();
 7697:    &logthis("Shutting down");
 7698: }
 7699: 
 7700: sub get_dns {
 7701:     my ($url,$func,$ignore_cache) = @_;
 7702:     if (!$ignore_cache) {
 7703: 	my ($content,$cached)=
 7704: 	    &Apache::lonnet::is_cached_new('dns',$url);
 7705: 	if ($cached) {
 7706: 	    &$func($content);
 7707: 	    return;
 7708: 	}
 7709:     }
 7710: 
 7711:     my %alldns;
 7712:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7713:     foreach my $dns (<$config>) {
 7714: 	next if ($dns !~ /^\^(\S*)/x);
 7715: 	$alldns{$1} = 1;
 7716:     }
 7717:     while (%alldns) {
 7718: 	my ($dns) = keys(%alldns);
 7719: 	delete($alldns{$dns});
 7720: 	my $ua=new LWP::UserAgent;
 7721: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7722: 	my $response=$ua->request($request);
 7723: 	next if ($response->is_error());
 7724: 	my @content = split("\n",$response->content);
 7725: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 7726: 	&$func(\@content);
 7727: 	return;
 7728:     }
 7729:     close($config);
 7730:     my $which = (split('/',$url))[3];
 7731:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 7732:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 7733:     my @content = <$config>;
 7734:     &$func(\@content);
 7735:     return;
 7736: }
 7737: # ------------------------------------------------------------ Read domain file
 7738: {
 7739:     my $loaded;
 7740:     my %domain;
 7741: 
 7742:     sub parse_domain_tab {
 7743: 	my ($lines) = @_;
 7744: 	foreach my $line (@$lines) {
 7745: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7746: 
 7747: 	    chomp($line);
 7748: 	    my ($name,@elements) = split(/:/,$line,9);
 7749: 	    my %this_domain;
 7750: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7751: 			       'lang_def', 'city', 'longi', 'lati',
 7752: 			       'primary') {
 7753: 		$this_domain{$field} = shift(@elements);
 7754: 	    }
 7755: 	    $domain{$name} = \%this_domain;
 7756: 	}
 7757:     }
 7758: 
 7759:     sub reset_domain_info {
 7760: 	undef($loaded);
 7761: 	undef(%domain);
 7762:     }
 7763: 
 7764:     sub load_domain_tab {
 7765: 	my ($ignore_cache) = @_;
 7766: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 7767: 	my $fh;
 7768: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7769: 	    my @lines = <$fh>;
 7770: 	    &parse_domain_tab(\@lines);
 7771: 	}
 7772: 	close($fh);
 7773: 	$loaded = 1;
 7774:     }
 7775: 
 7776:     sub domain {
 7777: 	&load_domain_tab() if (!$loaded);
 7778: 
 7779: 	my ($name,$what) = @_;
 7780: 	return if ( !exists($domain{$name}) );
 7781: 
 7782: 	if (!$what) {
 7783: 	    return $domain{$name}{'description'};
 7784: 	}
 7785: 	return $domain{$name}{$what};
 7786:     }
 7787: }
 7788: 
 7789: 
 7790: # ------------------------------------------------------------- Read hosts file
 7791: {
 7792:     my %hostname;
 7793:     my %hostdom;
 7794:     my %libserv;
 7795:     my $loaded;
 7796: 
 7797:     sub parse_hosts_tab {
 7798: 	my ($file) = @_;
 7799: 	foreach my $configline (@$file) {
 7800: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7801: 	    next if ($configline =~ /^\^/);
 7802: 	    chomp($configline);
 7803: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7804: 	    $name=~s/\s//g;
 7805: 	    if ($id && $domain && $role && $name) {
 7806: 		$hostname{$id}=$name;
 7807: 		$hostdom{$id}=$domain;
 7808: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7809: 	    }
 7810: 	}
 7811:     }
 7812:     
 7813:     sub reset_hosts_info {
 7814: 	&reset_domain_info();
 7815: 	&reset_hosts_ip_info();
 7816: 	undef(%hostname);
 7817: 	undef(%hostdom);
 7818: 	undef(%libserv);
 7819: 	undef($loaded);
 7820:     }
 7821: 
 7822:     sub load_hosts_tab {
 7823: 	my ($ignore_cache) = @_;
 7824: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 7825: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7826: 	my @config = <$config>;
 7827: 	&parse_hosts_tab(\@config);
 7828: 	close($config);
 7829: 	$loaded=1;
 7830:     }
 7831: 
 7832:     sub hostname {
 7833: 	&load_hosts_tab() if (!$loaded);
 7834: 
 7835: 	my ($lonid) = @_;
 7836: 	return $hostname{$lonid};
 7837:     }
 7838: 
 7839:     sub all_hostnames {
 7840: 	&load_hosts_tab() if (!$loaded);
 7841: 
 7842: 	return %hostname;
 7843:     }
 7844: 
 7845:     sub is_library {
 7846: 	&load_hosts_tab() if (!$loaded);
 7847: 
 7848: 	return exists($libserv{$_[0]});
 7849:     }
 7850: 
 7851:     sub all_library {
 7852: 	&load_hosts_tab() if (!$loaded);
 7853: 
 7854: 	return %libserv;
 7855:     }
 7856: 
 7857:     sub get_servers {
 7858: 	&load_hosts_tab() if (!$loaded);
 7859: 
 7860: 	my ($domain,$type) = @_;
 7861: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7862: 	                                          : %hostname;
 7863: 	my %result;
 7864: 	if (ref($domain) eq 'ARRAY') {
 7865: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7866: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7867: 		    $result{$host} = $hostname;
 7868: 		}
 7869: 	    }
 7870: 	} else {
 7871: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7872: 		if ($hostdom{$host} eq $domain) {
 7873: 		    $result{$host} = $hostname;
 7874: 		}
 7875: 	    }
 7876: 	}
 7877: 	return %result;
 7878:     }
 7879: 
 7880:     sub host_domain {
 7881: 	&load_hosts_tab() if (!$loaded);
 7882: 
 7883: 	my ($lonid) = @_;
 7884: 	return $hostdom{$lonid};
 7885:     }
 7886: 
 7887:     sub all_domains {
 7888: 	&load_hosts_tab() if (!$loaded);
 7889: 
 7890: 	my %seen;
 7891: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7892: 	return @uniq;
 7893:     }
 7894: }
 7895: 
 7896: { 
 7897:     my %iphost;
 7898:     my %name_to_ip;
 7899:     my %lonid_to_ip;
 7900: 
 7901:     my %valid_ip;
 7902:     sub valid_ip {
 7903: 	my ($ip) = @_;
 7904: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
 7905: 	    return 1;	
 7906: 	}
 7907: 	my $name = gethostbyip($ip);
 7908: 	my $lonid = &hostname($name);
 7909: 	if (defined($lonid)) {
 7910: 	    $valid_ip{$ip} = $lonid;
 7911: 	    return 1;
 7912: 	}
 7913: 	my %iphosts = &get_iphost();
 7914: 	if (ref($iphost{$ip})) {
 7915: 	    return 1;	
 7916: 	}
 7917:     }
 7918: 
 7919:     sub get_hosts_from_ip {
 7920: 	my ($ip) = @_;
 7921: 	my %iphosts = &get_iphost();
 7922: 	if (ref($iphosts{$ip})) {
 7923: 	    return @{$iphosts{$ip}};
 7924: 	}
 7925: 	return;
 7926:     }
 7927:     
 7928:     sub reset_hosts_ip_info {
 7929: 	undef(%iphost);
 7930: 	undef(%name_to_ip);
 7931: 	undef(%lonid_to_ip);
 7932:     }
 7933: 
 7934:     sub get_host_ip {
 7935: 	my ($lonid) = @_;
 7936: 	if (exists($lonid_to_ip{$lonid})) {
 7937: 	    return $lonid_to_ip{$lonid};
 7938: 	}
 7939: 	my $name=&hostname($lonid);
 7940:    	my $ip = gethostbyname($name);
 7941: 	return if (!$ip || length($ip) ne 4);
 7942: 	$ip=inet_ntoa($ip);
 7943: 	$name_to_ip{$name}   = $ip;
 7944: 	$lonid_to_ip{$lonid} = $ip;
 7945: 	return $ip;
 7946:     }
 7947:     
 7948:     sub get_iphost {
 7949: 	my ($ignore_cache) = @_;
 7950: 	if (!$ignore_cache) {
 7951: 	    if (%iphost) {
 7952: 		return %iphost;
 7953: 	    }
 7954: 	    my ($ip_info,$cached)=
 7955: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 7956: 	    if ($cached) {
 7957: 		%iphost      = %{$ip_info->[0]};
 7958: 		%name_to_ip  = %{$ip_info->[1]};
 7959: 		%lonid_to_ip = %{$ip_info->[2]};
 7960: 		return %iphost;
 7961: 	    }
 7962: 	}
 7963: 	my %hostname = &all_hostnames();
 7964: 	foreach my $id (keys(%hostname)) {
 7965: 	    my $name=&hostname($id);
 7966: 	    my $ip;
 7967: 	    if (!exists($name_to_ip{$name})) {
 7968: 		$ip = gethostbyname($name);
 7969: 		if (!$ip || length($ip) ne 4) {
 7970: 		    &logthis("Skipping host $id name $name no IP found");
 7971: 		    next;
 7972: 		}
 7973: 		$ip=inet_ntoa($ip);
 7974: 		$name_to_ip{$name} = $ip;
 7975: 	    } else {
 7976: 		$ip = $name_to_ip{$name};
 7977: 	    }
 7978: 	    $lonid_to_ip{$id} = $ip;
 7979: 	    push(@{$iphost{$ip}},$id);
 7980: 	}
 7981: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 7982: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 7983: 				      24*60*60);
 7984: 
 7985: 	return %iphost;
 7986:     }
 7987: }
 7988: 
 7989: BEGIN {
 7990: 
 7991: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7992:     unless ($readit) {
 7993: {
 7994:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7995:     %perlvar = (%perlvar,%{$configvars});
 7996: }
 7997: 
 7998: 
 7999: # ------------------------------------------------------ Read spare server file
 8000: {
 8001:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8002: 
 8003:     while (my $configline=<$config>) {
 8004:        chomp($configline);
 8005:        if ($configline) {
 8006: 	   my ($host,$type) = split(':',$configline,2);
 8007: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8008: 	   push(@{ $spareid{$type} }, $host);
 8009:        }
 8010:     }
 8011:     close($config);
 8012: }
 8013: # ------------------------------------------------------------ Read permissions
 8014: {
 8015:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8016: 
 8017:     while (my $configline=<$config>) {
 8018: 	chomp($configline);
 8019: 	if ($configline) {
 8020: 	    my ($role,$perm)=split(/ /,$configline);
 8021: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8022: 	}
 8023:     }
 8024:     close($config);
 8025: }
 8026: 
 8027: # -------------------------------------------- Read plain texts for permissions
 8028: {
 8029:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8030: 
 8031:     while (my $configline=<$config>) {
 8032: 	chomp($configline);
 8033: 	if ($configline) {
 8034: 	    my ($short,@plain)=split(/:/,$configline);
 8035:             %{$prp{$short}} = ();
 8036: 	    if (@plain > 0) {
 8037:                 $prp{$short}{'std'} = $plain[0];
 8038:                 for (my $i=1; $i<@plain; $i++) {
 8039:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8040:                 }
 8041:             }
 8042: 	}
 8043:     }
 8044:     close($config);
 8045: }
 8046: 
 8047: # ---------------------------------------------------------- Read package table
 8048: {
 8049:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8050: 
 8051:     while (my $configline=<$config>) {
 8052: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8053: 	chomp($configline);
 8054: 	my ($short,$plain)=split(/:/,$configline);
 8055: 	my ($pack,$name)=split(/\&/,$short);
 8056: 	if ($plain ne '') {
 8057: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8058: 	    $packagetab{$short}=$plain; 
 8059: 	}
 8060:     }
 8061:     close($config);
 8062: }
 8063: 
 8064: # ------------- set up temporary directory
 8065: {
 8066:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8067: 
 8068: }
 8069: 
 8070: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8071: 				'compress_threshold'=> 20_000,
 8072:  			        });
 8073: 
 8074: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8075: $dumpcount=0;
 8076: 
 8077: &logtouch();
 8078: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8079: $readit=1;
 8080:     {
 8081: 	use integer;
 8082: 	my $test=(2**32)+1;
 8083: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8084: 	&logthis(" Detected 64bit platform ($_64bit)");
 8085:     }
 8086: }
 8087: }
 8088: 
 8089: 1;
 8090: __END__
 8091: 
 8092: =pod
 8093: 
 8094: =head1 NAME
 8095: 
 8096: Apache::lonnet - Subroutines to ask questions about things in the network.
 8097: 
 8098: =head1 SYNOPSIS
 8099: 
 8100: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8101: 
 8102:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8103: 
 8104: Common parameters:
 8105: 
 8106: =over 4
 8107: 
 8108: =item *
 8109: 
 8110: $uname : an internal username (if $cname expecting a course Id specifically)
 8111: 
 8112: =item *
 8113: 
 8114: $udom : a domain (if $cdom expecting a course's domain specifically)
 8115: 
 8116: =item *
 8117: 
 8118: $symb : a resource instance identifier
 8119: 
 8120: =item *
 8121: 
 8122: $namespace : the name of a .db file that contains the data needed or
 8123: being set.
 8124: 
 8125: =back
 8126: 
 8127: =head1 OVERVIEW
 8128: 
 8129: lonnet provides subroutines which interact with the
 8130: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8131: about classes, users, and resources.
 8132: 
 8133: For many of these objects you can also use this to store data about
 8134: them or modify them in various ways.
 8135: 
 8136: =head2 Symbs
 8137: 
 8138: To identify a specific instance of a resource, LON-CAPA uses symbols
 8139: or "symbs"X<symb>. These identifiers are built from the URL of the
 8140: map, the resource number of the resource in the map, and the URL of
 8141: the resource itself. The latter is somewhat redundant, but might help
 8142: if maps change.
 8143: 
 8144: An example is
 8145: 
 8146:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8147: 
 8148: The respective map entry is
 8149: 
 8150:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8151:   title="Problem 2">
 8152:  </resource>
 8153: 
 8154: Symbs are used by the random number generator, as well as to store and
 8155: restore data specific to a certain instance of for example a problem.
 8156: 
 8157: =head2 Storing And Retrieving Data
 8158: 
 8159: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8160: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8161: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8162: is is the non-critical message twin of cstore. These functions are for
 8163: handlers to store a perl hash to a user's permanent data space in an
 8164: easy manner, and to retrieve it again on another call. It is expected
 8165: that a handler would use this once at the beginning to retrieve data,
 8166: and then again once at the end to send only the new data back.
 8167: 
 8168: The data is stored in the user's data directory on the user's
 8169: homeserver under the ID of the course.
 8170: 
 8171: The hash that is returned by restore will have all of the previous
 8172: value for all of the elements of the hash.
 8173: 
 8174: Example:
 8175: 
 8176:  #creating a hash
 8177:  my %hash;
 8178:  $hash{'foo'}='bar';
 8179: 
 8180:  #storing it
 8181:  &Apache::lonnet::cstore(\%hash);
 8182: 
 8183:  #changing a value
 8184:  $hash{'foo'}='notbar';
 8185: 
 8186:  #adding a new value
 8187:  $hash{'bar'}='foo';
 8188:  &Apache::lonnet::cstore(\%hash);
 8189: 
 8190:  #retrieving the hash
 8191:  my %history=&Apache::lonnet::restore();
 8192: 
 8193:  #print the hash
 8194:  foreach my $key (sort(keys(%history))) {
 8195:    print("\%history{$key} = $history{$key}");
 8196:  }
 8197: 
 8198: Will print out:
 8199: 
 8200:  %history{1:foo} = bar
 8201:  %history{1:keys} = foo:timestamp
 8202:  %history{1:timestamp} = 990455579
 8203:  %history{2:bar} = foo
 8204:  %history{2:foo} = notbar
 8205:  %history{2:keys} = foo:bar:timestamp
 8206:  %history{2:timestamp} = 990455580
 8207:  %history{bar} = foo
 8208:  %history{foo} = notbar
 8209:  %history{timestamp} = 990455580
 8210:  %history{version} = 2
 8211: 
 8212: Note that the special hash entries C<keys>, C<version> and
 8213: C<timestamp> were added to the hash. C<version> will be equal to the
 8214: total number of versions of the data that have been stored. The
 8215: C<timestamp> attribute will be the UNIX time the hash was
 8216: stored. C<keys> is available in every historical section to list which
 8217: keys were added or changed at a specific historical revision of a
 8218: hash.
 8219: 
 8220: B<Warning>: do not store the hash that restore returns directly. This
 8221: will cause a mess since it will restore the historical keys as if the
 8222: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8223: 
 8224: Calling convention:
 8225: 
 8226:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8227:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8228: 
 8229: For more detailed information, see lonnet specific documentation.
 8230: 
 8231: =head1 RETURN MESSAGES
 8232: 
 8233: =over 4
 8234: 
 8235: =item * B<con_lost>: unable to contact remote host
 8236: 
 8237: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8238: when the connection is brought back up
 8239: 
 8240: =item * B<con_failed>: unable to contact remote host and unable to save message
 8241: for later delivery
 8242: 
 8243: =item * B<error:>: an error a occured, a description of the error follows the :
 8244: 
 8245: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8246: that was requested
 8247: 
 8248: =back
 8249: 
 8250: =head1 PUBLIC SUBROUTINES
 8251: 
 8252: =head2 Session Environment Functions
 8253: 
 8254: =over 4
 8255: 
 8256: =item * 
 8257: X<appenv()>
 8258: B<appenv(%hash)>: the value of %hash is written to
 8259: the user envirnoment file, and will be restored for each access this
 8260: user makes during this session, also modifies the %env for the current
 8261: process
 8262: 
 8263: =item *
 8264: X<delenv()>
 8265: B<delenv($regexp)>: removes all items from the session
 8266: environment file that matches the regular expression in $regexp. The
 8267: values are also delted from the current processes %env.
 8268: 
 8269: =item * get_env_multiple($name) 
 8270: 
 8271: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8272: values may be defined and end up as an array ref.
 8273: 
 8274: returns an array of values
 8275: 
 8276: =back
 8277: 
 8278: =head2 User Information
 8279: 
 8280: =over 4
 8281: 
 8282: =item *
 8283: X<queryauthenticate()>
 8284: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8285: authentication scheme
 8286: 
 8287: =item *
 8288: X<authenticate()>
 8289: B<authenticate($uname,$upass,$udom)>: try to
 8290: authenticate user from domain's lib servers (first use the current
 8291: one). C<$upass> should be the users password.
 8292: 
 8293: =item *
 8294: X<homeserver()>
 8295: B<homeserver($uname,$udom)>: find the server which has
 8296: the user's directory and files (there must be only one), this caches
 8297: the answer, and also caches if there is a borken connection.
 8298: 
 8299: =item *
 8300: X<idget()>
 8301: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8302: (IDs are a unique resource in a domain, there must be only 1 ID per
 8303: username, and only 1 username per ID in a specific domain) (returns
 8304: hash: id=>name,id=>name)
 8305: 
 8306: =item *
 8307: X<idrget()>
 8308: B<idrget($udom,@unames)>: find the IDs behind a list of
 8309: usernames (returns hash: name=>id,name=>id)
 8310: 
 8311: =item *
 8312: X<idput()>
 8313: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8314: 
 8315: =item *
 8316: X<rolesinit()>
 8317: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8318: 
 8319: =item *
 8320: X<getsection()>
 8321: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8322: course $cname, return section name/number or '' for "not in course"
 8323: and '-1' for "no section"
 8324: 
 8325: =item *
 8326: X<userenvironment()>
 8327: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8328: passed in @what from the requested user's environment, returns a hash
 8329: 
 8330: =item * 
 8331: X<userlog_query()>
 8332: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8333: activity.log file. %filters defines filters applied when parsing the
 8334: log file. These can be start or end timestamps, or the type of action
 8335: - log to look for Login or Logout events, check for Checkin or
 8336: Checkout, role for role selection. The response is in the form
 8337: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8338: escaped strings of the action recorded in the activity.log file.
 8339: 
 8340: =back
 8341: 
 8342: =head2 User Roles
 8343: 
 8344: =over 4
 8345: 
 8346: =item *
 8347: 
 8348: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8349:  F: full access
 8350:  U,I,K: authentication modes (cxx only)
 8351:  '': forbidden
 8352:  1: user needs to choose course
 8353:  2: browse allowed
 8354:  A: passphrase authentication needed
 8355: 
 8356: =item *
 8357: 
 8358: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8359: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8360: and course level
 8361: 
 8362: =item *
 8363: 
 8364: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8365: explanation of a user role term
 8366: 
 8367: =item *
 8368: 
 8369: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8370: All arguments are optional. Returns a hash of a roles, either for
 8371: co-author/assistant author roles for a user's Construction Space
 8372: (default), or if $context is 'user', roles for the user himself,
 8373: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8374: and value is set to colon-separated start and end times for the role.
 8375: If no username and domain are specified, will default to current
 8376: user/domain. Types, roles, and roledoms are references to arrays,
 8377: of role statuses (active, future or previous), roles 
 8378: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8379: to restrict the list of roles reported. If no array ref is 
 8380: provided for types, will default to return only active roles.
 8381: 
 8382: =back
 8383: 
 8384: =head2 User Modification
 8385: 
 8386: =over 4
 8387: 
 8388: =item *
 8389: 
 8390: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8391: user for the level given by URL.  Optional start and end dates (leave empty
 8392: string or zero for "no date")
 8393: 
 8394: =item *
 8395: 
 8396: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8397: change a users, password, possible return values are: ok,
 8398: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8399: refused
 8400: 
 8401: =item *
 8402: 
 8403: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8404: 
 8405: =item *
 8406: 
 8407: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8408: modify user
 8409: 
 8410: =item *
 8411: 
 8412: modifystudent
 8413: 
 8414: modify a students enrollment and identification information.
 8415: The course id is resolved based on the current users environment.  
 8416: This means the envoking user must be a course coordinator or otherwise
 8417: associated with a course.
 8418: 
 8419: This call is essentially a wrapper for lonnet::modifyuser and
 8420: lonnet::modify_student_enrollment
 8421: 
 8422: Inputs: 
 8423: 
 8424: =over 4
 8425: 
 8426: =item B<$udom> Students loncapa domain
 8427: 
 8428: =item B<$uname> Students loncapa login name
 8429: 
 8430: =item B<$uid> Students id/student number
 8431: 
 8432: =item B<$umode> Students authentication mode
 8433: 
 8434: =item B<$upass> Students password
 8435: 
 8436: =item B<$first> Students first name
 8437: 
 8438: =item B<$middle> Students middle name
 8439: 
 8440: =item B<$last> Students last name
 8441: 
 8442: =item B<$gene> Students generation
 8443: 
 8444: =item B<$usec> Students section in course
 8445: 
 8446: =item B<$end> Unix time of the roles expiration
 8447: 
 8448: =item B<$start> Unix time of the roles start date
 8449: 
 8450: =item B<$forceid> If defined, allow $uid to be changed
 8451: 
 8452: =item B<$desiredhome> server to use as home server for student
 8453: 
 8454: =back
 8455: 
 8456: =item *
 8457: 
 8458: modify_student_enrollment
 8459: 
 8460: Change a students enrollment status in a class.  The environment variable
 8461: 'role.request.course' must be defined for this function to proceed.
 8462: 
 8463: Inputs:
 8464: 
 8465: =over 4
 8466: 
 8467: =item $udom, students domain
 8468: 
 8469: =item $uname, students name
 8470: 
 8471: =item $uid, students user id
 8472: 
 8473: =item $first, students first name
 8474: 
 8475: =item $middle
 8476: 
 8477: =item $last
 8478: 
 8479: =item $gene
 8480: 
 8481: =item $usec
 8482: 
 8483: =item $end
 8484: 
 8485: =item $start
 8486: 
 8487: =back
 8488: 
 8489: 
 8490: =item *
 8491: 
 8492: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8493: custom role; give a custom role to a user for the level given by URL.  Specify
 8494: name and domain of role author, and role name
 8495: 
 8496: =item *
 8497: 
 8498: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8499: 
 8500: =item *
 8501: 
 8502: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8503: 
 8504: =back
 8505: 
 8506: =head2 Course Infomation
 8507: 
 8508: =over 4
 8509: 
 8510: =item *
 8511: 
 8512: coursedescription($courseid) : returns a hash of information about the
 8513: specified course id, including all environment settings for the
 8514: course, the description of the course will be in the hash under the
 8515: key 'description'
 8516: 
 8517: =item *
 8518: 
 8519: resdata($name,$domain,$type,@which) : request for current parameter
 8520: setting for a specific $type, where $type is either 'course' or 'user',
 8521: @what should be a list of parameters to ask about. This routine caches
 8522: answers for 5 minutes.
 8523: 
 8524: =back
 8525: 
 8526: =head2 Course Modification
 8527: 
 8528: =over 4
 8529: 
 8530: =item *
 8531: 
 8532: writecoursepref($courseid,%prefs) : write preferences (environment
 8533: database) for a course
 8534: 
 8535: =item *
 8536: 
 8537: createcourse($udom,$description,$url) : make/modify course
 8538: 
 8539: =back
 8540: 
 8541: =head2 Resource Subroutines
 8542: 
 8543: =over 4
 8544: 
 8545: =item *
 8546: 
 8547: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8548: 
 8549: =item *
 8550: 
 8551: repcopy($filename) : subscribes to the requested file, and attempts to
 8552: replicate from the owning library server, Might return
 8553: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8554: 'bad_request', also attempts to grab the metadata for the
 8555: resource. Expects the local filesystem pathname
 8556: (/home/httpd/html/res/....)
 8557: 
 8558: =back
 8559: 
 8560: =head2 Resource Information
 8561: 
 8562: =over 4
 8563: 
 8564: =item *
 8565: 
 8566: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8567: a vairety of different possible values, $varname should be a request
 8568: string, and the other parameters can be used to specify who and what
 8569: one is asking about.
 8570: 
 8571: Possible values for $varname are environment.lastname (or other item
 8572: from the envirnment hash), user.name (or someother aspect about the
 8573: user), resource.0.maxtries (or some other part and parameter of a
 8574: resource)
 8575: 
 8576: =item *
 8577: 
 8578: directcondval($number) : get current value of a condition; reads from a state
 8579: string
 8580: 
 8581: =item *
 8582: 
 8583: condval($condidx) : value of condition index based on state
 8584: 
 8585: =item *
 8586: 
 8587: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8588: resource's metadata, $what should be either a specific key, or either
 8589: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8590: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8591: 
 8592: this function automatically caches all requests
 8593: 
 8594: =item *
 8595: 
 8596: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8597: network of library servers; returns file handle of where SQL and regex results
 8598: will be stored for query
 8599: 
 8600: =item *
 8601: 
 8602: symbread($filename) : return symbolic list entry (filename argument optional);
 8603: returns the data handle
 8604: 
 8605: =item *
 8606: 
 8607: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8608: a possible symb for the URL in $thisfn, and if is an encryypted
 8609: resource that the user accessed using /enc/ returns a 1 on success, 0
 8610: on failure, user must be in a course, as it assumes the existance of
 8611: the course initial hash, and uses $env('request.course.id'}
 8612: 
 8613: 
 8614: =item *
 8615: 
 8616: symbclean($symb) : removes versions numbers from a symb, returns the
 8617: cleaned symb
 8618: 
 8619: =item *
 8620: 
 8621: is_on_map($uri) : checks if the $uri is somewhere on the current
 8622: course map, user must be in a course for it to work.
 8623: 
 8624: =item *
 8625: 
 8626: numval($salt) : return random seed value (addend for rndseed)
 8627: 
 8628: =item *
 8629: 
 8630: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8631: a random seed, all arguments are optional, if they aren't sent it uses the
 8632: environment to derive them. Note: if symb isn't sent and it can't get one
 8633: from &symbread it will use the current time as its return value
 8634: 
 8635: =item *
 8636: 
 8637: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8638: unfakeable, receipt
 8639: 
 8640: =item *
 8641: 
 8642: receipt() : API to ireceipt working off of env values; given out to users
 8643: 
 8644: =item *
 8645: 
 8646: countacc($url) : count the number of accesses to a given URL
 8647: 
 8648: =item *
 8649: 
 8650: 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
 8651: 
 8652: =item *
 8653: 
 8654: 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)
 8655: 
 8656: =item *
 8657: 
 8658: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8659: 
 8660: =item *
 8661: 
 8662: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8663: forcing spreadsheet to reevaluate the resource scores next time.
 8664: 
 8665: =back
 8666: 
 8667: =head2 Storing/Retreiving Data
 8668: 
 8669: =over 4
 8670: 
 8671: =item *
 8672: 
 8673: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8674: for this url; hashref needs to be given and should be a \%hashname; the
 8675: remaining args aren't required and if they aren't passed or are '' they will
 8676: be derived from the env
 8677: 
 8678: =item *
 8679: 
 8680: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8681: uses critical subroutine
 8682: 
 8683: =item *
 8684: 
 8685: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8686: all args are optional
 8687: 
 8688: =item *
 8689: 
 8690: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8691: dumps the complete (or key matching regexp) namespace into a hash
 8692: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8693: normally &store()ed into
 8694: 
 8695: $range should be either an integer '100' (give me the first 100
 8696:                                            matching records)
 8697:               or be  two integers sperated by a - with no spaces
 8698:                  '30-50' (give me the 30th through the 50th matching
 8699:                           records)
 8700: 
 8701: 
 8702: =item *
 8703: 
 8704: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8705: replaces a &store() version of data with a replacement set of data
 8706: for a particular resource in a namespace passed in the $storehash hash 
 8707: reference
 8708: 
 8709: =item *
 8710: 
 8711: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8712: works very similar to store/cstore, but all data is stored in a
 8713: temporary location and can be reset using tmpreset, $storehash should
 8714: be a hash reference, returns nothing on success
 8715: 
 8716: =item *
 8717: 
 8718: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8719: similar to restore, but all data is stored in a temporary location and
 8720: can be reset using tmpreset. Returns a hash of values on success,
 8721: error string otherwise.
 8722: 
 8723: =item *
 8724: 
 8725: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8726: deltes all keys for $symb form the temporary storage hash.
 8727: 
 8728: =item *
 8729: 
 8730: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8731: reference filled in from namesp ($udom and $uname are optional)
 8732: 
 8733: =item *
 8734: 
 8735: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8736: namesp ($udom and $uname are optional)
 8737: 
 8738: =item *
 8739: 
 8740: dump($namespace,$udom,$uname,$regexp,$range) : 
 8741: dumps the complete (or key matching regexp) namespace into a hash
 8742: ($udom, $uname, $regexp, $range are optional)
 8743: 
 8744: $range should be either an integer '100' (give me the first 100
 8745:                                            matching records)
 8746:               or be  two integers sperated by a - with no spaces
 8747:                  '30-50' (give me the 30th through the 50th matching
 8748:                           records)
 8749: =item *
 8750: 
 8751: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8752: $store can be a scalar, an array reference, or if the amount to be 
 8753: incremented is > 1, a hash reference.
 8754: 
 8755: ($udom and $uname are optional)
 8756: 
 8757: =item *
 8758: 
 8759: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8760: ($udom and $uname are optional)
 8761: 
 8762: =item *
 8763: 
 8764: cput($namespace,$storehash,$udom,$uname) : critical put
 8765: ($udom and $uname are optional)
 8766: 
 8767: =item *
 8768: 
 8769: newput($namespace,$storehash,$udom,$uname) :
 8770: 
 8771: Attempts to store the items in the $storehash, but only if they don't
 8772: currently exist, if this succeeds you can be certain that you have 
 8773: successfully created a new key value pair in the $namespace db.
 8774: 
 8775: 
 8776: Args:
 8777:  $namespace: name of database to store values to
 8778:  $storehash: hashref to store to the db
 8779:  $udom: (optional) domain of user containing the db
 8780:  $uname: (optional) name of user caontaining the db
 8781: 
 8782: Returns:
 8783:  'ok' -> succeeded in storing all keys of $storehash
 8784:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8785:                         least <key> already existed in the db (other
 8786:                         requested keys may also already exist)
 8787:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8788:  'con_lost' -> unable to contact request server
 8789:  'refused' -> action was not allowed by remote machine
 8790: 
 8791: 
 8792: =item *
 8793: 
 8794: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8795: reference filled in from namesp (encrypts the return communication)
 8796: ($udom and $uname are optional)
 8797: 
 8798: =item *
 8799: 
 8800: log($udom,$name,$home,$message) : write to permanent log for user; use
 8801: critical subroutine
 8802: 
 8803: =item *
 8804: 
 8805: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8806: array reference filled in from namespace found in domain level on either
 8807: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8808: 
 8809: =item *
 8810: 
 8811: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8812: domain level either on specified domain server ($uhome) or primary domain 
 8813: server ($udom and $uhome are optional)
 8814: 
 8815: =back
 8816: 
 8817: =head2 Network Status Functions
 8818: 
 8819: =over 4
 8820: 
 8821: =item *
 8822: 
 8823: dirlist($uri) : return directory list based on URI
 8824: 
 8825: =item *
 8826: 
 8827: spareserver() : find server with least workload from spare.tab
 8828: 
 8829: =back
 8830: 
 8831: =head2 Apache Request
 8832: 
 8833: =over 4
 8834: 
 8835: =item *
 8836: 
 8837: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8838: localhost, posts hash
 8839: 
 8840: =back
 8841: 
 8842: =head2 Data to String to Data
 8843: 
 8844: =over 4
 8845: 
 8846: =item *
 8847: 
 8848: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8849: and '&' separators, supports elements that are arrayrefs and hashrefs
 8850: 
 8851: =item *
 8852: 
 8853: hashref2str($hashref) : convert a hashref into a string complete with
 8854: escaping and '=' and '&' separators, supports elements that are
 8855: arrayrefs and hashrefs
 8856: 
 8857: =item *
 8858: 
 8859: arrayref2str($arrayref) : convert an arrayref into a string complete
 8860: with escaping and '&' separators, supports elements that are arrayrefs
 8861: and hashrefs
 8862: 
 8863: =item *
 8864: 
 8865: str2hash($string) : convert string to hash using unescaping and
 8866: splitting on '=' and '&', supports elements that are arrayrefs and
 8867: hashrefs
 8868: 
 8869: =item *
 8870: 
 8871: str2array($string) : convert string to hash using unescaping and
 8872: splitting on '&', supports elements that are arrayrefs and hashrefs
 8873: 
 8874: =back
 8875: 
 8876: =head2 Logging Routines
 8877: 
 8878: =over 4
 8879: 
 8880: These routines allow one to make log messages in the lonnet.log and
 8881: lonnet.perm logfiles.
 8882: 
 8883: =item *
 8884: 
 8885: logtouch() : make sure the logfile, lonnet.log, exists
 8886: 
 8887: =item *
 8888: 
 8889: logthis() : append message to the normal lonnet.log file, it gets
 8890: preiodically rolled over and deleted.
 8891: 
 8892: =item *
 8893: 
 8894: logperm() : append a permanent message to lonnet.perm.log, this log
 8895: file never gets deleted by any automated portion of the system, only
 8896: messages of critical importance should go in here.
 8897: 
 8898: =back
 8899: 
 8900: =head2 General File Helper Routines
 8901: 
 8902: =over 4
 8903: 
 8904: =item *
 8905: 
 8906: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8907: (a) files in /uploaded
 8908:   (i) If a local copy of the file exists - 
 8909:       compares modification date of local copy with last-modified date for 
 8910:       definitive version stored on home server for course. If local copy is 
 8911:       stale, requests a new version from the home server and stores it. 
 8912:       If the original has been removed from the home server, then local copy 
 8913:       is unlinked.
 8914:   (ii) If local copy does not exist -
 8915:       requests the file from the home server and stores it. 
 8916:   
 8917:   If $caller is 'uploadrep':  
 8918:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8919:     for request for files originally uploaded via DOCS. 
 8920:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8921:   
 8922:   Otherwise:
 8923:      This indicates a call from the content generation phase of the request.
 8924:      -  returns the entire contents of the file or -1.
 8925:      
 8926: (b) files in /res
 8927:    - returns the entire contents of a file or -1; 
 8928:    it properly subscribes to and replicates the file if neccessary.
 8929: 
 8930: 
 8931: =item *
 8932: 
 8933: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8934:                   reference
 8935: 
 8936: returns either a stat() list of data about the file or an empty list
 8937: if the file doesn't exist or couldn't find out about it (connection
 8938: problems or user unknown)
 8939: 
 8940: =item *
 8941: 
 8942: filelocation($dir,$file) : returns file system location of a file
 8943: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8944: directory that relative $file lookups are to looked in ($dir of /a/dir
 8945: and a file of ../bob will become /a/bob)
 8946: 
 8947: =item *
 8948: 
 8949: hreflocation($dir,$file) : returns file system location or a URL; same as
 8950: filelocation except for hrefs
 8951: 
 8952: =item *
 8953: 
 8954: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8955: 
 8956: =back
 8957: 
 8958: =head2 Usererfile file routines (/uploaded*)
 8959: 
 8960: =over 4
 8961: 
 8962: =item *
 8963: 
 8964: userfileupload(): main rotine for putting a file in a user or course's
 8965:                   filespace, arguments are,
 8966: 
 8967:  formname - required - this is the name of the element in $env where the
 8968:            filename, and the contents of the file to create/modifed exist
 8969:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8970:            contents of the file is located in $env{'form.'.$formname}
 8971:  coursedoc - if true, store the file in the course of the active role
 8972:              of the current user
 8973:  subdir - required - subdirectory to put the file in under ../userfiles/
 8974:          if undefined, it will be placed in "unknown"
 8975: 
 8976:  (This routine calls clean_filename() to remove any dangerous
 8977:  characters from the filename, and then calls finuserfileupload() to
 8978:  complete the transaction)
 8979: 
 8980:  returns either the url of the uploaded file (/uploaded/....) if successful
 8981:  and /adm/notfound.html if unsuccessful
 8982: 
 8983: =item *
 8984: 
 8985: clean_filename(): routine for cleaing a filename up for storage in
 8986:                  userfile space, argument is:
 8987: 
 8988:  filename - proposed filename
 8989: 
 8990: returns: the new clean filename
 8991: 
 8992: =item *
 8993: 
 8994: finishuserfileupload(): routine that creaes and sends the file to
 8995: userspace, probably shouldn't be called directly
 8996: 
 8997:   docuname: username or courseid of destination for the file
 8998:   docudom: domain of user/course of destination for the file
 8999:   formname: same as for userfileupload()
 9000:   fname: filename (inculding subdirectories) for the file
 9001: 
 9002:  returns either the url of the uploaded file (/uploaded/....) if successful
 9003:  and /adm/notfound.html if unsuccessful
 9004: 
 9005: =item *
 9006: 
 9007: renameuserfile(): renames an existing userfile to a new name
 9008: 
 9009:   Args:
 9010:    docuname: username or courseid of destination for the file
 9011:    docudom: domain of user/course of destination for the file
 9012:    old: current file name (including any subdirs under userfiles)
 9013:    new: desired file name (including any subdirs under userfiles)
 9014: 
 9015: =item *
 9016: 
 9017: mkdiruserfile(): creates a directory is a userfiles dir
 9018: 
 9019:   Args:
 9020:    docuname: username or courseid of destination for the file
 9021:    docudom: domain of user/course of destination for the file
 9022:    dir: dir to create (including any subdirs under userfiles)
 9023: 
 9024: =item *
 9025: 
 9026: removeuserfile(): removes a file that exists in userfiles
 9027: 
 9028:   Args:
 9029:    docuname: username or courseid of destination for the file
 9030:    docudom: domain of user/course of destination for the file
 9031:    fname: filname to delete (including any subdirs under userfiles)
 9032: 
 9033: =item *
 9034: 
 9035: removeuploadedurl(): convience function for removeuserfile()
 9036: 
 9037:   Args:
 9038:    url:  a full /uploaded/... url to delete
 9039: 
 9040: =item * 
 9041: 
 9042: get_portfile_permissions():
 9043:   Args:
 9044:     domain: domain of user or course contain the portfolio files
 9045:     user: name of user or num of course contain the portfolio files
 9046:   Returns:
 9047:     hashref of a dump of the proper file_permissions.db
 9048:    
 9049: 
 9050: =item * 
 9051: 
 9052: get_access_controls():
 9053: 
 9054: Args:
 9055:   current_permissions: the hash ref returned from get_portfile_permissions()
 9056:   group: (optional) the group you want the files associated with
 9057:   file: (optional) the file you want access info on
 9058: 
 9059: Returns:
 9060:     a hash (keys are file names) of hashes containing
 9061:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9062:         values are XML containing access control settings (see below) 
 9063: 
 9064: Internal notes:
 9065: 
 9066:  access controls are stored in file_permissions.db as key=value pairs.
 9067:     key -> path to file/file_name\0uniqueID:scope_end_start
 9068:         where scope -> public,guest,course,group,domains or users.
 9069:               end -> UNIX time for end of access (0 -> no end date)
 9070:               start -> UNIX time for start of access
 9071: 
 9072:     value -> XML description of access control
 9073:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9074:             <start></start>
 9075:             <end></end>
 9076: 
 9077:             <password></password>  for scope type = guest
 9078: 
 9079:             <domain></domain>     for scope type = course or group
 9080:             <number></number>
 9081:             <roles id="">
 9082:              <role></role>
 9083:              <access></access>
 9084:              <section></section>
 9085:              <group></group>
 9086:             </roles>
 9087: 
 9088:             <dom></dom>         for scope type = domains
 9089: 
 9090:             <users>             for scope type = users
 9091:              <user>
 9092:               <uname></uname>
 9093:               <udom></udom>
 9094:              </user>
 9095:             </users>
 9096:            </scope> 
 9097:               
 9098:  Access data is also aggregated for each file in an additional key=value pair:
 9099:  key -> path to file/file_name\0accesscontrol 
 9100:  value -> reference to hash
 9101:           hash contains key = value pairs
 9102:           where key = uniqueID:scope_end_start
 9103:                 value = UNIX time record was last updated
 9104: 
 9105:           Used to improve speed of look-ups of access controls for each file.  
 9106:  
 9107:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9108: 
 9109: modify_access_controls():
 9110: 
 9111: Modifies access controls for a portfolio file
 9112: Args
 9113: 1. file name
 9114: 2. reference to hash of required changes,
 9115: 3. domain
 9116: 4. username
 9117:   where domain,username are the domain of the portfolio owner 
 9118:   (either a user or a course) 
 9119: 
 9120: Returns:
 9121: 1. result of additions or updates ('ok' or 'error', with error message). 
 9122: 2. result of deletions ('ok' or 'error', with error message).
 9123: 3. reference to hash of any new or updated access controls.
 9124: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9125:    key = integer (inbound ID)
 9126:    value = uniqueID  
 9127: 
 9128: =back
 9129: 
 9130: =head2 HTTP Helper Routines
 9131: 
 9132: =over 4
 9133: 
 9134: =item *
 9135: 
 9136: escape() : unpack non-word characters into CGI-compatible hex codes
 9137: 
 9138: =item *
 9139: 
 9140: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9141: 
 9142: =back
 9143: 
 9144: =head1 PRIVATE SUBROUTINES
 9145: 
 9146: =head2 Underlying communication routines (Shouldn't call)
 9147: 
 9148: =over 4
 9149: 
 9150: =item *
 9151: 
 9152: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9153: 
 9154: =item *
 9155: 
 9156: reply() : uses subreply to send a message to remote machine, logs all failures
 9157: 
 9158: =item *
 9159: 
 9160: critical() : passes a critical message to another server; if cannot
 9161: get through then place message in connection buffer directory and
 9162: returns con_delayed, if incapable of saving message, returns
 9163: con_failed
 9164: 
 9165: =item *
 9166: 
 9167: reconlonc() : tries to reconnect lonc client processes.
 9168: 
 9169: =back
 9170: 
 9171: =head2 Resource Access Logging
 9172: 
 9173: =over 4
 9174: 
 9175: =item *
 9176: 
 9177: flushcourselogs() : flush (save) buffer logs and access logs
 9178: 
 9179: =item *
 9180: 
 9181: courselog($what) : save message for course in hash
 9182: 
 9183: =item *
 9184: 
 9185: courseacclog($what) : save message for course using &courselog().  Perform
 9186: special processing for specific resource types (problems, exams, quizzes, etc).
 9187: 
 9188: =item *
 9189: 
 9190: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9191: as a PerlChildExitHandler
 9192: 
 9193: =back
 9194: 
 9195: =head2 Other
 9196: 
 9197: =over 4
 9198: 
 9199: =item *
 9200: 
 9201: symblist($mapname,%newhash) : update symbolic storage links
 9202: 
 9203: =back
 9204: 
 9205: =cut

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