Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.976.2.5

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.976.2.5! raeburn     4: # $Id: lonnet.pm,v 1.976.2.4 2008/12/31 18:26:53 raeburn Exp $
1.178     www         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: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
                     76: # use Date::Parse;
1.871     albertel   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    78:             $_64bit %env %protocol);
1.871     albertel   79: 
                     80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        83:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        84: 
1.1       albertel   85: use IO::Socket;
1.31      www        86: use GDBM_File;
1.208     albertel   87: use HTML::LCParser;
1.88      www        88: use Fcntl qw(:flock);
1.870     albertel   89: use Storable qw(thaw nfreeze);
1.539     albertel   90: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   91: use Cache::Memcached;
1.676     albertel   92: use Digest::MD5;
1.790     albertel   93: use Math::Random;
1.807     albertel   94: use LONCAPA qw(:DEFAULT :match);
1.740     www        95: use LONCAPA::Configuration;
1.676     albertel   96: 
1.195     www        97: my $readit;
1.550     foxr       98: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   99: 
1.619     albertel  100: require Exporter;
                    101: 
                    102: our @ISA = qw (Exporter);
                    103: our @EXPORT = qw(%env);
                    104: 
1.449     matthew   105: 
1.1       albertel  106: # --------------------------------------------------------------------- Logging
1.729     www       107: {
                    108:     my $logid;
                    109:     sub instructor_log {
1.957     raeburn   110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    111:         if (($cnum eq '') || ($cdom eq '')) {
                    112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    114:         }
1.729     www       115: 	$logid++;
1.957     raeburn   116:         my $now = time();
                    117: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       119: 				    { $id => {
                    120: 					'exe_uname' => $env{'user.name'},
                    121: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   122: 					'exe_time'  => $now,
1.730     www       123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    124: 					'delflag'   => $delflag,
                    125: 					'logentry'  => $storehash,
                    126: 					'uname'     => $uname,
                    127: 					'udom'      => $udom,
                    128: 				    }
1.957     raeburn   129: 				  },$cdom,$cnum);
1.729     www       130:     }
                    131: }
1.1       albertel  132: 
1.163     harris41  133: sub logtouch {
                    134:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  135:     unless (-e "$execdir/logs/lonnet.log") {	
                    136: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  137: 	close $fh;
                    138:     }
                    139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    141: }
                    142: 
1.1       albertel  143: sub logthis {
                    144:     my $message=shift;
                    145:     my $execdir=$perlvar{'lonDaemons'};
                    146:     my $now=time;
                    147:     my $local=localtime($now);
1.448     albertel  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    149: 	print $fh "$local ($$): $message\n";
                    150: 	close($fh);
                    151:     }
1.1       albertel  152:     return 1;
                    153: }
                    154: 
                    155: sub logperm {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.448     albertel  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    161: 	print $fh "$now:$message:$local\n";
                    162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
1.850     albertel  167: sub create_connection {
1.853     albertel  168:     my ($hostname,$lonid) = @_;
1.851     albertel  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  170: 				     Type    => SOCK_STREAM,
                    171: 				     Timeout => 10);
                    172:     return 0 if (!$client);
1.890     albertel  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  174:     my $result = <$client>;
                    175:     chomp($result);
                    176:     return 1 if ($result eq 'done');
                    177:     return 0;
                    178: }
                    179: 
                    180: 
1.1       albertel  181: # -------------------------------------------------- Non-critical communication
                    182: sub subreply {
                    183:     my ($cmd,$server)=@_;
1.838     albertel  184:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      185:     #
                    186:     #  With loncnew process trimming, there's a timing hole between lonc server
                    187:     #  process exit and the master server picking up the listen on the AF_UNIX
                    188:     #  socket.  In that time interval, a lock file will exist:
                    189: 
                    190:     my $lockfile=$peerfile.".lock";
                    191:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    192: 	sleep(1);
                    193:     }
                    194:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      195:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      196:     #
1.550     foxr      197:     #   We'll give the connection a few tries before abandoning it.  If
                    198:     #   connection is not possible, we'll con_lost back to the client.
                    199:     #   
                    200:     my $client;
                    201:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    202: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    203: 				      Type    => SOCK_STREAM,
                    204: 				      Timeout => 10);
1.869     albertel  205: 	if ($client) {
1.550     foxr      206: 	    last;		# Connected!
1.850     albertel  207: 	} else {
1.853     albertel  208: 	    &create_connection(&hostname($server),$server);
1.550     foxr      209: 	}
1.850     albertel  210:         sleep(1);		# Try again later if failed connection.
1.550     foxr      211:     }
                    212:     my $answer;
                    213:     if ($client) {
1.704     albertel  214: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      215: 	$answer=<$client>;
                    216: 	if (!$answer) { $answer="con_lost"; }
                    217: 	chomp($answer);
                    218:     } else {
                    219: 	$answer = 'con_lost';	# Failed connection.
                    220:     }
1.1       albertel  221:     return $answer;
                    222: }
                    223: 
                    224: sub reply {
                    225:     my ($cmd,$server)=@_;
1.838     albertel  226:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  227:     my $answer=subreply($cmd,$server);
1.65      www       228:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  229:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       230:                 " $cmd to $server returned $answer</font>");
                    231:     }
1.1       albertel  232:     return $answer;
                    233: }
                    234: 
                    235: # ----------------------------------------------------------- Send USR1 to lonc
                    236: 
                    237: sub reconlonc {
1.891     albertel  238:     my ($lonid) = @_;
                    239:     my $hostname = &hostname($lonid);
                    240:     if ($lonid) {
                    241: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    242: 	if ($hostname && -e $peerfile) {
                    243: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    244: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    245: 					     Type    => SOCK_STREAM,
                    246: 					     Timeout => 10);
                    247: 	    if ($client) {
                    248: 		print $client ("reset_retries\n");
                    249: 		my $answer=<$client>;
                    250: 		#reset just this one.
                    251: 	    }
                    252: 	}
                    253: 	return;
                    254:     }
                    255: 
1.836     www       256:     &logthis("Trying to reconnect lonc");
1.1       albertel  257:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  258:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  259: 	my $loncpid=<$fh>;
                    260:         chomp($loncpid);
                    261:         if (kill 0 => $loncpid) {
                    262: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    263:             kill USR1 => $loncpid;
                    264:             sleep 1;
1.836     www       265:          } else {
1.12      www       266: 	    &logthis(
1.672     albertel  267:                "<font color=\"blue\">WARNING:".
1.12      www       268:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  269:         }
                    270:     } else {
1.836     www       271: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  272:     }
                    273: }
                    274: 
                    275: # ------------------------------------------------------ Critical communication
1.12      www       276: 
1.1       albertel  277: sub critical {
                    278:     my ($cmd,$server)=@_;
1.838     albertel  279:     unless (&hostname($server)) {
1.672     albertel  280:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       281:                " Critical message to unknown server ($server)</font>");
                    282:         return 'no_such_host';
                    283:     }
1.1       albertel  284:     my $answer=reply($cmd,$server);
                    285:     if ($answer eq 'con_lost') {
                    286: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  287: 	my $answer=reply($cmd,$server);
1.1       albertel  288:         if ($answer eq 'con_lost') {
                    289:             my $now=time;
                    290:             my $middlename=$cmd;
1.5       www       291:             $middlename=substr($middlename,0,16);
1.1       albertel  292:             $middlename=~s/\W//g;
                    293:             my $dfilename=
1.305     www       294:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    295:             $dumpcount++;
1.1       albertel  296:             {
1.448     albertel  297: 		my $dfh;
                    298: 		if (open($dfh,">$dfilename")) {
                    299: 		    print $dfh "$cmd\n"; 
                    300: 		    close($dfh);
                    301: 		}
1.1       albertel  302:             }
                    303:             sleep 2;
                    304:             my $wcmd='';
                    305:             {
1.448     albertel  306: 		my $dfh;
                    307: 		if (open($dfh,"<$dfilename")) {
                    308: 		    $wcmd=<$dfh>; 
                    309: 		    close($dfh);
                    310: 		}
1.1       albertel  311:             }
                    312:             chomp($wcmd);
1.7       www       313:             if ($wcmd eq $cmd) {
1.672     albertel  314: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       315:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  316:                 &logperm("D:$server:$cmd");
                    317: 	        return 'con_delayed';
                    318:             } else {
1.672     albertel  319:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       320:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  321:                 &logperm("F:$server:$cmd");
                    322:                 return 'con_failed';
                    323:             }
                    324:         }
                    325:     }
                    326:     return $answer;
1.405     albertel  327: }
                    328: 
1.755     albertel  329: # ------------------------------------------- check if return value is an error
                    330: 
                    331: sub error {
                    332:     my ($result) = @_;
1.756     albertel  333:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  334: 	if ($2 == 2) { return undef; }
                    335: 	return $1;
                    336:     }
                    337:     return undef;
                    338: }
                    339: 
1.783     albertel  340: sub convert_and_load_session_env {
                    341:     my ($lonidsdir,$handle)=@_;
                    342:     my @profile;
                    343:     {
1.917     albertel  344: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    345: 	if (!$opened) {
1.915     albertel  346: 	    return 0;
                    347: 	}
1.783     albertel  348: 	flock($idf,LOCK_SH);
                    349: 	@profile=<$idf>;
                    350: 	close($idf);
                    351:     }
                    352:     my %temp_env;
                    353:     foreach my $line (@profile) {
1.786     albertel  354: 	if ($line !~ m/=/) {
                    355: 	    return 0;
                    356: 	}
1.783     albertel  357: 	chomp($line);
                    358: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    359: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    360:     }
                    361:     unlink("$lonidsdir/$handle.id");
                    362:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    363: 	    0640)) {
                    364: 	%disk_env = %temp_env;
                    365: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    366: 	untie(%disk_env);
                    367:     }
1.786     albertel  368:     return 1;
1.783     albertel  369: }
                    370: 
1.374     www       371: # ------------------------------------------- Transfer profile into environment
1.780     albertel  372: my $env_loaded;
                    373: sub transfer_profile_to_env {
1.788     albertel  374:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    375:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       376: 
1.720     albertel  377:     if (!defined($lonidsdir)) {
                    378: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    379:     }
                    380:     if (!defined($handle)) {
                    381:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    382:     }
                    383: 
1.786     albertel  384:     my $convert;
                    385:     {
1.917     albertel  386:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    387: 	if (!$opened) {
1.915     albertel  388: 	    return;
                    389: 	}
1.786     albertel  390: 	flock($idf,LOCK_SH);
                    391: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    392: 		&GDBM_READER(),0640)) {
                    393: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    394: 	    untie(%disk_env);
                    395: 	} else {
                    396: 	    $convert = 1;
                    397: 	}
                    398:     }
                    399:     if ($convert) {
                    400: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    401: 	    &logthis("Failed to load session, or convert session.");
                    402: 	}
1.374     www       403:     }
1.783     albertel  404: 
1.786     albertel  405:     my %remove;
1.783     albertel  406:     while ( my $envname = each(%env) ) {
1.433     matthew   407:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    408:             if ($time < time-300) {
1.783     albertel  409:                 $remove{$key}++;
1.433     matthew   410:             }
                    411:         }
                    412:     }
1.783     albertel  413: 
1.619     albertel  414:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  415:     $env_loaded=1;
1.783     albertel  416:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   417:         &delenv($expired_key);
1.374     www       418:     }
1.1       albertel  419: }
                    420: 
1.916     albertel  421: # ---------------------------------------------------- Check for valid session 
                    422: sub check_for_valid_session {
                    423:     my ($r) = @_;
                    424:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    425:     my $lonid=$cookies{'lonID'};
                    426:     return undef if (!$lonid);
                    427: 
                    428:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    429:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    430:     return undef if (!-e "$lonidsdir/$handle.id");
                    431: 
1.917     albertel  432:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    433:     return undef if (!$opened);
1.916     albertel  434: 
                    435:     flock($idf,LOCK_SH);
                    436:     my %disk_env;
                    437:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    438: 	    &GDBM_READER(),0640)) {
                    439: 	return undef;	
                    440:     }
                    441: 
                    442:     if (!defined($disk_env{'user.name'})
                    443: 	|| !defined($disk_env{'user.domain'})) {
                    444: 	return undef;
                    445:     }
                    446:     return $handle;
                    447: }
                    448: 
1.830     albertel  449: sub timed_flock {
                    450:     my ($file,$lock_type) = @_;
                    451:     my $failed=0;
                    452:     eval {
                    453: 	local $SIG{__DIE__}='DEFAULT';
                    454: 	local $SIG{ALRM}=sub {
                    455: 	    $failed=1;
                    456: 	    die("failed lock");
                    457: 	};
                    458: 	alarm(13);
                    459: 	flock($file,$lock_type);
                    460: 	alarm(0);
                    461:     };
                    462:     if ($failed) {
                    463: 	return undef;
                    464:     } else {
                    465: 	return 1;
                    466:     }
                    467: }
                    468: 
1.5       www       469: # ---------------------------------------------------------- Append Environment
                    470: 
                    471: sub appenv {
1.949     raeburn   472:     my ($newenv,$roles) = @_;
                    473:     if (ref($newenv) eq 'HASH') {
                    474:         foreach my $key (keys(%{$newenv})) {
                    475:             my $refused = 0;
                    476: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    477:                 $refused = 1;
                    478:                 if (ref($roles) eq 'ARRAY') {
                    479:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    480:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    481:                         $refused = 0;
                    482:                     }
                    483:                 }
                    484:             }
                    485:             if ($refused) {
                    486:                 &logthis("<font color=\"blue\">WARNING: ".
                    487:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    488:                          .'</font>');
                    489: 	        delete($newenv->{$key});
                    490:             } else {
                    491:                 $env{$key}=$newenv->{$key};
                    492:             }
                    493:         }
                    494:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    495:         if ($opened
                    496: 	    && &timed_flock($env_file,LOCK_EX)
                    497: 	    &&
                    498: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    499: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    500: 	    while (my ($key,$value) = each(%{$newenv})) {
                    501: 	        $disk_env{$key} = $value;
                    502: 	    }
                    503: 	    untie(%disk_env);
1.35      www       504:         }
1.191     harris41  505:     }
1.56      www       506:     return 'ok';
                    507: }
                    508: # ----------------------------------------------------- Delete from Environment
                    509: 
                    510: sub delenv {
                    511:     my $delthis=shift;
                    512:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  513:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       514:                 "Attempt to delete from environment ".$delthis);
                    515:         return 'error';
                    516:     }
1.917     albertel  517:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    518:     if ($opened
1.915     albertel  519: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  520: 	&&
                    521: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    522: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  523: 	foreach my $key (keys(%disk_env)) {
1.976.2.4  raeburn   524: 	    if ($key=~/^\Q$delthis\E/) { 
1.915     albertel  525: 		delete($env{$key});
                    526: 		delete($disk_env{$key});
                    527: 	    }
1.448     albertel  528: 	}
1.783     albertel  529: 	untie(%disk_env);
1.5       www       530:     }
                    531:     return 'ok';
1.369     albertel  532: }
                    533: 
1.790     albertel  534: sub get_env_multiple {
                    535:     my ($name) = @_;
                    536:     my @values;
                    537:     if (defined($env{$name})) {
                    538:         # exists is it an array
                    539:         if (ref($env{$name})) {
                    540:             @values=@{ $env{$name} };
                    541:         } else {
                    542:             $values[0]=$env{$name};
                    543:         }
                    544:     }
                    545:     return(@values);
                    546: }
                    547: 
1.958     www       548: # ------------------------------------------------------------------- Locking
                    549: 
                    550: sub set_lock {
                    551:     my ($text)=@_;
                    552:     $locknum++;
                    553:     my $id=$$.'-'.$locknum;
                    554:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    555:              'session.lock.'.$id => $text});
                    556:     return $id;
                    557: }
                    558: 
                    559: sub get_locks {
                    560:     my $num=0;
                    561:     my %texts=();
                    562:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    563:        if ($lock=~/\w/) {
                    564:           $num++;
                    565:           $texts{$lock}=$env{'session.lock.'.$lock};
                    566:        }
                    567:    }
                    568:    return ($num,%texts);
                    569: }
                    570: 
                    571: sub remove_lock {
                    572:     my ($id)=@_;
                    573:     my $newlocks='';
                    574:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    575:        if (($lock=~/\w/) && ($lock ne $id)) {
                    576:           $newlocks.=','.$lock;
                    577:        }
                    578:     }
                    579:     &appenv({'session.locks' => $newlocks});
                    580:     &delenv('session.lock.'.$id);
                    581: }
                    582: 
                    583: sub remove_all_locks {
                    584:     my $activelocks=$env{'session.locks'};
                    585:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    586:        if ($lock=~/\w/) {
                    587:           &remove_lock($lock);
                    588:        }
                    589:     }
                    590: }
                    591: 
                    592: 
1.369     albertel  593: # ------------------------------------------ Find out current server userload
                    594: sub userload {
                    595:     my $numusers=0;
                    596:     {
                    597: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    598: 	my $filename;
                    599: 	my $curtime=time;
                    600: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  601: 	    next if ($filename eq '.' || $filename eq '..');
                    602: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  603: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  604: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  605: 	}
                    606: 	closedir(LONIDS);
                    607:     }
                    608:     my $userloadpercent=0;
                    609:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    610:     if ($maxuserload) {
1.371     albertel  611: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  612:     }
1.372     albertel  613:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  614:     return $userloadpercent;
1.283     www       615: }
                    616: 
                    617: # ------------------------------------------ Fight off request when overloaded
                    618: 
                    619: sub overloaderror {
                    620:     my ($r,$checkserver)=@_;
                    621:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    622:     my $loadavg;
                    623:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  624:        open(my $loadfile,'/proc/loadavg');
1.283     www       625:        $loadavg=<$loadfile>;
                    626:        $loadavg =~ s/\s.*//g;
1.285     matthew   627:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  628:        close($loadfile);
1.283     www       629:     } else {
                    630:        $loadavg=&reply('load',$checkserver);
                    631:     }
1.285     matthew   632:     my $overload=$loadavg-100;
1.283     www       633:     if ($overload>0) {
1.285     matthew   634: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       635:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       636:         return 413;
1.283     www       637:     }    
                    638:     return '';
1.5       www       639: }
1.1       albertel  640: 
                    641: # ------------------------------ Find server with least workload from spare.tab
1.11      www       642: 
1.1       albertel  643: sub spareserver {
1.670     albertel  644:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  645:     my $spare_server;
1.370     albertel  646:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  647:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    648:                                                      :  $userloadpercent;
                    649:     
                    650:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    651: 	($spare_server, $lowest_load) =
                    652: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    653:     }
                    654: 
                    655:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    656: 
                    657:     if (!$found_server) {
                    658: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    659: 	    ($spare_server, $lowest_load) =
                    660: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    661: 	}
                    662:     }
                    663: 
                    664:     if (!$want_server_name) {
1.968     raeburn   665:         my $protocol = 'http';
                    666:         if ($protocol{$spare_server} eq 'https') {
                    667:             $protocol = $protocol{$spare_server};
                    668:         }
                    669: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  670:     }
                    671:     return $spare_server;
                    672: }
                    673: 
                    674: sub compare_server_load {
                    675:     my ($try_server, $spare_server, $lowest_load) = @_;
                    676: 
                    677:     my $loadans     = &reply('load',    $try_server);
                    678:     my $userloadans = &reply('userload',$try_server);
                    679: 
                    680:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    681: 	next; #didn't get a number from the server
                    682:     }
                    683: 
                    684:     my $load;
                    685:     if ($loadans =~ /\d/) {
                    686: 	if ($userloadans =~ /\d/) {
                    687: 	    #both are numbers, pick the bigger one
                    688: 	    $load = ($loadans > $userloadans) ? $loadans 
                    689: 		                              : $userloadans;
1.411     albertel  690: 	} else {
1.784     albertel  691: 	    $load = $loadans;
1.411     albertel  692: 	}
1.784     albertel  693:     } else {
                    694: 	$load = $userloadans;
                    695:     }
                    696: 
                    697:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    698: 	$spare_server = $try_server;
                    699: 	$lowest_load  = $load;
1.370     albertel  700:     }
1.784     albertel  701:     return ($spare_server,$lowest_load);
1.202     matthew   702: }
1.914     albertel  703: 
                    704: # --------------------------- ask offload servers if user already has a session
                    705: sub find_existing_session {
                    706:     my ($udom,$uname) = @_;
                    707:     foreach my $try_server (@{ $spareid{'primary'} },
                    708: 			    @{ $spareid{'default'} }) {
                    709: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    710:     }
                    711:     return;
                    712: }
                    713: 
                    714: # -------------------------------- ask if server already has a session for user
                    715: sub has_user_session {
                    716:     my ($lonid,$udom,$uname) = @_;
                    717:     my $result = &reply(join(':','userhassession',
                    718: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    719:     return 1 if ($result eq 'ok');
                    720: 
                    721:     return 0;
                    722: }
                    723: 
1.202     matthew   724: # --------------------------------------------- Try to change a user's password
                    725: 
                    726: sub changepass {
1.799     raeburn   727:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   728:     $currentpass = &escape($currentpass);
                    729:     $newpass     = &escape($newpass);
1.799     raeburn   730:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   731: 		       $server);
                    732:     if (! $answer) {
                    733: 	&logthis("No reply on password change request to $server ".
                    734: 		 "by $uname in domain $udom.");
                    735:     } elsif ($answer =~ "^ok") {
                    736:         &logthis("$uname in $udom successfully changed their password ".
                    737: 		 "on $server.");
                    738:     } elsif ($answer =~ "^pwchange_failure") {
                    739: 	&logthis("$uname in $udom was unable to change their password ".
                    740: 		 "on $server.  The action was blocked by either lcpasswd ".
                    741: 		 "or pwchange");
                    742:     } elsif ($answer =~ "^non_authorized") {
                    743:         &logthis("$uname in $udom did not get their password correct when ".
                    744: 		 "attempting to change it on $server.");
                    745:     } elsif ($answer =~ "^auth_mode_error") {
                    746:         &logthis("$uname in $udom attempted to change their password despite ".
                    747: 		 "not being locally or internally authenticated on $server.");
                    748:     } elsif ($answer =~ "^unknown_user") {
                    749:         &logthis("$uname in $udom attempted to change their password ".
                    750: 		 "on $server but were unable to because $server is not ".
                    751: 		 "their home server.");
                    752:     } elsif ($answer =~ "^refused") {
                    753: 	&logthis("$server refused to change $uname in $udom password because ".
                    754: 		 "it was sent an unencrypted request to change the password.");
                    755:     }
                    756:     return $answer;
1.1       albertel  757: }
                    758: 
1.169     harris41  759: # ----------------------- Try to determine user's current authentication scheme
                    760: 
                    761: sub queryauthenticate {
                    762:     my ($uname,$udom)=@_;
1.456     albertel  763:     my $uhome=&homeserver($uname,$udom);
                    764:     if (!$uhome) {
                    765: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    766: 	return 'no_host';
                    767:     }
                    768:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    769:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    770: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  771:     }
1.456     albertel  772:     return $answer;
1.169     harris41  773: }
                    774: 
1.1       albertel  775: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       776: 
1.1       albertel  777: sub authenticate {
1.952     raeburn   778:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  779:     $upass=&escape($upass);
                    780:     $uname= &LONCAPA::clean_username($uname);
1.836     www       781:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   782:     my $newhome;
1.836     www       783:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    784: # Maybe the machine was offline and only re-appeared again recently?
                    785:         &reconlonc();
                    786: # One more
1.952     raeburn   787: 	$uhome=&homeserver($uname,$udom,1);
                    788:         if (($uhome eq 'no_host') && $checkdefauth) {
                    789:             if (defined(&domain($udom,'primary'))) {
                    790:                 $newhome=&domain($udom,'primary');
                    791:             }
                    792:             if ($newhome ne '') {
                    793:                 $uhome = $newhome;
                    794:             }
                    795:         }
1.836     www       796: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    797: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   798: 	    return 'no_host';
                    799:         }
1.1       albertel  800:     }
1.952     raeburn   801:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  802:     if ($answer eq 'authorized') {
1.952     raeburn   803:         if ($newhome) {
                    804:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    805:             return 'no_account_on_host'; 
                    806:         } else {
                    807:             &logthis("User $uname at $udom authorized by $uhome");
                    808:             return $uhome;
                    809:         }
1.471     albertel  810:     }
                    811:     if ($answer eq 'non_authorized') {
                    812: 	&logthis("User $uname at $udom rejected by $uhome");
                    813: 	return 'no_host'; 
1.9       www       814:     }
1.471     albertel  815:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  816:     return 'no_host';
                    817: }
                    818: 
                    819: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       820: 
1.599     albertel  821: my %homecache;
1.1       albertel  822: sub homeserver {
1.230     stredwic  823:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  824:     my $index="$uname:$udom";
1.426     albertel  825: 
1.599     albertel  826:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  827: 
                    828:     my %servers = &get_servers($udom,'library');
                    829:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  830:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  831: 		 exists($badServerCache{$tryserver}));
1.841     albertel  832: 
                    833: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    834: 	if ($answer eq 'found') {
                    835: 	    delete($badServerCache{$tryserver}); 
                    836: 	    return $homecache{$index}=$tryserver;
                    837: 	} elsif ($answer eq 'no_host') {
                    838: 	    $badServerCache{$tryserver}=1;
                    839: 	}
1.1       albertel  840:     }    
                    841:     return 'no_host';
1.70      www       842: }
                    843: 
                    844: # ------------------------------------- Find the usernames behind a list of IDs
                    845: 
                    846: sub idget {
                    847:     my ($udom,@ids)=@_;
                    848:     my %returnhash=();
                    849:     
1.841     albertel  850:     my %servers = &get_servers($udom,'library');
                    851:     foreach my $tryserver (keys(%servers)) {
                    852: 	my $idlist=join('&',@ids);
                    853: 	$idlist=~tr/A-Z/a-z/; 
                    854: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    855: 	my @answer=();
                    856: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    857: 	    @answer=split(/\&/,$reply);
                    858: 	}                    ;
                    859: 	my $i;
                    860: 	for ($i=0;$i<=$#ids;$i++) {
                    861: 	    if ($answer[$i]) {
                    862: 		$returnhash{$ids[$i]}=$answer[$i];
                    863: 	    } 
                    864: 	}
                    865:     } 
1.70      www       866:     return %returnhash;
                    867: }
                    868: 
                    869: # ------------------------------------- Find the IDs behind a list of usernames
                    870: 
                    871: sub idrget {
                    872:     my ($udom,@unames)=@_;
                    873:     my %returnhash=();
1.800     albertel  874:     foreach my $uname (@unames) {
                    875:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  876:     }
1.70      www       877:     return %returnhash;
                    878: }
                    879: 
                    880: # ------------------------------- Store away a list of names and associated IDs
                    881: 
                    882: sub idput {
                    883:     my ($udom,%ids)=@_;
                    884:     my %servers=();
1.800     albertel  885:     foreach my $uname (keys(%ids)) {
                    886: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    887:         my $uhom=&homeserver($uname,$udom);
1.70      www       888:         if ($uhom ne 'no_host') {
1.800     albertel  889:             my $id=&escape($ids{$uname});
1.70      www       890:             $id=~tr/A-Z/a-z/;
1.800     albertel  891:             my $esc_unam=&escape($uname);
1.70      www       892: 	    if ($servers{$uhom}) {
1.800     albertel  893: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       894:             } else {
1.800     albertel  895:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       896:             }
                    897:         }
1.191     harris41  898:     }
1.800     albertel  899:     foreach my $server (keys(%servers)) {
                    900:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  901:     }
1.344     www       902: }
                    903: 
1.806     raeburn   904: # ------------------------------------------- get items from domain db files   
                    905: 
                    906: sub get_dom {
1.860     raeburn   907:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   908:     my $items='';
                    909:     foreach my $item (@$storearr) {
                    910:         $items.=&escape($item).'&';
                    911:     }
                    912:     $items=~s/\&$//;
1.860     raeburn   913:     if (!$udom) {
                    914:         $udom=$env{'user.domain'};
                    915:         if (defined(&domain($udom,'primary'))) {
                    916:             $uhome=&domain($udom,'primary');
                    917:         } else {
1.874     albertel  918:             undef($uhome);
1.860     raeburn   919:         }
                    920:     } else {
                    921:         if (!$uhome) {
                    922:             if (defined(&domain($udom,'primary'))) {
                    923:                 $uhome=&domain($udom,'primary');
                    924:             }
                    925:         }
                    926:     }
                    927:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   928:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   929:         my %returnhash;
1.875     albertel  930:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   931:             return %returnhash;
                    932:         }
1.806     raeburn   933:         my @pairs=split(/\&/,$rep);
                    934:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    935:             return @pairs;
                    936:         }
                    937:         my $i=0;
                    938:         foreach my $item (@$storearr) {
                    939:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    940:             $i++;
                    941:         }
                    942:         return %returnhash;
                    943:     } else {
1.880     banghart  944:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   945:     }
                    946: }
                    947: 
                    948: # -------------------------------------------- put items in domain db files 
                    949: 
                    950: sub put_dom {
1.860     raeburn   951:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    952:     if (!$udom) {
                    953:         $udom=$env{'user.domain'};
                    954:         if (defined(&domain($udom,'primary'))) {
                    955:             $uhome=&domain($udom,'primary');
                    956:         } else {
1.874     albertel  957:             undef($uhome);
1.860     raeburn   958:         }
                    959:     } else {
                    960:         if (!$uhome) {
                    961:             if (defined(&domain($udom,'primary'))) {
                    962:                 $uhome=&domain($udom,'primary');
                    963:             }
                    964:         }
                    965:     } 
                    966:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   967:         my $items='';
                    968:         foreach my $item (keys(%$storehash)) {
                    969:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    970:         }
                    971:         $items=~s/\&$//;
                    972:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    973:     } else {
1.860     raeburn   974:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   975:     }
                    976: }
                    977: 
1.837     raeburn   978: sub retrieve_inst_usertypes {
                    979:     my ($udom) = @_;
                    980:     my (%returnhash,@order);
1.846     albertel  981:     if (defined(&domain($udom,'primary'))) {
                    982:         my $uhome=&domain($udom,'primary');
1.837     raeburn   983:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn   984:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                    985:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                    986:             return (\%returnhash,\@order);
                    987:         }
1.837     raeburn   988:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    989:         my @pairs=split(/\&/,$hashitems);
                    990:         foreach my $item (@pairs) {
                    991:             my ($key,$value)=split(/=/,$item,2);
                    992:             $key = &unescape($key);
                    993:             next if ($key =~ /^error: 2 /);
                    994:             $returnhash{$key}=&thaw_unescape($value);
                    995:         }
                    996:         my @esc_order = split(/\&/,$orderitems);
                    997:         foreach my $item (@esc_order) {
                    998:             push(@order,&unescape($item));
                    999:         }
                   1000:     } else {
                   1001:         &logthis("get_dom failed - no primary domain server for $udom");
                   1002:     }
                   1003:     return (\%returnhash,\@order);
                   1004: }
                   1005: 
1.868     raeburn  1006: sub is_domainimage {
                   1007:     my ($url) = @_;
                   1008:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1009:         if (&domain($1) ne '') {
                   1010:             return '1';
                   1011:         }
                   1012:     }
                   1013:     return;
                   1014: }
                   1015: 
1.899     raeburn  1016: sub inst_directory_query {
                   1017:     my ($srch) = @_;
                   1018:     my $udom = $srch->{'srchdomain'};
                   1019:     my %results;
                   1020:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1021:     my $outcome;
1.899     raeburn  1022:     if ($homeserver ne '') {
1.904     albertel 1023: 	my $queryid=&reply("querysend:instdirsearch:".
                   1024: 			   &escape($srch->{'srchby'}).':'.
                   1025: 			   &escape($srch->{'srchterm'}).':'.
                   1026: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1027: 	my $host=&hostname($homeserver);
                   1028: 	if ($queryid !~/^\Q$host\E\_/) {
                   1029: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1030: 	    return;
                   1031: 	}
                   1032: 	my $response = &get_query_reply($queryid);
                   1033: 	my $maxtries = 5;
                   1034: 	my $tries = 1;
                   1035: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1036: 	    $response = &get_query_reply($queryid);
                   1037: 	    $tries ++;
                   1038: 	}
                   1039: 
                   1040:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1041:             if ($response eq 'unavailable') {
                   1042:                 $outcome = $response;
                   1043:             } else {
                   1044:                 $outcome = 'ok';
                   1045:                 my @matches = split(/\n/,$response);
                   1046:                 foreach my $match (@matches) {
                   1047:                     my ($key,$value) = split(/=/,$match);
                   1048:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1049:                 }
1.899     raeburn  1050:             }
                   1051:         }
                   1052:     }
1.909     raeburn  1053:     return ($outcome,%results);
1.899     raeburn  1054: }
                   1055: 
                   1056: sub usersearch {
                   1057:     my ($srch) = @_;
                   1058:     my $dom = $srch->{'srchdomain'};
                   1059:     my %results;
                   1060:     my %libserv = &all_library();
                   1061:     my $query = 'usersearch';
                   1062:     foreach my $tryserver (keys(%libserv)) {
                   1063:         if (&host_domain($tryserver) eq $dom) {
                   1064:             my $host=&hostname($tryserver);
                   1065:             my $queryid=
1.911     raeburn  1066:                 &reply("querysend:".&escape($query).':'.
                   1067:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1068:                        &escape($srch->{'srchtype'}).':'.
                   1069:                        &escape($srch->{'srchterm'}),$tryserver);
                   1070:             if ($queryid !~/^\Q$host\E\_/) {
                   1071:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1072:                 next;
1.899     raeburn  1073:             }
                   1074:             my $reply = &get_query_reply($queryid);
                   1075:             my $maxtries = 1;
                   1076:             my $tries = 1;
                   1077:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1078:                 $reply = &get_query_reply($queryid);
                   1079:                 $tries ++;
                   1080:             }
                   1081:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1082:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1083:             } else {
1.911     raeburn  1084:                 my @matches;
                   1085:                 if ($reply =~ /\n/) {
                   1086:                     @matches = split(/\n/,$reply);
                   1087:                 } else {
                   1088:                     @matches = split(/\&/,$reply);
                   1089:                 }
1.899     raeburn  1090:                 foreach my $match (@matches) {
                   1091:                     my ($uname,$udom,%userhash);
1.911     raeburn  1092:                     foreach my $entry (split(/:/,$match)) {
                   1093:                         my ($key,$value) =
                   1094:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1095:                         $userhash{$key} = $value;
                   1096:                         if ($key eq 'username') {
                   1097:                             $uname = $value;
                   1098:                         } elsif ($key eq 'domain') {
                   1099:                             $udom = $value;
1.911     raeburn  1100:                         }
1.899     raeburn  1101:                     }
                   1102:                     $results{$uname.':'.$udom} = \%userhash;
                   1103:                 }
                   1104:             }
                   1105:         }
                   1106:     }
                   1107:     return %results;
                   1108: }
                   1109: 
1.912     raeburn  1110: sub get_instuser {
                   1111:     my ($udom,$uname,$id) = @_;
                   1112:     my $homeserver = &domain($udom,'primary');
                   1113:     my ($outcome,%results);
                   1114:     if ($homeserver ne '') {
                   1115:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1116:                            &escape($id).':'.&escape($udom),$homeserver);
                   1117:         my $host=&hostname($homeserver);
                   1118:         if ($queryid !~/^\Q$host\E\_/) {
                   1119:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1120:             return;
                   1121:         }
                   1122:         my $response = &get_query_reply($queryid);
                   1123:         my $maxtries = 5;
                   1124:         my $tries = 1;
                   1125:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1126:             $response = &get_query_reply($queryid);
                   1127:             $tries ++;
                   1128:         }
                   1129:         if (!&error($response) && $response ne 'refused') {
                   1130:             if ($response eq 'unavailable') {
                   1131:                 $outcome = $response;
                   1132:             } else {
                   1133:                 $outcome = 'ok';
                   1134:                 my @matches = split(/\n/,$response);
                   1135:                 foreach my $match (@matches) {
                   1136:                     my ($key,$value) = split(/=/,$match);
                   1137:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1138:                 }
                   1139:             }
                   1140:         }
                   1141:     }
                   1142:     my %userinfo;
                   1143:     if (ref($results{$uname}) eq 'HASH') {
                   1144:         %userinfo = %{$results{$uname}};
                   1145:     } 
                   1146:     return ($outcome,%userinfo);
                   1147: }
                   1148: 
                   1149: sub inst_rulecheck {
1.923     raeburn  1150:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1151:     my %returnhash;
                   1152:     if ($udom ne '') {
                   1153:         if (ref($rules) eq 'ARRAY') {
                   1154:             @{$rules} = map {&escape($_);} (@{$rules});
                   1155:             my $rulestr = join(':',@{$rules});
                   1156:             my $homeserver=&domain($udom,'primary');
                   1157:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1158:                 my $response;
                   1159:                 if ($item eq 'username') {                
                   1160:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1161:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1162:                                               $homeserver));
1.923     raeburn  1163:                 } elsif ($item eq 'id') {
                   1164:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1165:                                               ':'.&escape($id).':'.$rulestr,
                   1166:                                               $homeserver));
1.945     raeburn  1167:                 } elsif ($item eq 'selfcreate') {
                   1168:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1169:                                                &escape($udom).':'.&escape($uname).
                   1170:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1171:                 }
1.912     raeburn  1172:                 if ($response ne 'refused') {
                   1173:                     my @pairs=split(/\&/,$response);
                   1174:                     foreach my $item (@pairs) {
                   1175:                         my ($key,$value)=split(/=/,$item,2);
                   1176:                         $key = &unescape($key);
                   1177:                         next if ($key =~ /^error: 2 /);
                   1178:                         $returnhash{$key}=&thaw_unescape($value);
                   1179:                     }
                   1180:                 }
                   1181:             }
                   1182:         }
                   1183:     }
                   1184:     return %returnhash;
                   1185: }
                   1186: 
                   1187: sub inst_userrules {
1.923     raeburn  1188:     my ($udom,$check) = @_;
1.912     raeburn  1189:     my (%ruleshash,@ruleorder);
                   1190:     if ($udom ne '') {
                   1191:         my $homeserver=&domain($udom,'primary');
                   1192:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1193:             my $response;
                   1194:             if ($check eq 'id') {
                   1195:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1196:                                  $homeserver);
1.943     raeburn  1197:             } elsif ($check eq 'email') {
                   1198:                 $response=&reply('instemailrules:'.&escape($udom),
                   1199:                                  $homeserver);
1.923     raeburn  1200:             } else {
                   1201:                 $response=&reply('instuserrules:'.&escape($udom),
                   1202:                                  $homeserver);
                   1203:             }
1.912     raeburn  1204:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1205:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1206:                 ($response ne 'no_such_host')) {
                   1207:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1208:                 my @pairs=split(/\&/,$hashitems);
                   1209:                 foreach my $item (@pairs) {
                   1210:                     my ($key,$value)=split(/=/,$item,2);
                   1211:                     $key = &unescape($key);
                   1212:                     next if ($key =~ /^error: 2 /);
                   1213:                     $ruleshash{$key}=&thaw_unescape($value);
                   1214:                 }
                   1215:                 my @esc_order = split(/\&/,$orderitems);
                   1216:                 foreach my $item (@esc_order) {
                   1217:                     push(@ruleorder,&unescape($item));
                   1218:                 }
                   1219:             }
                   1220:         }
                   1221:     }
                   1222:     return (\%ruleshash,\@ruleorder);
                   1223: }
                   1224: 
1.976     raeburn  1225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1226: 
                   1227: sub get_domain_defaults {
                   1228:     my ($domain) = @_;
                   1229:     my $cachetime = 60*60*24;
                   1230:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1231:     if (defined($cached)) {
                   1232:         if (ref($result) eq 'HASH') {
                   1233:             return %{$result};
                   1234:         }
                   1235:     }
                   1236:     my %domdefaults;
                   1237:     my %domconfig =
1.976     raeburn  1238:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1239:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1240:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1241:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1242:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.976.2.5! raeburn  1243:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
        !          1244:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1245:     } else {
                   1246:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1247:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1248:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1249:     }
1.976     raeburn  1250:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1251:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1252:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1253:         } else {
                   1254:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1255:         } 
                   1256:         my @usertools = ('aboutme','blog','portfolio');
                   1257:         foreach my $item (@usertools) {
                   1258:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1259:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1260:             }
                   1261:         }
                   1262:     }
1.943     raeburn  1263:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1264:                                   $cachetime);
                   1265:     return %domdefaults;
                   1266: }
                   1267: 
1.344     www      1268: # --------------------------------------------------- Assign a key to a student
                   1269: 
                   1270: sub assign_access_key {
1.364     www      1271: #
                   1272: # a valid key looks like uname:udom#comments
                   1273: # comments are being appended
                   1274: #
1.498     www      1275:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1276:     $kdom=
1.620     albertel 1277:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1278:     $knum=
1.620     albertel 1279:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1280:     $cdom=
1.620     albertel 1281:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1282:     $cnum=
1.620     albertel 1283:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1284:     $udom=$env{'user.name'} unless (defined($udom));
                   1285:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1286:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1287:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1288:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1289:                                                   # assigned to this person
                   1290:                                                   # - this should not happen,
1.345     www      1291:                                                   # unless something went wrong
                   1292:                                                   # the first time around
                   1293: # ready to assign
1.364     www      1294:         $logentry=$1.'; '.$logentry;
1.496     www      1295:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1296:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1297: # key now belongs to user
1.346     www      1298: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1299:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1300:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1301:                 return 'ok';
                   1302:             } else {
                   1303:                 return 
                   1304:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1305: 	    }
                   1306:         } else {
                   1307:             return 'error: Could not assign key, try again later.';
                   1308:         }
1.364     www      1309:     } elsif (!$existing{$ckey}) {
1.345     www      1310: # the key does not exist
                   1311: 	return 'error: The key does not exist';
                   1312:     } else {
                   1313: # the key is somebody else's
                   1314: 	return 'error: The key is already in use';
                   1315:     }
1.344     www      1316: }
                   1317: 
1.364     www      1318: # ------------------------------------------ put an additional comment on a key
                   1319: 
                   1320: sub comment_access_key {
                   1321: #
                   1322: # a valid key looks like uname:udom#comments
                   1323: # comments are being appended
                   1324: #
                   1325:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1326:     $cdom=
1.620     albertel 1327:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1328:     $cnum=
1.620     albertel 1329:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1330:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1331:     if ($existing{$ckey}) {
                   1332:         $existing{$ckey}.='; '.$logentry;
                   1333: # ready to assign
1.367     www      1334:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1335:                                                  $cdom,$cnum) eq 'ok') {
                   1336: 	    return 'ok';
                   1337:         } else {
                   1338: 	    return 'error: Count not store comment.';
                   1339:         }
                   1340:     } else {
                   1341: # the key does not exist
                   1342: 	return 'error: The key does not exist';
                   1343:     }
                   1344: }
                   1345: 
1.344     www      1346: # ------------------------------------------------------ Generate a set of keys
                   1347: 
                   1348: sub generate_access_keys {
1.364     www      1349:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1350:     $cdom=
1.620     albertel 1351:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1352:     $cnum=
1.620     albertel 1353:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1354:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1355:     unless (($cdom) && ($cnum)) { return 0; }
                   1356:     if ($number>10000) { return 0; }
                   1357:     sleep(2); # make sure don't get same seed twice
                   1358:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1359:     my $total=0;
                   1360:     for (my $i=1;$i<=$number;$i++) {
                   1361:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1362:                   sprintf("%lx",int(100000*rand)).'-'.
                   1363:                   sprintf("%lx",int(100000*rand));
                   1364:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1365:        $newkey=~s/0/h/g; # and also 0 and O
                   1366:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1367:        if ($existing{$newkey}) {
                   1368:            $i--;
                   1369:        } else {
1.364     www      1370: 	  if (&put('accesskeys',
                   1371:               { $newkey => '# generated '.localtime().
1.620     albertel 1372:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1373:                            '; '.$logentry },
                   1374: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1375:               $total++;
                   1376: 	  }
                   1377:        }
                   1378:     }
1.620     albertel 1379:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1380:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1381:     return $total;
                   1382: }
                   1383: 
                   1384: # ------------------------------------------------------- Validate an accesskey
                   1385: 
                   1386: sub validate_access_key {
                   1387:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1388:     $cdom=
1.620     albertel 1389:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1390:     $cnum=
1.620     albertel 1391:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1392:     $udom=$env{'user.domain'} unless (defined($udom));
                   1393:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1394:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1395:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1396: }
                   1397: 
                   1398: # ------------------------------------- Find the section of student in a course
1.652     albertel 1399: sub devalidate_getsection_cache {
                   1400:     my ($udom,$unam,$courseid)=@_;
                   1401:     my $hashid="$udom:$unam:$courseid";
                   1402:     &devalidate_cache_new('getsection',$hashid);
                   1403: }
1.298     matthew  1404: 
1.815     albertel 1405: sub courseid_to_courseurl {
                   1406:     my ($courseid) = @_;
                   1407:     #already url style courseid
                   1408:     return $courseid if ($courseid =~ m{^/});
                   1409: 
                   1410:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1411: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1412: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1413: 	return "/$cdom/$cnum";
                   1414:     }
                   1415: 
                   1416:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1417:     if (exists($courseinfo{'num'})) {
                   1418: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1419:     }
                   1420: 
                   1421:     return undef;
                   1422: }
                   1423: 
1.298     matthew  1424: sub getsection {
                   1425:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1426:     my $cachetime=1800;
1.551     albertel 1427: 
                   1428:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1429:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1430:     if (defined($cached)) { return $result; }
                   1431: 
1.298     matthew  1432:     my %Pending; 
                   1433:     my %Expired;
                   1434:     #
                   1435:     # Each role can either have not started yet (pending), be active, 
                   1436:     #    or have expired.
                   1437:     #
                   1438:     # If there is an active role, we are done.
                   1439:     #
                   1440:     # If there is more than one role which has not started yet, 
                   1441:     #     choose the one which will start sooner
                   1442:     # If there is one role which has not started yet, return it.
                   1443:     #
                   1444:     # If there is more than one expired role, choose the one which ended last.
                   1445:     # If there is a role which has expired, return it.
                   1446:     #
1.815     albertel 1447:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1448:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1449:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1450:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1451:         my $section=$1;
                   1452:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1453:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1454:         my $now=time;
1.548     albertel 1455:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1456:             $Expired{$end}=$section;
                   1457:             next;
                   1458:         }
1.548     albertel 1459:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1460:             $Pending{$start}=$section;
                   1461:             next;
                   1462:         }
1.599     albertel 1463:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1464:     }
                   1465:     #
                   1466:     # Presumedly there will be few matching roles from the above
                   1467:     # loop and the sorting time will be negligible.
                   1468:     if (scalar(keys(%Pending))) {
                   1469:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1470:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1471:     } 
                   1472:     if (scalar(keys(%Expired))) {
                   1473:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1474:         my $time = pop(@sorted);
1.599     albertel 1475:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1476:     }
1.599     albertel 1477:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1478: }
1.70      www      1479: 
1.599     albertel 1480: sub save_cache {
                   1481:     &purge_remembered();
1.722     albertel 1482:     #&Apache::loncommon::validate_page();
1.620     albertel 1483:     undef(%env);
1.780     albertel 1484:     undef($env_loaded);
1.599     albertel 1485: }
1.452     albertel 1486: 
1.599     albertel 1487: my $to_remember=-1;
                   1488: my %remembered;
                   1489: my %accessed;
                   1490: my $kicks=0;
                   1491: my $hits=0;
1.849     albertel 1492: sub make_key {
                   1493:     my ($name,$id) = @_;
1.872     albertel 1494:     if (length($id) > 65 
                   1495: 	&& length(&escape($id)) > 200) {
                   1496: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1497:     }
1.849     albertel 1498:     return &escape($name.':'.$id);
                   1499: }
                   1500: 
1.599     albertel 1501: sub devalidate_cache_new {
                   1502:     my ($name,$id,$debug) = @_;
                   1503:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1504:     $id=&make_key($name,$id);
1.599     albertel 1505:     $memcache->delete($id);
                   1506:     delete($remembered{$id});
                   1507:     delete($accessed{$id});
                   1508: }
                   1509: 
                   1510: sub is_cached_new {
                   1511:     my ($name,$id,$debug) = @_;
1.849     albertel 1512:     $id=&make_key($name,$id);
1.599     albertel 1513:     if (exists($remembered{$id})) {
                   1514: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1515: 	$accessed{$id}=[&gettimeofday()];
                   1516: 	$hits++;
                   1517: 	return ($remembered{$id},1);
                   1518:     }
                   1519:     my $value = $memcache->get($id);
                   1520:     if (!(defined($value))) {
                   1521: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1522: 	return (undef,undef);
1.416     albertel 1523:     }
1.599     albertel 1524:     if ($value eq '__undef__') {
                   1525: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1526: 	$value=undef;
                   1527:     }
                   1528:     &make_room($id,$value,$debug);
                   1529:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1530:     return ($value,1);
                   1531: }
                   1532: 
                   1533: sub do_cache_new {
                   1534:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1535:     $id=&make_key($name,$id);
1.599     albertel 1536:     my $setvalue=$value;
                   1537:     if (!defined($setvalue)) {
                   1538: 	$setvalue='__undef__';
                   1539:     }
1.623     albertel 1540:     if (!defined($time) ) {
                   1541: 	$time=600;
                   1542:     }
1.599     albertel 1543:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1544:     my $result = $memcache->set($id,$setvalue,$time);
                   1545:     if (! $result) {
1.872     albertel 1546: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1547: 	$memcache->disconnect_all();
1.872     albertel 1548:     }
1.600     albertel 1549:     # need to make a copy of $value
1.919     albertel 1550:     &make_room($id,$value,$debug);
1.599     albertel 1551:     return $value;
                   1552: }
                   1553: 
                   1554: sub make_room {
                   1555:     my ($id,$value,$debug)=@_;
1.919     albertel 1556: 
                   1557:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1558:                                     : $value;
1.599     albertel 1559:     if ($to_remember<0) { return; }
                   1560:     $accessed{$id}=[&gettimeofday()];
                   1561:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1562:     my $to_kick;
                   1563:     my $max_time=0;
                   1564:     foreach my $other (keys(%accessed)) {
                   1565: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1566: 	    $to_kick=$other;
                   1567: 	    $max_time=&tv_interval($accessed{$other});
                   1568: 	}
                   1569:     }
                   1570:     delete($remembered{$to_kick});
                   1571:     delete($accessed{$to_kick});
                   1572:     $kicks++;
                   1573:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1574:     return;
                   1575: }
                   1576: 
1.599     albertel 1577: sub purge_remembered {
1.604     albertel 1578:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1579:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1580:     undef(%remembered);
                   1581:     undef(%accessed);
1.428     albertel 1582: }
1.70      www      1583: # ------------------------------------- Read an entry from a user's environment
                   1584: 
                   1585: sub userenvironment {
                   1586:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1587:     my $items;
                   1588:     foreach my $item (@what) {
                   1589:         $items.=&escape($item).'&';
                   1590:     }
                   1591:     $items=~s/\&$//;
1.70      www      1592:     my %returnhash=();
                   1593:     my @answer=split(/\&/,
1.976     raeburn  1594:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1595:                       &homeserver($unam,$udom)));
                   1596:     my $i;
                   1597:     for ($i=0;$i<=$#what;$i++) {
                   1598: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1599:     }
                   1600:     return %returnhash;
1.1       albertel 1601: }
                   1602: 
1.617     albertel 1603: # ---------------------------------------------------------- Get a studentphoto
                   1604: sub studentphoto {
                   1605:     my ($udom,$unam,$ext) = @_;
                   1606:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1607:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1608:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1609:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1610:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1611:             } else {
                   1612:                 my ($result,$perm_reqd)=
1.707     albertel 1613: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1614:                 if ($result eq 'ok') {
                   1615:                     if (!($perm_reqd eq 'yes')) {
                   1616:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1617:                     }
                   1618:                 }
                   1619:             }
                   1620:         }
                   1621:     } else {
                   1622:         my ($result,$perm_reqd) = 
1.707     albertel 1623: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1624:         if ($result eq 'ok') {
                   1625:             if (!($perm_reqd eq 'yes')) {
                   1626:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1627:             }
                   1628:         }
                   1629:     }
                   1630:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1631: }
                   1632: 
                   1633: sub retrievestudentphoto {
                   1634:     my ($udom,$unam,$ext,$type) = @_;
                   1635:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1636:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1637:     if ($ret eq 'ok') {
                   1638:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1639:         if ($type eq 'thumbnail') {
                   1640:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1641:         }
                   1642:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1643:         return $tokenurl;
                   1644:     } else {
                   1645:         if ($type eq 'thumbnail') {
                   1646:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1647:         } else { 
                   1648:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1649:         }
1.617     albertel 1650:     }
                   1651: }
                   1652: 
1.263     www      1653: # -------------------------------------------------------------------- New chat
                   1654: 
                   1655: sub chatsend {
1.724     raeburn  1656:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1657:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1658:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1659:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1660:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1661: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1662: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1663: }
                   1664: 
                   1665: # ------------------------------------------ Find current version of a resource
                   1666: 
                   1667: sub getversion {
                   1668:     my $fname=&clutter(shift);
                   1669:     unless ($fname=~/^\/res\//) { return -1; }
                   1670:     return &currentversion(&filelocation('',$fname));
                   1671: }
                   1672: 
                   1673: sub currentversion {
                   1674:     my $fname=shift;
1.599     albertel 1675:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1676:     if (defined($cached)) { return $result; }
1.292     www      1677:     my $author=$fname;
                   1678:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1679:     my ($udom,$uname)=split(/\//,$author);
                   1680:     my $home=homeserver($uname,$udom);
                   1681:     if ($home eq 'no_host') { 
                   1682:         return -1; 
                   1683:     }
                   1684:     my $answer=reply("currentversion:$fname",$home);
                   1685:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1686: 	return -1;
                   1687:     }
1.599     albertel 1688:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1689: }
                   1690: 
1.1       albertel 1691: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1692: 
1.1       albertel 1693: sub subscribe {
                   1694:     my $fname=shift;
1.761     raeburn  1695:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1696:     $fname=~s/[\n\r]//g;
1.1       albertel 1697:     my $author=$fname;
                   1698:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1699:     my ($udom,$uname)=split(/\//,$author);
                   1700:     my $home=homeserver($uname,$udom);
1.335     albertel 1701:     if ($home eq 'no_host') {
                   1702:         return 'not_found';
1.1       albertel 1703:     }
                   1704:     my $answer=reply("sub:$fname",$home);
1.64      www      1705:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1706: 	$answer.=' by '.$home;
                   1707:     }
1.1       albertel 1708:     return $answer;
                   1709: }
                   1710:     
1.8       www      1711: # -------------------------------------------------------------- Replicate file
                   1712: 
                   1713: sub repcopy {
                   1714:     my $filename=shift;
1.23      www      1715:     $filename=~s/\/+/\//g;
1.607     raeburn  1716:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1717:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1718:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1719: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1720: 	return &repcopy_userfile($filename);
                   1721:     }
1.532     albertel 1722:     $filename=~s/[\n\r]//g;
1.8       www      1723:     my $transname="$filename.in.transfer";
1.828     www      1724: # FIXME: this should flock
1.607     raeburn  1725:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1726:     my $remoteurl=subscribe($filename);
1.64      www      1727:     if ($remoteurl =~ /^con_lost by/) {
                   1728: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1729:            return 'unavailable';
1.8       www      1730:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1731: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1732: 	   return 'not_found';
1.64      www      1733:     } elsif ($remoteurl =~ /^rejected by/) {
                   1734: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1735:            return 'forbidden';
1.20      www      1736:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1737:            return 'ok';
1.8       www      1738:     } else {
1.290     www      1739:         my $author=$filename;
                   1740:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1741:         my ($udom,$uname)=split(/\//,$author);
                   1742:         my $home=homeserver($uname,$udom);
                   1743:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1744:            my @parts=split(/\//,$filename);
                   1745:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1746:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1747:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1748: 	       return 'bad_request';
1.8       www      1749:            }
                   1750:            my $count;
                   1751:            for ($count=5;$count<$#parts;$count++) {
                   1752:                $path.="/$parts[$count]";
                   1753:                if ((-e $path)!=1) {
                   1754: 		   mkdir($path,0777);
                   1755:                }
                   1756:            }
                   1757:            my $ua=new LWP::UserAgent;
                   1758:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1759:            my $response=$ua->request($request,$transname);
                   1760:            if ($response->is_error()) {
                   1761: 	       unlink($transname);
                   1762:                my $message=$response->status_line;
1.672     albertel 1763:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1764:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1765:                return 'unavailable';
1.8       www      1766:            } else {
1.16      www      1767: 	       if ($remoteurl!~/\.meta$/) {
                   1768:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1769:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1770:                   if ($mresponse->is_error()) {
                   1771: 		      unlink($filename.'.meta');
                   1772:                       &logthis(
1.672     albertel 1773:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1774:                   }
                   1775: 	       }
1.8       www      1776:                rename($transname,$filename);
1.607     raeburn  1777:                return 'ok';
1.8       www      1778:            }
1.290     www      1779:        }
1.8       www      1780:     }
1.330     www      1781: }
                   1782: 
                   1783: # ------------------------------------------------ Get server side include body
                   1784: sub ssi_body {
1.381     albertel 1785:     my ($filelink,%form)=@_;
1.606     matthew  1786:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1787:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1788:     }
1.953     www      1789:     my $output='';
                   1790:     my $response;
1.976.2.3  raeburn  1791:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1792:        ($output,$response)=&externalssi($filelink);
1.953     www      1793:     } else {
                   1794:        ($output,$response)=&ssi($filelink,%form);
                   1795:     }
1.778     albertel 1796:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1797:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1798:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1799:     if (wantarray) {
                   1800:         return ($output, $response);
                   1801:     } else {
                   1802:         return $output;
                   1803:     }
1.8       www      1804: }
                   1805: 
1.15      www      1806: # --------------------------------------------------------- Server Side Include
                   1807: 
1.782     albertel 1808: sub absolute_url {
                   1809:     my ($host_name) = @_;
                   1810:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1811:     if ($host_name eq '') {
                   1812: 	$host_name = $ENV{'SERVER_NAME'};
                   1813:     }
                   1814:     return $protocol.$host_name;
                   1815: }
                   1816: 
1.942     foxr     1817: #
                   1818: #   Server side include.
                   1819: # Parameters:
                   1820: #  fn     Possibly encrypted resource name/id.
                   1821: #  form   Hash that describes how the rendering should be done
                   1822: #         and other things.
1.944     foxr     1823: # Returns:
1.950     raeburn  1824: #   Scalar context: The content of the response.
                   1825: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1826: #     
1.15      www      1827: sub ssi {
                   1828: 
1.944     foxr     1829:     my ($fn,%form)=@_;
1.15      www      1830:     my $ua=new LWP::UserAgent;
1.23      www      1831:     my $request;
1.711     albertel 1832: 
                   1833:     $form{'no_update_last_known'}=1;
1.895     albertel 1834:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1835:     if (%form) {
1.782     albertel 1836:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1837:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1838:     } else {
1.782     albertel 1839:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1840:     }
                   1841: 
1.15      www      1842:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1843:     my $response=$ua->request($request);
                   1844: 
1.944     foxr     1845:     if (wantarray) {
                   1846: 	return ($response->content, $response);
                   1847:     } else {
                   1848: 	return $response->content;
1.942     foxr     1849:     }
1.324     www      1850: }
                   1851: 
                   1852: sub externalssi {
                   1853:     my ($url)=@_;
                   1854:     my $ua=new LWP::UserAgent;
                   1855:     my $request=new HTTP::Request('GET',$url);
                   1856:     my $response=$ua->request($request);
1.954     raeburn  1857:     if (wantarray) {
                   1858:         return ($response->content, $response);
                   1859:     } else {
                   1860:         return $response->content;
                   1861:     }
1.15      www      1862: }
1.254     www      1863: 
1.492     albertel 1864: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1865: 
                   1866: sub allowuploaded {
                   1867:     my ($srcurl,$url)=@_;
                   1868:     $url=&clutter(&declutter($url));
                   1869:     my $dir=$url;
                   1870:     $dir=~s/\/[^\/]+$//;
                   1871:     my %httpref=();
                   1872:     my $httpurl=&hreflocation('',$url);
                   1873:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1874:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1875: }
1.477     raeburn  1876: 
1.478     albertel 1877: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1878: # input: action, courseID, current domain, intended
1.637     raeburn  1879: #        path to file, source of file, instruction to parse file for objects,
                   1880: #        ref to hash for embedded objects,
                   1881: #        ref to hash for codebase of java objects.
                   1882: #
1.485     raeburn  1883: # output: url to file (if action was uploaddoc), 
                   1884: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1885: #
1.478     albertel 1886: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1887: # course.
1.477     raeburn  1888: #
1.478     albertel 1889: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1890: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1891: #          course's home server.
1.477     raeburn  1892: #
1.478     albertel 1893: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1894: #          be copied from $source (current location) to 
                   1895: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1896: #         and will then be copied to
                   1897: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1898: #         course's home server.
1.485     raeburn  1899: #
1.481     raeburn  1900: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1901: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1902: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1903: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1904: #         in course's home server.
1.637     raeburn  1905: #
1.477     raeburn  1906: 
                   1907: sub process_coursefile {
1.638     albertel 1908:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1909:     my $fetchresult;
1.638     albertel 1910:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1911:     if ($action eq 'propagate') {
1.638     albertel 1912:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1913: 			     $home);
1.481     raeburn  1914:     } else {
1.477     raeburn  1915:         my $fpath = '';
                   1916:         my $fname = $file;
1.478     albertel 1917:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1918:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1919:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1920:         if ($action eq 'copy') {
                   1921:             if ($source eq '') {
                   1922:                 $fetchresult = 'no source file';
                   1923:                 return $fetchresult;
                   1924:             } else {
                   1925:                 my $destination = $filepath.'/'.$fname;
                   1926:                 rename($source,$destination);
                   1927:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1928:                                  $home);
1.481     raeburn  1929:             }
                   1930:         } elsif ($action eq 'uploaddoc') {
                   1931:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1932:             print $fh $env{'form.'.$source};
1.481     raeburn  1933:             close($fh);
1.637     raeburn  1934:             if ($parser eq 'parse') {
1.961     raeburn  1935:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1936:                 unless ($parse_result eq 'ok') {
                   1937:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1938:                 }
                   1939:             }
1.477     raeburn  1940:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1941:                                  $home);
1.481     raeburn  1942:             if ($fetchresult eq 'ok') {
                   1943:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1944:             } else {
                   1945:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1946:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1947:                 return '/adm/notfound.html';
                   1948:             }
1.477     raeburn  1949:         }
                   1950:     }
1.485     raeburn  1951:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1952:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1953:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1954:     }
                   1955:     return $fetchresult;
                   1956: }
                   1957: 
1.637     raeburn  1958: sub build_filepath {
                   1959:     my ($fpath) = @_;
                   1960:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1961:     unless ($fpath eq '') {
                   1962:         my @parts=split('/',$fpath);
                   1963:         foreach my $part (@parts) {
                   1964:             $filepath.= '/'.$part;
                   1965:             if ((-e $filepath)!=1) {
                   1966:                 mkdir($filepath,0777);
                   1967:             }
                   1968:         }
                   1969:     }
                   1970:     return $filepath;
                   1971: }
                   1972: 
                   1973: sub store_edited_file {
1.638     albertel 1974:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1975:     my $file = $primary_url;
                   1976:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1977:     my $fpath = '';
                   1978:     my $fname = $file;
                   1979:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1980:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1981:     my $filepath = &build_filepath($fpath);
                   1982:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1983:     print $fh $content;
                   1984:     close($fh);
1.638     albertel 1985:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1986:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1987: 			  $home);
1.637     raeburn  1988:     if ($$fetchresult eq 'ok') {
                   1989:         return '/uploaded/'.$fpath.'/'.$fname;
                   1990:     } else {
1.638     albertel 1991:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1992: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1993:         return '/adm/notfound.html';
                   1994:     }
                   1995: }
                   1996: 
1.531     albertel 1997: sub clean_filename {
1.831     albertel 1998:     my ($fname,$args)=@_;
1.315     www      1999: # Replace Windows backslashes by forward slashes
1.257     www      2000:     $fname=~s/\\/\//g;
1.831     albertel 2001:     if (!$args->{'keep_path'}) {
                   2002:         # Get rid of everything but the actual filename
                   2003: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2004:     }
1.315     www      2005: # Replace spaces by underscores
                   2006:     $fname=~s/\s+/\_/g;
                   2007: # Replace all other weird characters by nothing
1.831     albertel 2008:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2009: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2010: # numbers
                   2011:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2012:     return $fname;
                   2013: }
                   2014: 
1.608     albertel 2015: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2016: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2017: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2018: #        $coursedoc - if true up to the current course
                   2019: #                     if false
                   2020: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2021: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2022: #        $allfiles - reference to hash for embedded objects
                   2023: #        $codebase - reference to hash for codebase of java objects
                   2024: #        $desuname - username for permanent storage of uploaded file
                   2025: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2026: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2027: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2028: # 
1.686     albertel 2029: # output: url of file in userspace, or error: <message> 
                   2030: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2031: 
                   2032: 
1.531     albertel 2033: sub userfileupload {
1.860     raeburn  2034:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2035:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2036:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2037:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2038:     $fname=&clean_filename($fname);
1.315     www      2039: # See if there is anything left
1.257     www      2040:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2041:     chop($env{'form.'.$formname});
1.523     raeburn  2042:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2043:         my $now = time;
                   2044:         my $filepath = 'tmp/helprequests/'.$now;
                   2045:         my @parts=split(/\//,$filepath);
                   2046:         my $fullpath = $perlvar{'lonDaemons'};
                   2047:         for (my $i=0;$i<@parts;$i++) {
                   2048:             $fullpath .= '/'.$parts[$i];
                   2049:             if ((-e $fullpath)!=1) {
                   2050:                 mkdir($fullpath,0777);
                   2051:             }
                   2052:         }
                   2053:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2054:         print $fh $env{'form.'.$formname};
1.523     raeburn  2055:         close($fh);
1.741     raeburn  2056:         return $fullpath.'/'.$fname;
                   2057:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2058:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2059:                        '_'.$env{'user.domain'}.'/pending';
                   2060:         my @parts=split(/\//,$filepath);
                   2061:         my $fullpath = $perlvar{'lonDaemons'};
                   2062:         for (my $i=0;$i<@parts;$i++) {
                   2063:             $fullpath .= '/'.$parts[$i];
                   2064:             if ((-e $fullpath)!=1) {
                   2065:                 mkdir($fullpath,0777);
                   2066:             }
                   2067:         }
                   2068:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2069:         print $fh $env{'form.'.$formname};
                   2070:         close($fh);
                   2071:         return $fullpath.'/'.$fname;
1.523     raeburn  2072:     }
1.719     banghart 2073:     
1.258     www      2074: # Create the directory if not present
1.493     albertel 2075:     $fname="$subdir/$fname";
1.259     www      2076:     if ($coursedoc) {
1.638     albertel 2077: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2078: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2079:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2080:             return &finishuserfileupload($docuname,$docudom,
                   2081: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2082: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2083:         } else {
1.620     albertel 2084:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2085:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2086: 				       $fname,$formname,$parser,
                   2087: 				       $allfiles,$codebase);
1.481     raeburn  2088:         }
1.719     banghart 2089:     } elsif (defined($destuname)) {
                   2090:         my $docuname=$destuname;
                   2091:         my $docudom=$destudom;
1.860     raeburn  2092: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2093: 				     $parser,$allfiles,$codebase,
                   2094:                                      $thumbwidth,$thumbheight);
1.719     banghart 2095:         
1.259     www      2096:     } else {
1.638     albertel 2097:         my $docuname=$env{'user.name'};
                   2098:         my $docudom=$env{'user.domain'};
1.714     raeburn  2099:         if (exists($env{'form.group'})) {
                   2100:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2101:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2102:         }
1.860     raeburn  2103: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2104: 				     $parser,$allfiles,$codebase,
                   2105:                                      $thumbwidth,$thumbheight);
1.259     www      2106:     }
1.271     www      2107: }
                   2108: 
                   2109: sub finishuserfileupload {
1.860     raeburn  2110:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2111:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2112:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2113:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2114:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2115:     $file=$fname;
                   2116:     if ($fname=~m|/|) {
                   2117:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2118: 	$path.=$fnamepath.'/';
                   2119:     }
1.259     www      2120:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2121:     my $count;
                   2122:     for ($count=4;$count<=$#parts;$count++) {
                   2123:         $filepath.="/$parts[$count]";
                   2124:         if ((-e $filepath)!=1) {
                   2125: 	    mkdir($filepath,0777);
                   2126:         }
                   2127:     }
                   2128: # Save the file
                   2129:     {
1.701     albertel 2130: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2131: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2132: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2133: 	    return '/adm/notfound.html';
                   2134: 	}
                   2135: 	if (!print FH ($env{'form.'.$formname})) {
                   2136: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2137: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2138: 	    return '/adm/notfound.html';
                   2139: 	}
1.570     albertel 2140: 	close(FH);
1.258     www      2141:     }
1.637     raeburn  2142:     if ($parser eq 'parse') {
1.961     raeburn  2143:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2144: 						   $codebase);
1.637     raeburn  2145:         unless ($parse_result eq 'ok') {
1.638     albertel 2146:             &logthis('Failed to parse '.$filepath.$file.
                   2147: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2148:         }
                   2149:     }
1.860     raeburn  2150:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2151:         my $input = $filepath.'/'.$file;
                   2152:         my $output = $filepath.'/'.'tn-'.$file;
                   2153:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2154:         system("convert -sample $thumbsize $input $output");
                   2155:         if (-e $filepath.'/'.'tn-'.$file) {
                   2156:             $fetchthumb  = 1; 
                   2157:         }
                   2158:     }
1.858     raeburn  2159:  
1.259     www      2160: # Notify homeserver to grep it
                   2161: #
1.638     albertel 2162:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2163:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2164:     if ($fetchresult eq 'ok') {
1.860     raeburn  2165:         if ($fetchthumb) {
                   2166:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2167:             if ($thumbresult ne 'ok') {
                   2168:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2169:                          $docuhome.': '.$thumbresult);
                   2170:             }
                   2171:         }
1.259     www      2172: #
1.258     www      2173: # Return the URL to it
1.494     albertel 2174:         return '/uploaded/'.$path.$file;
1.263     www      2175:     } else {
1.494     albertel 2176:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2177: 		 ': '.$fetchresult);
1.263     www      2178:         return '/adm/notfound.html';
1.858     raeburn  2179:     }
1.493     albertel 2180: }
                   2181: 
1.637     raeburn  2182: sub extract_embedded_items {
1.961     raeburn  2183:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2184:     my @state = ();
                   2185:     my %javafiles = (
                   2186:                       codebase => '',
                   2187:                       code => '',
                   2188:                       archive => ''
                   2189:                     );
                   2190:     my %mediafiles = (
                   2191:                       src => '',
                   2192:                       movie => '',
                   2193:                      );
1.648     raeburn  2194:     my $p;
                   2195:     if ($content) {
                   2196:         $p = HTML::LCParser->new($content);
                   2197:     } else {
1.961     raeburn  2198:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2199:     }
1.641     albertel 2200:     while (my $t=$p->get_token()) {
1.640     albertel 2201: 	if ($t->[0] eq 'S') {
                   2202: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2203: 	    push(@state, $tagname);
1.648     raeburn  2204:             if (lc($tagname) eq 'allow') {
                   2205:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2206:             }
1.640     albertel 2207: 	    if (lc($tagname) eq 'img') {
                   2208: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2209: 	    }
1.886     albertel 2210: 	    if (lc($tagname) eq 'a') {
                   2211: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2212: 	    }
1.645     raeburn  2213:             if (lc($tagname) eq 'script') {
                   2214:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2215:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2216:                 } else {
                   2217:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2218:                 }
                   2219:             }
                   2220:             if (lc($tagname) eq 'link') {
                   2221:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2222:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2223:                 }
                   2224:             }
1.640     albertel 2225: 	    if (lc($tagname) eq 'object' ||
                   2226: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2227: 		foreach my $item (keys(%javafiles)) {
                   2228: 		    $javafiles{$item} = '';
                   2229: 		}
                   2230: 	    }
                   2231: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2232: 		my $name = lc($attr->{'name'});
                   2233: 		foreach my $item (keys(%javafiles)) {
                   2234: 		    if ($name eq $item) {
                   2235: 			$javafiles{$item} = $attr->{'value'};
                   2236: 			last;
                   2237: 		    }
                   2238: 		}
                   2239: 		foreach my $item (keys(%mediafiles)) {
                   2240: 		    if ($name eq $item) {
                   2241: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2242: 			last;
                   2243: 		    }
                   2244: 		}
                   2245: 	    }
                   2246: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2247: 		foreach my $item (keys(%javafiles)) {
                   2248: 		    if ($attr->{$item}) {
                   2249: 			$javafiles{$item} = $attr->{$item};
                   2250: 			last;
                   2251: 		    }
                   2252: 		}
                   2253: 		foreach my $item (keys(%mediafiles)) {
                   2254: 		    if ($attr->{$item}) {
                   2255: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2256: 			last;
                   2257: 		    }
                   2258: 		}
                   2259: 	    }
                   2260: 	} elsif ($t->[0] eq 'E') {
                   2261: 	    my ($tagname) = ($t->[1]);
                   2262: 	    if ($javafiles{'codebase'} ne '') {
                   2263: 		$javafiles{'codebase'} .= '/';
                   2264: 	    }  
                   2265: 	    if (lc($tagname) eq 'applet' ||
                   2266: 		lc($tagname) eq 'object' ||
                   2267: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2268: 		) {
                   2269: 		foreach my $item (keys(%javafiles)) {
                   2270: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2271: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2272: 			&add_filetype($allfiles,$file,$item);
                   2273: 		    }
                   2274: 		}
                   2275: 	    } 
                   2276: 	    pop @state;
                   2277: 	}
                   2278:     }
1.637     raeburn  2279:     return 'ok';
                   2280: }
                   2281: 
1.639     albertel 2282: sub add_filetype {
                   2283:     my ($allfiles,$file,$type)=@_;
                   2284:     if (exists($allfiles->{$file})) {
                   2285: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2286: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2287: 	}
                   2288:     } else {
                   2289: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2290:     }
                   2291: }
                   2292: 
1.493     albertel 2293: sub removeuploadedurl {
                   2294:     my ($url)=@_;
                   2295:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2296:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2297: }
                   2298: 
                   2299: sub removeuserfile {
                   2300:     my ($docuname,$docudom,$fname)=@_;
                   2301:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2302:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2303:     if ($result eq 'ok') {
                   2304:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2305:             my $metafile = $fname.'.meta';
                   2306:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2307: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2308:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2309:             my $sqlresult = 
1.823     albertel 2310:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2311:                                         'portfolio_metadata',$group,
                   2312:                                         'delete');
1.798     raeburn  2313:         }
                   2314:     }
                   2315:     return $result;
1.257     www      2316: }
1.15      www      2317: 
1.530     albertel 2318: sub mkdiruserfile {
                   2319:     my ($docuname,$docudom,$dir)=@_;
                   2320:     my $home=&homeserver($docuname,$docudom);
                   2321:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2322: }
                   2323: 
1.531     albertel 2324: sub renameuserfile {
                   2325:     my ($docuname,$docudom,$old,$new)=@_;
                   2326:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2327:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2328:                         &escape("$old").':'.&escape("$new"),$home);
                   2329:     if ($result eq 'ok') {
                   2330:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2331:             my $oldmeta = $old.'.meta';
                   2332:             my $newmeta = $new.'.meta';
                   2333:             my $metaresult = 
                   2334:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2335: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2336:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2337:             my $sqlresult = 
1.823     albertel 2338:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2339:                                         'portfolio_metadata',$group,
                   2340:                                         'delete');
1.798     raeburn  2341:         }
                   2342:     }
                   2343:     return $result;
1.531     albertel 2344: }
                   2345: 
1.14      www      2346: # ------------------------------------------------------------------------- Log
                   2347: 
                   2348: sub log {
                   2349:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2350:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2351: }
                   2352: 
                   2353: # ------------------------------------------------------------------ Course Log
1.352     www      2354: #
                   2355: # This routine flushes several buffers of non-mission-critical nature
                   2356: #
1.157     www      2357: 
                   2358: sub flushcourselogs {
1.352     www      2359:     &logthis('Flushing log buffers');
                   2360: #
                   2361: # course logs
                   2362: # This is a log of all transactions in a course, which can be used
                   2363: # for data mining purposes
                   2364: #
                   2365: # It also collects the courseid database, which lists last transaction
                   2366: # times and course titles for all courseids
                   2367: #
                   2368:     my %courseidbuffer=();
1.921     raeburn  2369:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2370:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2371: 		          &escape($courselogs{$crsid}),
                   2372: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2373: 	    delete $courselogs{$crsid};
                   2374:         } else {
                   2375:             &logthis('Failed to flush log buffer for '.$crsid);
                   2376:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2377:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2378:                         " exceeded maximum size, deleting.</font>");
                   2379:                delete $courselogs{$crsid};
                   2380:             }
1.352     www      2381:         }
1.920     raeburn  2382:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2383:             'description' => $coursedescrbuf{$crsid},
                   2384:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2385:             'type'        => $coursetypebuf{$crsid},
                   2386:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2387:         };
1.191     harris41 2388:     }
1.352     www      2389: #
                   2390: # Write course id database (reverse lookup) to homeserver of courses 
                   2391: # Is used in pickcourse
                   2392: #
1.840     albertel 2393:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2394:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2395:                                     $courseidbuffer{$crs_home},
                   2396:                                     $crs_home,'timeonly');
1.352     www      2397:     }
                   2398: #
                   2399: # File accesses
                   2400: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2401: #
1.449     matthew  2402:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2403:         if ($entry =~ /___count$/) {
                   2404:             my ($dom,$name);
1.807     albertel 2405:             ($dom,$name,undef)=
1.811     albertel 2406: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2407:             if (! defined($dom) || $dom eq '' || 
                   2408:                 ! defined($name) || $name eq '') {
1.620     albertel 2409:                 my $cid = $env{'request.course.id'};
                   2410:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2411:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2412:             }
1.450     matthew  2413:             my $value = $accesshash{$entry};
                   2414:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2415:             my %temphash=($url => $value);
1.449     matthew  2416:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2417:             if ($result eq 'ok') {
                   2418:                 delete $accesshash{$entry};
                   2419:             } elsif ($result eq 'unknown_cmd') {
                   2420:                 # Target server has old code running on it.
1.450     matthew  2421:                 my %temphash=($entry => $value);
1.449     matthew  2422:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2423:                     delete $accesshash{$entry};
                   2424:                 }
                   2425:             }
                   2426:         } else {
1.811     albertel 2427:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2428:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2429:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2430:                 delete $accesshash{$entry};
                   2431:             }
1.185     www      2432:         }
1.191     harris41 2433:     }
1.352     www      2434: #
                   2435: # Roles
                   2436: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2437: #
1.800     albertel 2438:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2439:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2440: 	    split(/\:/,$entry);
                   2441:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2442:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2443:                 $rudom,$runame) eq 'ok') {
                   2444: 	    delete $userrolehash{$entry};
                   2445:         }
                   2446:     }
1.662     raeburn  2447: #
                   2448: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2449: #
                   2450:     my %domrolebuffer = ();
                   2451:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2452:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2453:         if ($domrolebuffer{$rudom}) {
                   2454:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2455:                       '='.&escape($domainrolehash{$entry});
                   2456:         } else {
                   2457:             $domrolebuffer{$rudom}.=&escape($entry).
                   2458:                       '='.&escape($domainrolehash{$entry});
                   2459:         }
                   2460:         delete $domainrolehash{$entry};
                   2461:     }
                   2462:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2463: 	my %servers = &get_servers($dom,'library');
                   2464: 	foreach my $tryserver (keys(%servers)) {
                   2465: 	    unless (&reply('domroleput:'.$dom.':'.
                   2466: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2467: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2468: 	    }
1.662     raeburn  2469:         }
                   2470:     }
1.186     www      2471:     $dumpcount++;
1.157     www      2472: }
                   2473: 
                   2474: sub courselog {
                   2475:     my $what=shift;
1.158     www      2476:     $what=time.':'.$what;
1.620     albertel 2477:     unless ($env{'request.course.id'}) { return ''; }
                   2478:     $coursedombuf{$env{'request.course.id'}}=
                   2479:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2480:     $coursenumbuf{$env{'request.course.id'}}=
                   2481:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2482:     $coursehombuf{$env{'request.course.id'}}=
                   2483:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2484:     $coursedescrbuf{$env{'request.course.id'}}=
                   2485:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2486:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2487:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2488:     $courseownerbuf{$env{'request.course.id'}}=
                   2489:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2490:     $coursetypebuf{$env{'request.course.id'}}=
                   2491:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2492:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2493: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2494:     } else {
1.620     albertel 2495: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2496:     }
1.620     albertel 2497:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2498: 	&flushcourselogs();
                   2499:     }
1.158     www      2500: }
                   2501: 
                   2502: sub courseacclog {
                   2503:     my $fnsymb=shift;
1.620     albertel 2504:     unless ($env{'request.course.id'}) { return ''; }
                   2505:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2506:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2507:         $what.=':POST';
1.583     matthew  2508:         # FIXME: Probably ought to escape things....
1.800     albertel 2509: 	foreach my $key (keys(%env)) {
                   2510:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2511:                 my $formitem = $1;
                   2512:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2513:                     $what.=':'.$formitem.'='.$env{$key};
                   2514:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2515:                     $what.=':'.$formitem.'='.$env{$key};
                   2516:                 }
1.158     www      2517:             }
1.191     harris41 2518:         }
1.583     matthew  2519:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2520:         # FIXME: We should not be depending on a form parameter that someone
                   2521:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2522:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2523:             $what.= ':POST';
                   2524:             # FIXME: Probably ought to escape things....
                   2525:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2526:                                  'crsdiscuss') {
1.620     albertel 2527:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2528:             }
                   2529:         }
1.158     www      2530:     }
                   2531:     &courselog($what);
1.149     www      2532: }
                   2533: 
1.185     www      2534: sub countacc {
                   2535:     my $url=&declutter(shift);
1.458     matthew  2536:     return if (! defined($url) || $url eq '');
1.620     albertel 2537:     unless ($env{'request.course.id'}) { return ''; }
                   2538:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2539:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2540:     $accesshash{$key}++;
1.185     www      2541: }
1.349     www      2542: 
1.361     www      2543: sub linklog {
                   2544:     my ($from,$to)=@_;
                   2545:     $from=&declutter($from);
                   2546:     $to=&declutter($to);
                   2547:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2548:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2549: }
                   2550:   
1.349     www      2551: sub userrolelog {
                   2552:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2553:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2554:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2555:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2556:         ($trole=~/^ta/)) {
1.350     www      2557:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2558:        $userrolehash
                   2559:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2560:                     =$tend.':'.$tstart;
1.662     raeburn  2561:     }
1.898     albertel 2562:     if (($env{'request.role'} =~ /dc\./) &&
                   2563: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2564: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2565: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2566:        $userrolehash
                   2567:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2568:                     =$tend.':'.$tstart;
                   2569:     }
1.662     raeburn  2570:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2571:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2572:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2573:         ($trole=~/^sc/)) {
                   2574:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2575:        $domainrolehash
                   2576:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2577:                     = $tend.':'.$tstart;
                   2578:     }
1.351     www      2579: }
                   2580: 
1.957     raeburn  2581: sub courserolelog {
                   2582:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2583:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2584:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2585:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2586:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2587:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2588:             my $cdom = $1;
                   2589:             my $cnum = $2;
                   2590:             my $sec = $3;
                   2591:             my $namespace = 'rolelog';
                   2592:             my %storehash = (
                   2593:                                role    => $trole,
                   2594:                                start   => $tstart,
                   2595:                                end     => $tend,
                   2596:                                selfenroll => $selfenroll,
                   2597:                                context    => $context,
                   2598:                             );
                   2599:             if ($trole eq 'gr') {
                   2600:                 $namespace = 'groupslog';
                   2601:                 $storehash{'group'} = $sec;
                   2602:             } else {
                   2603:                 $storehash{'section'} = $sec;
                   2604:             }
                   2605:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2606:         }
                   2607:     }
                   2608:     return;
                   2609: }
                   2610: 
1.351     www      2611: sub get_course_adv_roles {
1.948     raeburn  2612:     my ($cid,$codes) = @_;
1.620     albertel 2613:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2614:     my %coursehash=&coursedescription($cid);
1.470     www      2615:     my %nothide=();
1.800     albertel 2616:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2617:         if ($user !~ /:/) {
                   2618: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2619:         } else {
                   2620:             $nothide{$user}=1;
                   2621:         }
1.470     www      2622:     }
1.351     www      2623:     my %returnhash=();
                   2624:     my %dumphash=
                   2625:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2626:     my $now=time;
1.800     albertel 2627:     foreach my $entry (keys %dumphash) {
                   2628: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2629:         if (($tstart) && ($tstart<0)) { next; }
                   2630:         if (($tend) && ($tend<$now)) { next; }
                   2631:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2632:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2633: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2634: 	if ((&privileged($username,$domain)) && 
                   2635: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2636: 	if ($role eq 'cr') { next; }
1.948     raeburn  2637:         if ($codes) {
                   2638:             if ($section) { $role .= ':'.$section; }
                   2639:             if ($returnhash{$role}) {
                   2640:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2641:             } else {
                   2642:                 $returnhash{$role}=$username.':'.$domain;
                   2643:             }
1.351     www      2644:         } else {
1.948     raeburn  2645:             my $key=&plaintext($role);
1.973     bisitz   2646:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2647:             if ($returnhash{$key}) {
                   2648: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2649:             } else {
                   2650:                 $returnhash{$key}=$username.':'.$domain;
                   2651:             }
1.351     www      2652:         }
1.948     raeburn  2653:     }
1.400     www      2654:     return %returnhash;
                   2655: }
                   2656: 
                   2657: sub get_my_roles {
1.937     raeburn  2658:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2659:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2660:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2661:     my (%dumphash,%nothide);
1.858     raeburn  2662:     if ($context eq 'userroles') { 
                   2663:         %dumphash = &dump('roles',$udom,$uname);
                   2664:     } else {
                   2665:         %dumphash=
1.400     www      2666:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2667:         if ($hidepriv) {
                   2668:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2669:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2670:                 if ($user !~ /:/) {
                   2671:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2672:                 } else {
                   2673:                     $nothide{$user} = 1;
                   2674:                 }
                   2675:             }
                   2676:         }
1.858     raeburn  2677:     }
1.400     www      2678:     my %returnhash=();
                   2679:     my $now=time;
1.800     albertel 2680:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2681:         my ($role,$tend,$tstart);
                   2682:         if ($context eq 'userroles') {
                   2683: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2684:         } else {
                   2685:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2686:         }
1.400     www      2687:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2688:         my $status = 'active';
1.939     raeburn  2689:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2690:             $status = 'previous';
                   2691:         } 
                   2692:         if (($tstart) && ($now<$tstart)) {
                   2693:             $status = 'future';
                   2694:         }
                   2695:         if (ref($types) eq 'ARRAY') {
                   2696:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2697:                 next;
                   2698:             } 
                   2699:         } else {
                   2700:             if ($status ne 'active') {
                   2701:                 next;
                   2702:             }
                   2703:         }
1.867     raeburn  2704:         my ($rolecode,$username,$domain,$section,$area);
                   2705:         if ($context eq 'userroles') {
                   2706:             ($area,$rolecode) = split(/_/,$entry);
                   2707:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2708:         } else {
                   2709:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2710:         }
1.832     raeburn  2711:         if (ref($roledoms) eq 'ARRAY') {
                   2712:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2713:                 next;
                   2714:             }
                   2715:         }
                   2716:         if (ref($roles) eq 'ARRAY') {
                   2717:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2718:                 if ($role =~ /^cr\//) {
                   2719:                     if (!grep(/^cr$/,@{$roles})) {
                   2720:                         next;
                   2721:                     }
                   2722:                 } else {
                   2723:                     next;
                   2724:                 }
1.832     raeburn  2725:             }
1.867     raeburn  2726:         }
1.937     raeburn  2727:         if ($hidepriv) {
                   2728:             if ((&privileged($username,$domain)) &&
                   2729:                 (!$nothide{$username.':'.$domain})) { 
                   2730:                 next;
                   2731:             }
                   2732:         }
1.933     raeburn  2733:         if ($withsec) {
                   2734:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2735:                 $tstart.':'.$tend;
                   2736:         } else {
                   2737:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2738:         }
1.832     raeburn  2739:     }
1.373     www      2740:     return %returnhash;
1.399     www      2741: }
                   2742: 
                   2743: # ----------------------------------------------------- Frontpage Announcements
                   2744: #
                   2745: #
                   2746: 
                   2747: sub postannounce {
                   2748:     my ($server,$text)=@_;
1.844     albertel 2749:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2750:     unless ($text=~/\w/) { $text=''; }
                   2751:     return &reply('setannounce:'.&escape($text),$server);
                   2752: }
                   2753: 
                   2754: sub getannounce {
1.448     albertel 2755: 
                   2756:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2757: 	my $announcement='';
1.800     albertel 2758: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2759: 	close($fh);
1.399     www      2760: 	if ($announcement=~/\w/) { 
                   2761: 	    return 
                   2762:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2763:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2764: 	} else {
                   2765: 	    return '';
                   2766: 	}
                   2767:     } else {
                   2768: 	return '';
                   2769:     }
1.351     www      2770: }
1.353     www      2771: 
                   2772: # ---------------------------------------------------------- Course ID routines
                   2773: # Deal with domain's nohist_courseid.db files
                   2774: #
                   2775: 
                   2776: sub courseidput {
1.921     raeburn  2777:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2778:     my $outcome;
                   2779:     if ($caller eq 'timeonly') {
                   2780:         my $cids = '';
                   2781:         foreach my $item (keys(%$storehash)) {
                   2782:             $cids.=&escape($item).'&';
                   2783:         }
                   2784:         $cids=~s/\&$//;
                   2785:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2786:                           $coursehome);       
                   2787:     } else {
                   2788:         my $items = '';
                   2789:         foreach my $item (keys(%$storehash)) {
                   2790:             $items.= &escape($item).'='.
                   2791:                      &freeze_escape($$storehash{$item}).'&';
                   2792:         }
                   2793:         $items=~s/\&$//;
                   2794:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2795:                           $coursehome);
1.918     raeburn  2796:     }
                   2797:     if ($outcome eq 'unknown_cmd') {
                   2798:         my $what;
                   2799:         foreach my $cid (keys(%$storehash)) {
                   2800:             $what .= &escape($cid).'=';
1.921     raeburn  2801:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2802:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2803:             }
                   2804:             $what =~ s/\:$/&/;
                   2805:         }
                   2806:         $what =~ s/\&$//;  
                   2807:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2808:     } else {
                   2809:         return $outcome;
                   2810:     }
1.353     www      2811: }
                   2812: 
                   2813: sub courseiddump {
1.921     raeburn  2814:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2815:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2816:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2817:     my $as_hash = 1;
                   2818:     my %returnhash;
                   2819:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2820:     my %libserv = &all_library();
                   2821:     foreach my $tryserver (keys(%libserv)) {
                   2822:         if ( (  $hostidflag == 1 
                   2823: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2824: 	     || (!defined($hostidflag)) ) {
                   2825: 
1.918     raeburn  2826: 	    if (($domfilter eq '') ||
                   2827: 		(&host_domain($tryserver) eq $domfilter)) {
                   2828:                 my $rep = 
                   2829:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2830:                          $sincefilter.':'.&escape($descfilter).':'.
                   2831:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2832:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2833:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2834:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2835:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2836:                 my @pairs=split(/\&/,$rep);
                   2837:                 foreach my $item (@pairs) {
                   2838:                     my ($key,$value)=split(/\=/,$item,2);
                   2839:                     $key = &unescape($key);
                   2840:                     next if ($key =~ /^error: 2 /);
                   2841:                     my $result = &thaw_unescape($value);
                   2842:                     if (ref($result) eq 'HASH') {
                   2843:                         $returnhash{$key}=$result;
                   2844:                     } else {
1.921     raeburn  2845:                         my @responses = split(/:/,$value);
                   2846:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2847:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2848:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2849:                         }
                   2850:                     } 
1.353     www      2851:                 }
                   2852:             }
                   2853:         }
                   2854:     }
                   2855:     return %returnhash;
                   2856: }
                   2857: 
1.658     raeburn  2858: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2859: 
                   2860: sub dcmailput {
1.685     raeburn  2861:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2862:     my $status = &Apache::lonnet::critical(
1.740     www      2863:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2864:        &escape($message),$server);
1.662     raeburn  2865:     return $status;
                   2866: }
                   2867: 
1.658     raeburn  2868: sub dcmaildump {
                   2869:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2870:     my %returnhash=();
1.846     albertel 2871: 
                   2872:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2873:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2874:                                                          &escape($enddate).':';
                   2875: 	my @esc_senders=map { &escape($_)} @$senders;
                   2876: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2877: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2878:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2879:             if (($key) && ($value)) {
                   2880:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2881:             }
                   2882:         }
                   2883:     }
                   2884:     return %returnhash;
                   2885: }
1.662     raeburn  2886: # ---------------------------------------------------------- Domain roles
                   2887: 
                   2888: sub get_domain_roles {
                   2889:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2890:     if (undef($startdate) || $startdate eq '') {
                   2891:         $startdate = '.';
                   2892:     }
                   2893:     if (undef($enddate) || $enddate eq '') {
                   2894:         $enddate = '.';
                   2895:     }
1.922     raeburn  2896:     my $rolelist;
                   2897:     if (ref($roles) eq 'ARRAY') {
                   2898:         $rolelist = join(':',@{$roles});
                   2899:     }
1.662     raeburn  2900:     my %personnel = ();
1.841     albertel 2901: 
                   2902:     my %servers = &get_servers($dom,'library');
                   2903:     foreach my $tryserver (keys(%servers)) {
                   2904: 	%{$personnel{$tryserver}}=();
                   2905: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2906: 					    &escape($startdate).':'.
                   2907: 					    &escape($enddate).':'.
                   2908: 					    &escape($rolelist), $tryserver))) {
                   2909: 	    my ($key,$value) = split(/\=/,$line,2);
                   2910: 	    if (($key) && ($value)) {
                   2911: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2912: 	    }
                   2913: 	}
1.662     raeburn  2914:     }
                   2915:     return %personnel;
                   2916: }
1.658     raeburn  2917: 
1.149     www      2918: # ----------------------------------------------------------- Check out an item
                   2919: 
1.504     albertel 2920: sub get_first_access {
                   2921:     my ($type,$argsymb)=@_;
1.790     albertel 2922:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2923:     if ($argsymb) { $symb=$argsymb; }
                   2924:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2925:     if ($type eq 'course') {
                   2926: 	$res='course';
                   2927:     } elsif ($type eq 'map') {
1.588     albertel 2928: 	$res=&symbread($map);
                   2929:     } else {
                   2930: 	$res=$symb;
                   2931:     }
                   2932:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2933:     return $times{"$courseid\0$res"};
1.504     albertel 2934: }
                   2935: 
                   2936: sub set_first_access {
                   2937:     my ($type)=@_;
1.790     albertel 2938:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2939:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2940:     if ($type eq 'course') {
                   2941: 	$res='course';
                   2942:     } elsif ($type eq 'map') {
1.588     albertel 2943: 	$res=&symbread($map);
                   2944:     } else {
                   2945: 	$res=$symb;
                   2946:     }
                   2947:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2948:     if (!$firstaccess) {
1.588     albertel 2949: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2950:     }
                   2951:     return 'already_set';
1.504     albertel 2952: }
                   2953: 
1.149     www      2954: sub checkout {
                   2955:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2956:     my $now=time;
                   2957:     my $lonhost=$perlvar{'lonHostID'};
                   2958:     my $infostr=&escape(
1.234     www      2959:                  'CHECKOUTTOKEN&'.
1.149     www      2960:                  $tuname.'&'.
                   2961:                  $tudom.'&'.
                   2962:                  $tcrsid.'&'.
                   2963:                  $symb.'&'.
                   2964: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2965:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2966:     if ($token=~/^error\:/) { 
1.672     albertel 2967:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2968:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2969:                  "</font>");
                   2970:         return ''; 
                   2971:     }
                   2972: 
1.149     www      2973:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2974:     $token=~tr/a-z/A-Z/;
                   2975: 
1.153     www      2976:     my %infohash=('resource.0.outtoken' => $token,
                   2977:                   'resource.0.checkouttime' => $now,
                   2978:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2979: 
                   2980:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2981:        return '';
1.151     www      2982:     } else {
1.672     albertel 2983:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2984:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2985:                  "</font>");
1.149     www      2986:     }    
                   2987: 
                   2988:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2989:                          &escape('Checkout '.$infostr.' - '.
                   2990:                                                  $token)) ne 'ok') {
                   2991: 	return '';
1.151     www      2992:     } else {
1.672     albertel 2993:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2994:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2995:                  "</font>");
1.149     www      2996:     }
1.151     www      2997:     return $token;
1.149     www      2998: }
                   2999: 
                   3000: # ------------------------------------------------------------ Check in an item
                   3001: 
                   3002: sub checkin {
                   3003:     my $token=shift;
1.150     www      3004:     my $now=time;
                   3005:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3006:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3007:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3008:     $dtoken=~s/\W/\_/g;
1.234     www      3009:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3010:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3011: 
1.154     www      3012:     unless (($tuname) && ($tudom)) {
                   3013:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3014:         return '';
                   3015:     }
                   3016:     
                   3017:     unless (&allowed('mgr',$tcrsid)) {
                   3018:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3019:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3020:         return '';
                   3021:     }
                   3022: 
1.153     www      3023:     my %infohash=('resource.0.intoken' => $token,
                   3024:                   'resource.0.checkintime' => $now,
                   3025:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3026: 
                   3027:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3028:        return '';
                   3029:     }    
                   3030: 
                   3031:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3032:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3033: 	return '';
                   3034:     }
                   3035: 
                   3036:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3037: }
                   3038: 
                   3039: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3040: 
                   3041: sub expirespread {
                   3042:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3043:     my $cid=$env{'request.course.id'}; 
1.110     www      3044:     if ($cid) {
                   3045:        my $now=time;
                   3046:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3047:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3048:                             $env{'course.'.$cid.'.num'}.
1.110     www      3049: 	        	    ':nohist_expirationdates:'.
                   3050:                             &escape($key).'='.$now,
1.620     albertel 3051:                             $env{'course.'.$cid.'.home'})
1.110     www      3052:     }
                   3053:     return 'ok';
1.14      www      3054: }
                   3055: 
1.109     www      3056: # ----------------------------------------------------- Devalidate Spreadsheets
                   3057: 
                   3058: sub devalidate {
1.325     www      3059:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3060:     my $cid=$env{'request.course.id'}; 
1.109     www      3061:     if ($cid) {
1.391     matthew  3062:         # delete the stored spreadsheets for
                   3063:         # - the student level sheet of this user in course's homespace
                   3064:         # - the assessment level sheet for this resource 
                   3065:         #   for this user in user's homespace
1.553     albertel 3066: 	# - current conditional state info
1.325     www      3067: 	my $key=$uname.':'.$udom.':';
1.109     www      3068:         my $status=
1.299     matthew  3069: 	    &del('nohist_calculatedsheets',
1.391     matthew  3070: 		 [$key.'studentcalc:'],
1.620     albertel 3071: 		 $env{'course.'.$cid.'.domain'},
                   3072: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3073: 		.' '.
                   3074: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3075: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3076:         unless ($status eq 'ok ok') {
                   3077:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3078:                     $uname.' at '.$udom.' for '.
1.109     www      3079: 		    $symb.': '.$status);
1.133     albertel 3080:         }
1.553     albertel 3081: 	&delenv('user.state.'.$cid);
1.109     www      3082:     }
                   3083: }
                   3084: 
1.265     albertel 3085: sub get_scalar {
                   3086:     my ($string,$end) = @_;
                   3087:     my $value;
                   3088:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3089: 	$value = $1;
                   3090:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3091: 	$value = $1;
                   3092:     }
                   3093:     return &unescape($value);
                   3094: }
                   3095: 
                   3096: sub array2str {
                   3097:   my (@array) = @_;
                   3098:   my $result=&arrayref2str(\@array);
                   3099:   $result=~s/^__ARRAY_REF__//;
                   3100:   $result=~s/__END_ARRAY_REF__$//;
                   3101:   return $result;
                   3102: }
                   3103: 
1.204     albertel 3104: sub arrayref2str {
                   3105:   my ($arrayref) = @_;
1.265     albertel 3106:   my $result='__ARRAY_REF__';
1.204     albertel 3107:   foreach my $elem (@$arrayref) {
1.265     albertel 3108:     if(ref($elem) eq 'ARRAY') {
                   3109:       $result.=&arrayref2str($elem).'&';
                   3110:     } elsif(ref($elem) eq 'HASH') {
                   3111:       $result.=&hashref2str($elem).'&';
                   3112:     } elsif(ref($elem)) {
                   3113:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3114:     } else {
                   3115:       $result.=&escape($elem).'&';
                   3116:     }
                   3117:   }
                   3118:   $result=~s/\&$//;
1.265     albertel 3119:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3120:   return $result;
                   3121: }
                   3122: 
1.168     albertel 3123: sub hash2str {
1.204     albertel 3124:   my (%hash) = @_;
                   3125:   my $result=&hashref2str(\%hash);
1.265     albertel 3126:   $result=~s/^__HASH_REF__//;
                   3127:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3128:   return $result;
                   3129: }
                   3130: 
                   3131: sub hashref2str {
                   3132:   my ($hashref)=@_;
1.265     albertel 3133:   my $result='__HASH_REF__';
1.800     albertel 3134:   foreach my $key (sort(keys(%$hashref))) {
                   3135:     if (ref($key) eq 'ARRAY') {
                   3136:       $result.=&arrayref2str($key).'=';
                   3137:     } elsif (ref($key) eq 'HASH') {
                   3138:       $result.=&hashref2str($key).'=';
                   3139:     } elsif (ref($key)) {
1.265     albertel 3140:       $result.='=';
1.800     albertel 3141:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3142:     } else {
1.800     albertel 3143: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3144:     }
                   3145: 
1.800     albertel 3146:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3147:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3148:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3149:       $result.=&hashref2str($hashref->{$key}).'&';
                   3150:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3151:        $result.='&';
1.800     albertel 3152:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3153:     } else {
1.800     albertel 3154:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3155:     }
                   3156:   }
1.168     albertel 3157:   $result=~s/\&$//;
1.265     albertel 3158:   $result .= '__END_HASH_REF__';
1.168     albertel 3159:   return $result;
                   3160: }
                   3161: 
                   3162: sub str2hash {
1.265     albertel 3163:     my ($string)=@_;
                   3164:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3165:     return %$hash;
                   3166: }
                   3167: 
                   3168: sub str2hashref {
1.168     albertel 3169:   my ($string) = @_;
1.265     albertel 3170: 
                   3171:   my %hash;
                   3172: 
                   3173:   if($string !~ /^__HASH_REF__/) {
                   3174:       if (! ($string eq '' || !defined($string))) {
                   3175: 	  $hash{'error'}='Not hash reference';
                   3176:       }
                   3177:       return (\%hash, $string);
                   3178:   }
                   3179: 
                   3180:   $string =~ s/^__HASH_REF__//;
                   3181: 
                   3182:   while($string !~ /^__END_HASH_REF__/) {
                   3183:       #key
                   3184:       my $key='';
                   3185:       if($string =~ /^__HASH_REF__/) {
                   3186:           ($key, $string)=&str2hashref($string);
                   3187:           if(defined($key->{'error'})) {
                   3188:               $hash{'error'}='Bad data';
                   3189:               return (\%hash, $string);
                   3190:           }
                   3191:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3192:           ($key, $string)=&str2arrayref($string);
                   3193:           if($key->[0] eq 'Array reference error') {
                   3194:               $hash{'error'}='Bad data';
                   3195:               return (\%hash, $string);
                   3196:           }
                   3197:       } else {
                   3198:           $string =~ s/^(.*?)=//;
1.267     albertel 3199: 	  $key=&unescape($1);
1.265     albertel 3200:       }
                   3201:       $string =~ s/^=//;
                   3202: 
                   3203:       #value
                   3204:       my $value='';
                   3205:       if($string =~ /^__HASH_REF__/) {
                   3206:           ($value, $string)=&str2hashref($string);
                   3207:           if(defined($value->{'error'})) {
                   3208:               $hash{'error'}='Bad data';
                   3209:               return (\%hash, $string);
                   3210:           }
                   3211:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3212:           ($value, $string)=&str2arrayref($string);
                   3213:           if($value->[0] eq 'Array reference error') {
                   3214:               $hash{'error'}='Bad data';
                   3215:               return (\%hash, $string);
                   3216:           }
                   3217:       } else {
                   3218: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3219:       }
                   3220:       $string =~ s/^&//;
                   3221: 
                   3222:       $hash{$key}=$value;
1.204     albertel 3223:   }
1.265     albertel 3224: 
                   3225:   $string =~ s/^__END_HASH_REF__//;
                   3226: 
                   3227:   return (\%hash, $string);
1.204     albertel 3228: }
                   3229: 
                   3230: sub str2array {
1.265     albertel 3231:     my ($string)=@_;
                   3232:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3233:     return @$array;
                   3234: }
                   3235: 
                   3236: sub str2arrayref {
1.204     albertel 3237:   my ($string) = @_;
1.265     albertel 3238:   my @array;
                   3239: 
                   3240:   if($string !~ /^__ARRAY_REF__/) {
                   3241:       if (! ($string eq '' || !defined($string))) {
                   3242: 	  $array[0]='Array reference error';
                   3243:       }
                   3244:       return (\@array, $string);
                   3245:   }
                   3246: 
                   3247:   $string =~ s/^__ARRAY_REF__//;
                   3248: 
                   3249:   while($string !~ /^__END_ARRAY_REF__/) {
                   3250:       my $value='';
                   3251:       if($string =~ /^__HASH_REF__/) {
                   3252:           ($value, $string)=&str2hashref($string);
                   3253:           if(defined($value->{'error'})) {
                   3254:               $array[0] ='Array reference error';
                   3255:               return (\@array, $string);
                   3256:           }
                   3257:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3258:           ($value, $string)=&str2arrayref($string);
                   3259:           if($value->[0] eq 'Array reference error') {
                   3260:               $array[0] ='Array reference error';
                   3261:               return (\@array, $string);
                   3262:           }
                   3263:       } else {
                   3264: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3265:       }
                   3266:       $string =~ s/^&//;
                   3267: 
                   3268:       push(@array, $value);
1.191     harris41 3269:   }
1.265     albertel 3270: 
                   3271:   $string =~ s/^__END_ARRAY_REF__//;
                   3272: 
                   3273:   return (\@array, $string);
1.168     albertel 3274: }
                   3275: 
1.167     albertel 3276: # -------------------------------------------------------------------Temp Store
                   3277: 
1.168     albertel 3278: sub tmpreset {
                   3279:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3280:   if (!$symb) {
                   3281:     $symb=&symbread();
1.620     albertel 3282:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3283:   }
                   3284:   $symb=escape($symb);
                   3285: 
1.620     albertel 3286:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3287:   $namespace=~s/\//\_/g;
                   3288:   $namespace=~s/\W//g;
                   3289: 
1.620     albertel 3290:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3291:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3292:   if ($domain eq 'public' && $stuname eq 'public') {
                   3293:       $stuname=$ENV{'REMOTE_ADDR'};
                   3294:   }
1.168     albertel 3295:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3296:   my %hash;
                   3297:   if (tie(%hash,'GDBM_File',
                   3298: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3299: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3300:     foreach my $key (keys %hash) {
1.180     albertel 3301:       if ($key=~ /:$symb/) {
1.168     albertel 3302: 	delete($hash{$key});
                   3303:       }
                   3304:     }
                   3305:   }
                   3306: }
                   3307: 
1.167     albertel 3308: sub tmpstore {
1.168     albertel 3309:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3310: 
                   3311:   if (!$symb) {
                   3312:     $symb=&symbread();
1.620     albertel 3313:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3314:   }
                   3315:   $symb=escape($symb);
                   3316: 
                   3317:   if (!$namespace) {
                   3318:     # I don't think we would ever want to store this for a course.
                   3319:     # it seems this will only be used if we don't have a course.
1.620     albertel 3320:     #$namespace=$env{'request.course.id'};
1.168     albertel 3321:     #if (!$namespace) {
1.620     albertel 3322:       $namespace=$env{'request.state'};
1.168     albertel 3323:     #}
                   3324:   }
                   3325:   $namespace=~s/\//\_/g;
                   3326:   $namespace=~s/\W//g;
1.620     albertel 3327:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3328:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3329:   if ($domain eq 'public' && $stuname eq 'public') {
                   3330:       $stuname=$ENV{'REMOTE_ADDR'};
                   3331:   }
1.168     albertel 3332:   my $now=time;
                   3333:   my %hash;
                   3334:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3335:   if (tie(%hash,'GDBM_File',
                   3336: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3337: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3338:     $hash{"version:$symb"}++;
                   3339:     my $version=$hash{"version:$symb"};
                   3340:     my $allkeys=''; 
                   3341:     foreach my $key (keys(%$storehash)) {
                   3342:       $allkeys.=$key.':';
1.591     albertel 3343:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3344:     }
                   3345:     $hash{"$version:$symb:timestamp"}=$now;
                   3346:     $allkeys.='timestamp';
                   3347:     $hash{"$version:keys:$symb"}=$allkeys;
                   3348:     if (untie(%hash)) {
                   3349:       return 'ok';
                   3350:     } else {
                   3351:       return "error:$!";
                   3352:     }
                   3353:   } else {
                   3354:     return "error:$!";
                   3355:   }
                   3356: }
1.167     albertel 3357: 
1.168     albertel 3358: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3359: 
1.168     albertel 3360: sub tmprestore {
                   3361:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3362: 
1.168     albertel 3363:   if (!$symb) {
                   3364:     $symb=&symbread();
1.620     albertel 3365:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3366:   }
                   3367:   $symb=escape($symb);
                   3368: 
1.620     albertel 3369:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3370: 
1.620     albertel 3371:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3372:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3373:   if ($domain eq 'public' && $stuname eq 'public') {
                   3374:       $stuname=$ENV{'REMOTE_ADDR'};
                   3375:   }
1.168     albertel 3376:   my %returnhash;
                   3377:   $namespace=~s/\//\_/g;
                   3378:   $namespace=~s/\W//g;
                   3379:   my %hash;
                   3380:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3381:   if (tie(%hash,'GDBM_File',
                   3382: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3383: 	  &GDBM_READER(),0640)) {
1.168     albertel 3384:     my $version=$hash{"version:$symb"};
                   3385:     $returnhash{'version'}=$version;
                   3386:     my $scope;
                   3387:     for ($scope=1;$scope<=$version;$scope++) {
                   3388:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3389:       my @keys=split(/:/,$vkeys);
                   3390:       my $key;
                   3391:       $returnhash{"$scope:keys"}=$vkeys;
                   3392:       foreach $key (@keys) {
1.591     albertel 3393: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3394: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3395:       }
                   3396:     }
1.168     albertel 3397:     if (!(untie(%hash))) {
                   3398:       return "error:$!";
                   3399:     }
                   3400:   } else {
                   3401:     return "error:$!";
                   3402:   }
                   3403:   return %returnhash;
1.167     albertel 3404: }
                   3405: 
1.9       www      3406: # ----------------------------------------------------------------------- Store
                   3407: 
                   3408: sub store {
1.124     www      3409:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3410:     my $home='';
                   3411: 
1.168     albertel 3412:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3413: 
1.213     www      3414:     $symb=&symbclean($symb);
1.122     albertel 3415:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3416: 
1.620     albertel 3417:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3418:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3419: 
                   3420:     &devalidate($symb,$stuname,$domain);
1.109     www      3421: 
                   3422:     $symb=escape($symb);
1.187     www      3423:     if (!$namespace) { 
1.620     albertel 3424:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3425:           return ''; 
                   3426:        } 
                   3427:     }
1.620     albertel 3428:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3429: 
                   3430:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3431:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3432: 
1.12      www      3433:     my $namevalue='';
1.800     albertel 3434:     foreach my $key (keys(%$storehash)) {
                   3435:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3436:     }
1.12      www      3437:     $namevalue=~s/\&$//;
1.187     www      3438:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3439:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3440: }
                   3441: 
1.47      www      3442: # -------------------------------------------------------------- Critical Store
                   3443: 
                   3444: sub cstore {
1.124     www      3445:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3446:     my $home='';
                   3447: 
1.168     albertel 3448:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3449: 
1.213     www      3450:     $symb=&symbclean($symb);
1.122     albertel 3451:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3452: 
1.620     albertel 3453:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3454:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3455: 
                   3456:     &devalidate($symb,$stuname,$domain);
1.109     www      3457: 
                   3458:     $symb=escape($symb);
1.187     www      3459:     if (!$namespace) { 
1.620     albertel 3460:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3461:           return ''; 
                   3462:        } 
                   3463:     }
1.620     albertel 3464:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3465: 
                   3466:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3467:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3468: 
1.47      www      3469:     my $namevalue='';
1.800     albertel 3470:     foreach my $key (keys(%$storehash)) {
                   3471:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3472:     }
1.47      www      3473:     $namevalue=~s/\&$//;
1.187     www      3474:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3475:     return critical
                   3476:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3477: }
                   3478: 
1.9       www      3479: # --------------------------------------------------------------------- Restore
                   3480: 
                   3481: sub restore {
1.124     www      3482:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3483:     my $home='';
                   3484: 
1.168     albertel 3485:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3486: 
1.122     albertel 3487:     if (!$symb) {
                   3488:       unless ($symb=escape(&symbread())) { return ''; }
                   3489:     } else {
1.213     www      3490:       $symb=&escape(&symbclean($symb));
1.122     albertel 3491:     }
1.188     www      3492:     if (!$namespace) { 
1.620     albertel 3493:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3494:           return ''; 
                   3495:        } 
                   3496:     }
1.620     albertel 3497:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3498:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3499:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3500:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3501: 
1.12      www      3502:     my %returnhash=();
1.800     albertel 3503:     foreach my $line (split(/\&/,$answer)) {
                   3504: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3505:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3506:     }
1.75      www      3507:     my $version;
                   3508:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3509:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3510:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3511:        }
1.75      www      3512:     }
1.13      www      3513:     return %returnhash;
1.34      www      3514: }
                   3515: 
                   3516: # ---------------------------------------------------------- Course Description
                   3517: 
                   3518: sub coursedescription {
1.731     albertel 3519:     my ($courseid,$args)=@_;
1.34      www      3520:     $courseid=~s/^\///;
1.49      www      3521:     $courseid=~s/\_/\//g;
1.34      www      3522:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3523:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3524:     my $normalid=$cdomain.'_'.$cnum;
                   3525:     # need to always cache even if we get errors otherwise we keep 
                   3526:     # trying and trying and trying to get the course description.
                   3527:     my %envhash=();
                   3528:     my %returnhash=();
1.731     albertel 3529:     
                   3530:     my $expiretime=600;
                   3531:     if ($env{'request.course.id'} eq $normalid) {
                   3532: 	$expiretime=120;
                   3533:     }
                   3534: 
                   3535:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3536:     if (!$args->{'freshen_cache'}
                   3537: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3538: 	foreach my $key (keys(%env)) {
                   3539: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3540: 	    my ($setting) = $1;
                   3541: 	    $returnhash{$setting} = $env{$key};
                   3542: 	}
                   3543: 	return %returnhash;
                   3544:     }
                   3545: 
                   3546:     # get the data agin
                   3547:     if (!$args->{'one_time'}) {
                   3548: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3549:     }
1.811     albertel 3550: 
1.34      www      3551:     if ($chome ne 'no_host') {
1.302     albertel 3552:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3553:        if (!exists($returnhash{'con_lost'})) {
                   3554:            $returnhash{'home'}= $chome;
                   3555: 	   $returnhash{'domain'} = $cdomain;
                   3556: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3557:            if (!defined($returnhash{'type'})) {
                   3558:                $returnhash{'type'} = 'Course';
                   3559:            }
1.130     albertel 3560:            while (my ($name,$value) = each %returnhash) {
1.53      www      3561:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3562:            }
1.270     www      3563:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3564:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3565: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3566:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3567:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3568:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3569:        }
                   3570:     }
1.731     albertel 3571:     if (!$args->{'one_time'}) {
1.949     raeburn  3572: 	&appenv(\%envhash);
1.731     albertel 3573:     }
1.302     albertel 3574:     return %returnhash;
1.461     www      3575: }
                   3576: 
                   3577: # -------------------------------------------------See if a user is privileged
                   3578: 
                   3579: sub privileged {
                   3580:     my ($username,$domain)=@_;
                   3581:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3582: 			&homeserver($username,$domain));
                   3583:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3584:     my $now=time;
                   3585:     if ($rolesdump ne '') {
1.800     albertel 3586:         foreach my $entry (split(/&/,$rolesdump)) {
                   3587: 	    if ($entry!~/^rolesdef_/) {
                   3588: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3589: 		$area=~s/\_\w\w$//;
                   3590: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3591: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3592: 		    my $active=1;
                   3593: 		    if ($tend) {
                   3594: 			if ($tend<$now) { $active=0; }
                   3595: 		    }
                   3596: 		    if ($tstart) {
                   3597: 			if ($tstart>$now) { $active=0; }
                   3598: 		    }
                   3599: 		    if ($active) { return 1; }
                   3600: 		}
                   3601: 	    }
                   3602: 	}
                   3603:     }
                   3604:     return 0;
1.9       www      3605: }
1.1       albertel 3606: 
1.103     harris41 3607: # -------------------------------------------------------- Get user privileges
1.11      www      3608: 
                   3609: sub rolesinit {
                   3610:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3611:     my %userroles;
1.11      www      3612:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3613:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3614:     my %allroles=();
1.678     raeburn  3615:     my %allgroups=();   
1.11      www      3616:     my $now=time;
1.966     raeburn  3617:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3618:     my $group_privs;
1.11      www      3619: 
                   3620:     if ($rolesdump ne '') {
1.800     albertel 3621:         foreach my $entry (split(/&/,$rolesdump)) {
                   3622: 	  if ($entry!~/^rolesdef_/) {
                   3623:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3624: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3625:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3626: 	    if ($role=~/^cr/) { 
1.807     albertel 3627: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3628: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3629: 		    ($tend,$tstart)=split('_',$trest);
                   3630: 		} else {
                   3631: 		    $trole=$role;
                   3632: 		}
1.678     raeburn  3633:             } elsif ($role =~ m|^gr/|) {
                   3634:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3635:                 ($trole,$group_privs) = split(/\//,$trole);
                   3636:                 $group_privs = &unescape($group_privs);
1.587     albertel 3637: 	    } else {
                   3638: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3639: 	    }
1.743     albertel 3640: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3641: 					 $username);
                   3642: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3643:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3644:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3645:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3646: 		my $spec=$trole.'.'.$area;
                   3647: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3648: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3649:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3650:                 } elsif ($trole eq 'gr') {
                   3651:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3652: 		} else {
1.567     raeburn  3653:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3654: 		}
1.12      www      3655:             }
1.662     raeburn  3656:           }
1.191     harris41 3657:         }
1.743     albertel 3658:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3659:         $userroles{'user.adv'}    = $adv;
                   3660: 	$userroles{'user.author'} = $author;
1.620     albertel 3661:         $env{'user.adv'}=$adv;
1.11      www      3662:     }
1.743     albertel 3663:     return \%userroles;  
1.11      www      3664: }
                   3665: 
1.567     raeburn  3666: sub set_arearole {
                   3667:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3668: # log the associated role with the area
                   3669:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3670:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3671: }
                   3672: 
                   3673: sub custom_roleprivs {
                   3674:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3675:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3676:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3677:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3678:         my ($rdummy,$roledef)=
                   3679:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3680:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3681:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3682:             if (defined($syspriv)) {
                   3683:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3684:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3685:             }
                   3686:             if ($tdomain ne '') {
                   3687:                 if (defined($dompriv)) {
                   3688:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3689:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3690:                 }
                   3691:                 if (($trest ne '') && (defined($coursepriv))) {
                   3692:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3693:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3694:                 }
                   3695:             }
                   3696:         }
                   3697:     }
                   3698: }
                   3699: 
1.678     raeburn  3700: sub group_roleprivs {
                   3701:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3702:     my $access = 1;
                   3703:     my $now = time;
                   3704:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3705:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3706:     if ($access) {
1.811     albertel 3707:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3708:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3709:     }
                   3710: }
1.567     raeburn  3711: 
                   3712: sub standard_roleprivs {
                   3713:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3714:     if (defined($pr{$trole.':s'})) {
                   3715:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3716:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3717:     }
                   3718:     if ($tdomain ne '') {
                   3719:         if (defined($pr{$trole.':d'})) {
                   3720:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3721:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3722:         }
                   3723:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3724:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3725:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3726:         }
                   3727:     }
                   3728: }
                   3729: 
                   3730: sub set_userprivs {
1.678     raeburn  3731:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3732:     my $author=0;
                   3733:     my $adv=0;
1.678     raeburn  3734:     my %grouproles = ();
                   3735:     if (keys(%{$allgroups}) > 0) {
                   3736:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3737:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3738:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3739:                 $trole = $1;
                   3740:                 $area = $2;
1.681     raeburn  3741:                 $sec = $3;
                   3742:                 $extendedarea = $area.$sec;
                   3743:                 if (exists($$allgroups{$area})) {
                   3744:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3745:                         my $spec = $trole.'.'.$extendedarea;
                   3746:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3747:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3748:                     }
                   3749:                 }
                   3750:             }
                   3751:         }
                   3752:     }
1.800     albertel 3753:     foreach my $group (keys(%grouproles)) {
                   3754:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3755:     }
1.800     albertel 3756:     foreach my $role (keys(%{$allroles})) {
                   3757:         my %thesepriv;
1.941     raeburn  3758:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3759:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3760:             if ($item ne '') {
                   3761:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3762:                 if ($restrictions eq '') {
                   3763:                     $thesepriv{$privilege}='F';
                   3764:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3765:                     $thesepriv{$privilege}.=$restrictions;
                   3766:                 }
                   3767:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3768:             }
                   3769:         }
                   3770:         my $thesestr='';
1.800     albertel 3771:         foreach my $priv (keys(%thesepriv)) {
                   3772: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3773: 	}
                   3774:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3775:     }
                   3776:     return ($author,$adv);
                   3777: }
                   3778: 
1.12      www      3779: # --------------------------------------------------------------- get interface
                   3780: 
                   3781: sub get {
1.131     albertel 3782:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3783:    my $items='';
1.800     albertel 3784:    foreach my $item (@$storearr) {
                   3785:        $items.=&escape($item).'&';
1.191     harris41 3786:    }
1.12      www      3787:    $items=~s/\&$//;
1.620     albertel 3788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3789:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3790:    my $uhome=&homeserver($uname,$udomain);
                   3791: 
1.133     albertel 3792:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3793:    my @pairs=split(/\&/,$rep);
1.273     albertel 3794:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3795:      return @pairs;
                   3796:    }
1.15      www      3797:    my %returnhash=();
1.42      www      3798:    my $i=0;
1.800     albertel 3799:    foreach my $item (@$storearr) {
                   3800:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3801:       $i++;
1.191     harris41 3802:    }
1.15      www      3803:    return %returnhash;
1.27      www      3804: }
                   3805: 
                   3806: # --------------------------------------------------------------- del interface
                   3807: 
                   3808: sub del {
1.133     albertel 3809:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3810:    my $items='';
1.800     albertel 3811:    foreach my $item (@$storearr) {
                   3812:        $items.=&escape($item).'&';
1.191     harris41 3813:    }
1.27      www      3814:    $items=~s/\&$//;
1.620     albertel 3815:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3816:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3817:    my $uhome=&homeserver($uname,$udomain);
                   3818: 
                   3819:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3820: }
                   3821: 
                   3822: # -------------------------------------------------------------- dump interface
                   3823: 
                   3824: sub dump {
1.755     albertel 3825:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3826:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3827:     if (!$uname) { $uname=$env{'user.name'}; }
                   3828:     my $uhome=&homeserver($uname,$udomain);
                   3829:     if ($regexp) {
                   3830: 	$regexp=&escape($regexp);
                   3831:     } else {
                   3832: 	$regexp='.';
                   3833:     }
                   3834:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3835:     my @pairs=split(/\&/,$rep);
                   3836:     my %returnhash=();
                   3837:     foreach my $item (@pairs) {
                   3838: 	my ($key,$value)=split(/=/,$item,2);
                   3839: 	$key = &unescape($key);
                   3840: 	next if ($key =~ /^error: 2 /);
                   3841: 	$returnhash{$key}=&thaw_unescape($value);
                   3842:     }
                   3843:     return %returnhash;
1.407     www      3844: }
                   3845: 
1.717     albertel 3846: # --------------------------------------------------------- dumpstore interface
                   3847: 
                   3848: sub dumpstore {
                   3849:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3851:    if (!$uname) { $uname=$env{'user.name'}; }
                   3852:    my $uhome=&homeserver($uname,$udomain);
                   3853:    if ($regexp) {
                   3854:        $regexp=&escape($regexp);
                   3855:    } else {
                   3856:        $regexp='.';
                   3857:    }
                   3858:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3859:    my @pairs=split(/\&/,$rep);
                   3860:    my %returnhash=();
                   3861:    foreach my $item (@pairs) {
                   3862:        my ($key,$value)=split(/=/,$item,2);
                   3863:        next if ($key =~ /^error: 2 /);
                   3864:        $returnhash{$key}=&thaw_unescape($value);
                   3865:    }
                   3866:    return %returnhash;
1.717     albertel 3867: }
                   3868: 
1.407     www      3869: # -------------------------------------------------------------- keys interface
                   3870: 
                   3871: sub getkeys {
                   3872:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3873:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3874:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3875:    my $uhome=&homeserver($uname,$udomain);
                   3876:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3877:    my @keyarray=();
1.800     albertel 3878:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3879:       next if ($key =~ /^error: 2 /);
1.800     albertel 3880:       push(@keyarray,&unescape($key));
1.407     www      3881:    }
                   3882:    return @keyarray;
1.318     matthew  3883: }
                   3884: 
1.319     matthew  3885: # --------------------------------------------------------------- currentdump
                   3886: sub currentdump {
1.328     matthew  3887:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3888:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3889:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3890:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3891:    my $uhome = &homeserver($sname,$sdom);
                   3892:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3893:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3894:    #
1.318     matthew  3895:    my %returnhash=();
1.319     matthew  3896:    #
                   3897:    if ($rep eq "unknown_cmd") { 
                   3898:        # an old lond will not know currentdump
                   3899:        # Do a dump and make it look like a currentdump
1.822     albertel 3900:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3901:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3902:        my %hash = @tmp;
                   3903:        @tmp=();
1.424     matthew  3904:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3905:    } else {
                   3906:        my @pairs=split(/\&/,$rep);
1.800     albertel 3907:        foreach my $pair (@pairs) {
                   3908:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3909:            my ($symb,$param) = split(/:/,$key);
                   3910:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3911:                                                         &thaw_unescape($value);
1.319     matthew  3912:        }
1.191     harris41 3913:    }
1.12      www      3914:    return %returnhash;
1.424     matthew  3915: }
                   3916: 
                   3917: sub convert_dump_to_currentdump{
                   3918:     my %hash = %{shift()};
                   3919:     my %returnhash;
                   3920:     # Code ripped from lond, essentially.  The only difference
                   3921:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3922:     # we might run in to problems with parameter names =~ /^v\./
                   3923:     while (my ($key,$value) = each(%hash)) {
                   3924:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3925: 	$symb  = &unescape($symb);
                   3926: 	$param = &unescape($param);
1.424     matthew  3927:         next if ($v eq 'version' || $symb eq 'keys');
                   3928:         next if (exists($returnhash{$symb}) &&
                   3929:                  exists($returnhash{$symb}->{$param}) &&
                   3930:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3931:         $returnhash{$symb}->{$param}=$value;
                   3932:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3933:     }
                   3934:     #
                   3935:     # Remove all of the keys in the hashes which keep track of
                   3936:     # the version of the parameter.
                   3937:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3938:         # use a foreach because we are going to delete from the hash.
                   3939:         foreach my $key (keys(%$param_hash)) {
                   3940:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3941:         }
                   3942:     }
                   3943:     return \%returnhash;
1.12      www      3944: }
                   3945: 
1.627     albertel 3946: # ------------------------------------------------------ critical inc interface
                   3947: 
                   3948: sub cinc {
                   3949:     return &inc(@_,'critical');
                   3950: }
                   3951: 
1.449     matthew  3952: # --------------------------------------------------------------- inc interface
                   3953: 
                   3954: sub inc {
1.627     albertel 3955:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3956:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3957:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3958:     my $uhome=&homeserver($uname,$udomain);
                   3959:     my $items='';
                   3960:     if (! ref($store)) {
                   3961:         # got a single value, so use that instead
                   3962:         $items = &escape($store).'=&';
                   3963:     } elsif (ref($store) eq 'SCALAR') {
                   3964:         $items = &escape($$store).'=&';        
                   3965:     } elsif (ref($store) eq 'ARRAY') {
                   3966:         $items = join('=&',map {&escape($_);} @{$store});
                   3967:     } elsif (ref($store) eq 'HASH') {
                   3968:         while (my($key,$value) = each(%{$store})) {
                   3969:             $items.= &escape($key).'='.&escape($value).'&';
                   3970:         }
                   3971:     }
                   3972:     $items=~s/\&$//;
1.627     albertel 3973:     if ($critical) {
                   3974: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3975:     } else {
                   3976: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3977:     }
1.449     matthew  3978: }
                   3979: 
1.12      www      3980: # --------------------------------------------------------------- put interface
                   3981: 
                   3982: sub put {
1.134     albertel 3983:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3984:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3985:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3986:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3987:    my $items='';
1.800     albertel 3988:    foreach my $item (keys(%$storehash)) {
                   3989:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3990:    }
1.12      www      3991:    $items=~s/\&$//;
1.134     albertel 3992:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3993: }
                   3994: 
1.631     albertel 3995: # ------------------------------------------------------------ newput interface
                   3996: 
                   3997: sub newput {
                   3998:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3999:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4000:    if (!$uname) { $uname=$env{'user.name'}; }
                   4001:    my $uhome=&homeserver($uname,$udomain);
                   4002:    my $items='';
                   4003:    foreach my $key (keys(%$storehash)) {
                   4004:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4005:    }
                   4006:    $items=~s/\&$//;
                   4007:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4008: }
                   4009: 
                   4010: # ---------------------------------------------------------  putstore interface
                   4011: 
1.524     raeburn  4012: sub putstore {
1.715     albertel 4013:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4014:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4015:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4016:    my $uhome=&homeserver($uname,$udomain);
                   4017:    my $items='';
1.715     albertel 4018:    foreach my $key (keys(%$storehash)) {
                   4019:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4020:    }
1.715     albertel 4021:    $items=~s/\&$//;
1.716     albertel 4022:    my $esc_symb=&escape($symb);
                   4023:    my $esc_v=&escape($version);
1.715     albertel 4024:    my $reply =
1.716     albertel 4025:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4026: 	      $uhome);
                   4027:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4028:        # gfall back to way things use to be done
1.715     albertel 4029:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4030: 			    $uname);
1.524     raeburn  4031:    }
1.715     albertel 4032:    return $reply;
                   4033: }
                   4034: 
                   4035: sub old_putstore {
1.716     albertel 4036:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4037:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4038:     if (!$uname) { $uname=$env{'user.name'}; }
                   4039:     my $uhome=&homeserver($uname,$udomain);
                   4040:     my %newstorehash;
1.800     albertel 4041:     foreach my $item (keys(%$storehash)) {
                   4042: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4043: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4044:     }
                   4045:     my $items='';
                   4046:     my %allitems = ();
1.800     albertel 4047:     foreach my $item (keys(%newstorehash)) {
                   4048: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4049: 	    my $key = $1.':keys:'.$2;
                   4050: 	    $allitems{$key} .= $3.':';
                   4051: 	}
1.800     albertel 4052: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4053:     }
1.800     albertel 4054:     foreach my $item (keys(%allitems)) {
                   4055: 	$allitems{$item} =~ s/\:$//;
                   4056: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4057:     }
                   4058:     $items=~s/\&$//;
                   4059:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4060: }
                   4061: 
1.47      www      4062: # ------------------------------------------------------ critical put interface
                   4063: 
                   4064: sub cput {
1.134     albertel 4065:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4067:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4068:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4069:    my $items='';
1.800     albertel 4070:    foreach my $item (keys(%$storehash)) {
                   4071:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4072:    }
1.47      www      4073:    $items=~s/\&$//;
1.134     albertel 4074:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4075: }
                   4076: 
                   4077: # -------------------------------------------------------------- eget interface
                   4078: 
                   4079: sub eget {
1.133     albertel 4080:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4081:    my $items='';
1.800     albertel 4082:    foreach my $item (@$storearr) {
                   4083:        $items.=&escape($item).'&';
1.191     harris41 4084:    }
1.12      www      4085:    $items=~s/\&$//;
1.620     albertel 4086:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4087:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4088:    my $uhome=&homeserver($uname,$udomain);
                   4089:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4090:    my @pairs=split(/\&/,$rep);
                   4091:    my %returnhash=();
1.42      www      4092:    my $i=0;
1.800     albertel 4093:    foreach my $item (@$storearr) {
                   4094:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4095:       $i++;
1.191     harris41 4096:    }
1.12      www      4097:    return %returnhash;
                   4098: }
                   4099: 
1.667     albertel 4100: # ------------------------------------------------------------ tmpput interface
                   4101: sub tmpput {
1.802     raeburn  4102:     my ($storehash,$server,$context)=@_;
1.667     albertel 4103:     my $items='';
1.800     albertel 4104:     foreach my $item (keys(%$storehash)) {
                   4105: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4106:     }
                   4107:     $items=~s/\&$//;
1.802     raeburn  4108:     if (defined($context)) {
                   4109:         $items .= ':'.&escape($context);
                   4110:     }
1.667     albertel 4111:     return &reply("tmpput:$items",$server);
                   4112: }
                   4113: 
                   4114: # ------------------------------------------------------------ tmpget interface
                   4115: sub tmpget {
1.688     albertel 4116:     my ($token,$server)=@_;
                   4117:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4118:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4119:     my %returnhash;
                   4120:     foreach my $item (split(/\&/,$rep)) {
                   4121: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4122:         next if ($key =~ /^error: 2 /);
1.667     albertel 4123: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4124:     }
                   4125:     return %returnhash;
                   4126: }
                   4127: 
1.688     albertel 4128: # ------------------------------------------------------------ tmpget interface
                   4129: sub tmpdel {
                   4130:     my ($token,$server)=@_;
                   4131:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4132:     return &reply("tmpdel:$token",$server);
                   4133: }
                   4134: 
1.765     albertel 4135: # -------------------------------------------------- portfolio access checking
                   4136: 
                   4137: sub portfolio_access {
1.766     albertel 4138:     my ($requrl) = @_;
1.765     albertel 4139:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4140:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4141:     if ($result) {
                   4142:         my %setters;
                   4143:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4144:             my ($startblock,$endblock) =
                   4145:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4146:             if ($startblock && $endblock) {
                   4147:                 return 'B';
                   4148:             }
                   4149:         } else {
                   4150:             my ($startblock,$endblock) =
                   4151:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4152:             if ($startblock && $endblock) {
                   4153:                 return 'B';
                   4154:             }
                   4155:         }
                   4156:     }
1.765     albertel 4157:     if ($result eq 'ok') {
1.766     albertel 4158:        return 'F';
1.765     albertel 4159:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4160:        return 'A';
1.765     albertel 4161:     }
1.766     albertel 4162:     return '';
1.765     albertel 4163: }
                   4164: 
                   4165: sub get_portfolio_access {
1.767     albertel 4166:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4167: 
                   4168:     if (!ref($access_hash)) {
                   4169: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4170: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4171: 						   $file_name);
                   4172: 	$access_hash = $access_controls{$file_name};
                   4173:     }
                   4174: 
1.765     albertel 4175:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4176:     my $now = time;
                   4177:     if (ref($access_hash) eq 'HASH') {
                   4178:         foreach my $key (keys(%{$access_hash})) {
                   4179:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4180:             if ($start > $now) {
                   4181:                 next;
                   4182:             }
                   4183:             if ($end && $end<$now) {
                   4184:                 next;
                   4185:             }
                   4186:             if ($scope eq 'public') {
                   4187:                 $public = $key;
                   4188:                 last;
                   4189:             } elsif ($scope eq 'guest') {
                   4190:                 $guest = $key;
                   4191:             } elsif ($scope eq 'domains') {
                   4192:                 push(@domains,$key);
                   4193:             } elsif ($scope eq 'users') {
                   4194:                 push(@users,$key);
                   4195:             } elsif ($scope eq 'course') {
                   4196:                 push(@courses,$key);
                   4197:             } elsif ($scope eq 'group') {
                   4198:                 push(@groups,$key);
                   4199:             }
                   4200:         }
                   4201:         if ($public) {
                   4202:             return 'ok';
                   4203:         }
                   4204:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4205:             if ($guest) {
                   4206:                 return $guest;
                   4207:             }
                   4208:         } else {
                   4209:             if (@domains > 0) {
                   4210:                 foreach my $domkey (@domains) {
                   4211:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4212:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4213:                             return 'ok';
                   4214:                         }
                   4215:                     }
                   4216:                 }
                   4217:             }
                   4218:             if (@users > 0) {
                   4219:                 foreach my $userkey (@users) {
1.865     raeburn  4220:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4221:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4222:                             if (ref($item) eq 'HASH') {
                   4223:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4224:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4225:                                     return 'ok';
                   4226:                                 }
                   4227:                             }
                   4228:                         }
                   4229:                     } 
1.765     albertel 4230:                 }
                   4231:             }
                   4232:             my %roleshash;
                   4233:             my @courses_and_groups = @courses;
                   4234:             push(@courses_and_groups,@groups); 
                   4235:             if (@courses_and_groups > 0) {
                   4236:                 my (%allgroups,%allroles); 
                   4237:                 my ($start,$end,$role,$sec,$group);
                   4238:                 foreach my $envkey (%env) {
1.811     albertel 4239:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4240:                         my $cid = $2.'_'.$3; 
                   4241:                         if ($1 eq 'gr') {
                   4242:                             $group = $4;
                   4243:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4244:                         } else {
                   4245:                             if ($4 eq '') {
                   4246:                                 $sec = 'none';
                   4247:                             } else {
                   4248:                                 $sec = $4;
                   4249:                             }
                   4250:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4251:                         }
1.811     albertel 4252:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4253:                         my $cid = $2.'_'.$3;
                   4254:                         if ($4 eq '') {
                   4255:                             $sec = 'none';
                   4256:                         } else {
                   4257:                             $sec = $4;
                   4258:                         }
                   4259:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4260:                     }
                   4261:                 }
                   4262:                 if (keys(%allroles) == 0) {
                   4263:                     return;
                   4264:                 }
                   4265:                 foreach my $key (@courses_and_groups) {
                   4266:                     my %content = %{$$access_hash{$key}};
                   4267:                     my $cnum = $content{'number'};
                   4268:                     my $cdom = $content{'domain'};
                   4269:                     my $cid = $cdom.'_'.$cnum;
                   4270:                     if (!exists($allroles{$cid})) {
                   4271:                         next;
                   4272:                     }    
                   4273:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4274:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4275:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4276:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4277:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4278:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4279:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4280:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4281:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4282:                                         if (grep/^all$/,@sections) {
                   4283:                                             return 'ok';
                   4284:                                         } else {
                   4285:                                             if (grep/^$sec$/,@sections) {
                   4286:                                                 return 'ok';
                   4287:                                             }
                   4288:                                         }
                   4289:                                     }
                   4290:                                 }
                   4291:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4292:                                     if (grep/^none$/,@groups) {
                   4293:                                         return 'ok';
                   4294:                                     }
                   4295:                                 } else {
                   4296:                                     if (grep/^all$/,@groups) {
                   4297:                                         return 'ok';
                   4298:                                     } 
                   4299:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4300:                                         if (grep/^$group$/,@groups) {
                   4301:                                             return 'ok';
                   4302:                                         }
                   4303:                                     }
                   4304:                                 } 
                   4305:                             }
                   4306:                         }
                   4307:                     }
                   4308:                 }
                   4309:             }
                   4310:             if ($guest) {
                   4311:                 return $guest;
                   4312:             }
                   4313:         }
                   4314:     }
                   4315:     return;
                   4316: }
                   4317: 
                   4318: sub course_group_datechecker {
                   4319:     my ($dates,$now,$status) = @_;
                   4320:     my ($start,$end) = split(/\./,$dates);
                   4321:     if (!$start && !$end) {
                   4322:         return 'ok';
                   4323:     }
                   4324:     if (grep/^active$/,@{$status}) {
                   4325:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4326:             return 'ok';
                   4327:         }
                   4328:     }
                   4329:     if (grep/^previous$/,@{$status}) {
                   4330:         if ($end > $now ) {
                   4331:             return 'ok';
                   4332:         }
                   4333:     }
                   4334:     if (grep/^future$/,@{$status}) {
                   4335:         if ($start > $now) {
                   4336:             return 'ok';
                   4337:         }
                   4338:     }
                   4339:     return; 
                   4340: }
                   4341: 
                   4342: sub parse_portfolio_url {
                   4343:     my ($url) = @_;
                   4344: 
                   4345:     my ($type,$udom,$unum,$group,$file_name);
                   4346:     
1.823     albertel 4347:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4348: 	$type = 1;
                   4349:         $udom = $1;
                   4350:         $unum = $2;
                   4351:         $file_name = $3;
1.823     albertel 4352:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4353: 	$type = 2;
                   4354:         $udom = $1;
                   4355:         $unum = $2;
                   4356:         $group = $3;
                   4357:         $file_name = $3.'/'.$4;
                   4358:     }
                   4359:     if (wantarray) {
                   4360: 	return ($type,$udom,$unum,$file_name,$group);
                   4361:     }
                   4362:     return $type;
                   4363: }
                   4364: 
                   4365: sub is_portfolio_url {
                   4366:     my ($url) = @_;
                   4367:     return scalar(&parse_portfolio_url($url));
                   4368: }
                   4369: 
1.798     raeburn  4370: sub is_portfolio_file {
                   4371:     my ($file) = @_;
1.820     raeburn  4372:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4373:         return 1;
                   4374:     }
                   4375:     return;
                   4376: }
                   4377: 
1.976     raeburn  4378: sub usertools_access {
1.976.2.1  raeburn  4379:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4380:     my $access;
                   4381:     my %tools = (
                   4382:                   aboutme   => 1,
                   4383:                   blog      => 1,
                   4384:                   portfolio => 1,
                   4385:                 );
                   4386:     return if (!defined($tools{$tool}));
                   4387: 
                   4388:     if ((!defined($udom)) || (!defined($uname))) {
                   4389:         $udom = $env{'user.domain'};
                   4390:         $uname = $env{'user.name'};
                   4391:     }
                   4392: 
1.976.2.1  raeburn  4393:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4394:         if ($action ne 'reload') {
                   4395:             return $env{'environment.availabletools.'.$tool};
                   4396:         }
1.976     raeburn  4397:     }
                   4398: 
                   4399:     my ($toolstatus,$inststatus);
                   4400: 
                   4401:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4402:         $toolstatus = $env{'environment.tools.'.$tool};
                   4403:         $inststatus = $env{'environment.inststatus'};
                   4404:     } else {
                   4405:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4406:         $toolstatus = $userenv{'tools.'.$tool};
                   4407:         $inststatus = $userenv{'inststatus'};
                   4408:     }
                   4409: 
                   4410:     if ($toolstatus ne '') {
                   4411:         if ($toolstatus) {
                   4412:             $access = 1;
                   4413:         } else {
                   4414:             $access = 0;
                   4415:         }
                   4416:         return $access;
                   4417:     }
                   4418: 
                   4419:     my $is_adv = &is_advanced_user($udom,$uname);
                   4420:     my %domdef = &get_domain_defaults($udom);
                   4421:     if (ref($domdef{$tool}) eq 'HASH') {
                   4422:         if ($is_adv) {
                   4423:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4424:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4425:                     $access = 1;
                   4426:                 } else {
                   4427:                     $access = 0;
                   4428:                 }
                   4429:                 return $access;
                   4430:             }
                   4431:         }
                   4432:         if ($inststatus ne '') {
                   4433:             my ($hasaccess,$hasnoaccess);
                   4434:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4435:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4436:                     if ($domdef{$tool}{$affiliation}) {
                   4437:                         $hasaccess = 1;
                   4438:                     } else {
                   4439:                         $hasnoaccess = 1;
                   4440:                     }
                   4441:                 }
                   4442:             }
                   4443:             if ($hasaccess || $hasnoaccess) {
                   4444:                 if ($hasaccess) {
                   4445:                     $access = 1;
                   4446:                 } elsif ($hasnoaccess) {
                   4447:                     $access = 0; 
                   4448:                 }
                   4449:                 return $access;
                   4450:             }
                   4451:         } else {
                   4452:             if ($domdef{$tool}{'default'} ne '') {
                   4453:                 if ($domdef{$tool}{'default'}) {
                   4454:                     $access = 1;
                   4455:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4456:                     $access = 0;
                   4457:                 }
                   4458:                 return $access;
                   4459:             }
                   4460:         }
                   4461:     } else {
                   4462:         $access = 1;
                   4463:         return $access;
                   4464:     }
                   4465: }
                   4466: 
                   4467: sub is_advanced_user {
                   4468:     my ($udom,$uname) = @_;
                   4469:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4470:     my %allroles;
                   4471:     my $is_adv;
                   4472:     foreach my $role (keys(%roleshash)) {
                   4473:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4474:         my $area = '/'.$tdomain.'/'.$trest;
                   4475:         if ($sec ne '') {
                   4476:             $area .= '/'.$sec;
                   4477:         }
                   4478:         if (($area ne '') && ($trole ne '')) {
                   4479:             my $spec=$trole.'.'.$area;
                   4480:             if ($trole =~ /^cr\//) {
                   4481:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4482:             } elsif ($trole ne 'gr') {
                   4483:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4484:             }
                   4485:         }
                   4486:     }
                   4487:     foreach my $role (keys(%allroles)) {
                   4488:         last if ($is_adv);
                   4489:         foreach my $item (split(/:/,$allroles{$role})) {
                   4490:             if ($item ne '') {
                   4491:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4492:                 if ($privilege eq 'adv') {
                   4493:                     $is_adv = 1;
                   4494:                     last;
                   4495:                 }
                   4496:             }
                   4497:         }
                   4498:     }
                   4499:     return $is_adv;
                   4500: }
1.798     raeburn  4501: 
1.341     www      4502: # ---------------------------------------------- Custom access rule evaluation
                   4503: 
                   4504: sub customaccess {
                   4505:     my ($priv,$uri)=@_;
1.807     albertel 4506:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4507:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4508:     $udom = &LONCAPA::clean_domain($udom);
                   4509:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4510:     my $access=0;
1.800     albertel 4511:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4512: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4513: 	if ($type eq 'user') {
                   4514: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4515: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4516: 		if ($tdom) {
                   4517: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4518: 		}
1.896     albertel 4519: 		if ($tuname) {
                   4520: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4521: 		}
                   4522: 		$access=($effect eq 'allow');
                   4523: 		last;
                   4524: 	    }
                   4525: 	} else {
                   4526: 	    if ($role) {
                   4527: 		if ($role ne $urole) { next; }
                   4528: 	    }
                   4529: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4530: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4531: 		if ($tdom) {
                   4532: 		    if ($tdom ne $udom) { next; }
                   4533: 		}
                   4534: 		if ($tcrs) {
                   4535: 		    if ($tcrs ne $ucrs) { next; }
                   4536: 		}
                   4537: 		if ($tsec) {
                   4538: 		    if ($tsec ne $usec) { next; }
                   4539: 		}
                   4540: 		$access=($effect eq 'allow');
                   4541: 		last;
                   4542: 	    }
                   4543: 	    if ($realm eq '' && $role eq '') {
                   4544: 		$access=($effect eq 'allow');
                   4545: 	    }
1.402     bowersj2 4546: 	}
1.341     www      4547:     }
                   4548:     return $access;
                   4549: }
                   4550: 
1.103     harris41 4551: # ------------------------------------------------- Check for a user privilege
1.12      www      4552: 
                   4553: sub allowed {
1.810     raeburn  4554:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4555:     my $ver_orguri=$uri;
1.439     www      4556:     $uri=&deversion($uri);
1.152     www      4557:     my $orguri=$uri;
1.52      www      4558:     $uri=&declutter($uri);
1.809     raeburn  4559: 
1.810     raeburn  4560:     if ($priv eq 'evb') {
                   4561: # Evade communication block restrictions for specified role in a course
                   4562:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4563:             return $1;
                   4564:         } else {
                   4565:             return;
                   4566:         }
                   4567:     }
                   4568: 
1.620     albertel 4569:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4570: # Free bre access to adm and meta resources
1.775     albertel 4571:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4572: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4573: 	&& ($priv eq 'bre')) {
1.14      www      4574: 	return 'F';
1.159     www      4575:     }
                   4576: 
1.545     banghart 4577: # Free bre access to user's own portfolio contents
1.714     raeburn  4578:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4579:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4580: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4581:         my %setters;
                   4582:         my ($startblock,$endblock) = 
                   4583:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4584:         if ($startblock && $endblock) {
                   4585:             return 'B';
                   4586:         } else {
                   4587:             return 'F';
                   4588:         }
1.545     banghart 4589:     }
                   4590: 
1.762     raeburn  4591: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4592:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4593:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4594:         if (exists($env{'request.course.id'})) {
                   4595:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4596:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4597:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4598:                 my $courseprivid=$env{'request.course.id'};
                   4599:                 $courseprivid=~s/\_/\//;
                   4600:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4601:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4602:                     return $1; 
1.762     raeburn  4603:                 } else {
                   4604:                     if ($env{'request.course.sec'}) {
                   4605:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4606:                     }
                   4607:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4608:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4609:                         return $2;
                   4610:                     }
1.714     raeburn  4611:                 }
                   4612:             }
                   4613:         }
                   4614:     }
                   4615: 
1.159     www      4616: # Free bre to public access
                   4617: 
                   4618:     if ($priv eq 'bre') {
1.238     www      4619:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4620: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4621:            return 'F'; 
                   4622:         }
1.238     www      4623:         if ($copyright eq 'priv') {
                   4624:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4625: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4626: 		return '';
                   4627:             }
                   4628:         }
                   4629:         if ($copyright eq 'domain') {
                   4630:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4631: 	    unless (($env{'user.domain'} eq $1) ||
                   4632:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4633: 		return '';
                   4634:             }
1.262     matthew  4635:         }
1.620     albertel 4636:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4637:             # Library role, so allow browsing of resources in this domain.
                   4638:             return 'F';
1.238     www      4639:         }
1.341     www      4640:         if ($copyright eq 'custom') {
                   4641: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4642:         }
1.14      www      4643:     }
1.264     matthew  4644:     # Domain coordinator is trying to create a course
1.620     albertel 4645:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4646:         # uri is the requested domain in this case.
                   4647:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4648:         # a role of dc for the domain in question.
1.620     albertel 4649:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4650:     }
1.29      www      4651: 
1.52      www      4652:     my $thisallowed='';
                   4653:     my $statecond=0;
                   4654:     my $courseprivid='';
                   4655: 
                   4656: # Course
                   4657: 
1.620     albertel 4658:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4659:        $thisallowed.=$1;
                   4660:     }
1.29      www      4661: 
1.52      www      4662: # Domain
                   4663: 
1.620     albertel 4664:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4665:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4666:        $thisallowed.=$1;
                   4667:     }
1.52      www      4668: 
                   4669: # Course: uri itself is a course
1.66      www      4670:     my $courseuri=$uri;
                   4671:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4672:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4673: 
1.620     albertel 4674:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4675:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4676:        $thisallowed.=$1;
                   4677:     }
1.29      www      4678: 
1.665     albertel 4679: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4680: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4681:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4682: 	$thisallowed='';
1.671     raeburn  4683:         my ($match)=&is_on_map($uri);
                   4684:         if ($match) {
                   4685:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4686:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4687:                 $thisallowed.=$1;
                   4688:             }
                   4689:         } else {
1.705     albertel 4690:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4691:             if ($refuri) {
                   4692:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4693:                     $thisallowed='F';
1.671     raeburn  4694:                 } else {
                   4695:                     $refuri=&declutter($refuri);
                   4696:                     my ($match) = &is_on_map($refuri);
                   4697:                     if ($match) {
                   4698:                         $thisallowed='F';
                   4699:                     }
1.669     raeburn  4700:                 }
1.671     raeburn  4701:             }
                   4702:         }
1.314     www      4703:     }
1.492     albertel 4704: 
1.766     albertel 4705:     if ($priv eq 'bre'
                   4706: 	&& $thisallowed ne 'F' 
                   4707: 	&& $thisallowed ne '2'
                   4708: 	&& &is_portfolio_url($uri)) {
                   4709: 	$thisallowed = &portfolio_access($uri);
                   4710:     }
                   4711:     
1.52      www      4712: # Full access at system, domain or course-wide level? Exit.
1.29      www      4713:     if ($thisallowed=~/F/) {
                   4714: 	return 'F';
                   4715:     }
                   4716: 
1.52      www      4717: # If this is generating or modifying users, exit with special codes
1.29      www      4718: 
1.643     www      4719:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4720: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4721: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4722: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4723: 	    unless ($auname) { return $thisallowed; }
                   4724: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4725: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4726: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4727: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4728: 	}
1.52      www      4729: 	return $thisallowed;
                   4730:     }
                   4731: #
1.103     harris41 4732: # Gathered so far: system, domain and course wide privileges
1.52      www      4733: #
                   4734: # Course: See if uri or referer is an individual resource that is part of 
                   4735: # the course
                   4736: 
1.620     albertel 4737:     if ($env{'request.course.id'}) {
1.232     www      4738: 
1.620     albertel 4739:        $courseprivid=$env{'request.course.id'};
                   4740:        if ($env{'request.course.sec'}) {
                   4741:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4742:        }
                   4743:        $courseprivid=~s/\_/\//;
                   4744:        my $checkreferer=1;
1.232     www      4745:        my ($match,$cond)=&is_on_map($uri);
                   4746:        if ($match) {
                   4747:            $statecond=$cond;
1.620     albertel 4748:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4749:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4750:                $thisallowed.=$1;
                   4751:                $checkreferer=0;
                   4752:            }
1.29      www      4753:        }
1.83      www      4754:        
1.148     www      4755:        if ($checkreferer) {
1.620     albertel 4756: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4757:             unless ($refuri) {
1.800     albertel 4758:                 foreach my $key (keys(%env)) {
                   4759: 		    if ($key=~/^httpref\..*\*/) {
                   4760: 			my $pattern=$key;
1.156     www      4761:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4762:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4763:                         $pattern=~s/\//\\\//g;
1.152     www      4764:                         if ($orguri=~/$pattern/) {
1.800     albertel 4765: 			    $refuri=$env{$key};
1.148     www      4766:                         }
                   4767:                     }
1.191     harris41 4768:                 }
1.148     www      4769:             }
1.232     www      4770: 
1.148     www      4771:          if ($refuri) { 
1.152     www      4772: 	  $refuri=&declutter($refuri);
1.232     www      4773:           my ($match,$cond)=&is_on_map($refuri);
                   4774:             if ($match) {
                   4775:               my $refstatecond=$cond;
1.620     albertel 4776:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4777:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4778:                   $thisallowed.=$1;
1.53      www      4779:                   $uri=$refuri;
                   4780:                   $statecond=$refstatecond;
1.52      www      4781:               }
                   4782:           }
1.148     www      4783:         }
1.29      www      4784:        }
1.52      www      4785:    }
1.29      www      4786: 
1.52      www      4787: #
1.103     harris41 4788: # Gathered now: all privileges that could apply, and condition number
1.52      www      4789: # 
                   4790: #
                   4791: # Full or no access?
                   4792: #
1.29      www      4793: 
1.52      www      4794:     if ($thisallowed=~/F/) {
                   4795: 	return 'F';
                   4796:     }
1.29      www      4797: 
1.52      www      4798:     unless ($thisallowed) {
                   4799:         return '';
                   4800:     }
1.29      www      4801: 
1.52      www      4802: # Restrictions exist, deal with them
                   4803: #
                   4804: #   C:according to course preferences
                   4805: #   R:according to resource settings
                   4806: #   L:unless locked
                   4807: #   X:according to user session state
                   4808: #
                   4809: 
                   4810: # Possibly locked functionality, check all courses
1.54      www      4811: # Locks might take effect only after 10 minutes cache expiration for other
                   4812: # courses, and 2 minutes for current course
1.52      www      4813: 
                   4814:     my $envkey;
                   4815:     if ($thisallowed=~/L/) {
1.620     albertel 4816:         foreach $envkey (keys %env) {
1.54      www      4817:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4818:                my $courseid=$2;
                   4819:                my $roleid=$1.'.'.$2;
1.92      www      4820:                $courseid=~s/^\///;
1.54      www      4821:                my $expiretime=600;
1.620     albertel 4822:                if ($env{'request.role'} eq $roleid) {
1.54      www      4823: 		  $expiretime=120;
                   4824:                }
                   4825: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4826:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4827:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4828: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4829:                }
1.620     albertel 4830:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4831:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4832: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4833:                        &log($env{'user.domain'},$env{'user.name'},
                   4834:                             $env{'user.home'},
1.57      www      4835:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4836:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4837:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4838: 		       return '';
                   4839:                    }
                   4840:                }
1.620     albertel 4841:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4842:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4843: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4844:                        &log($env{'user.domain'},$env{'user.name'},
                   4845:                             $env{'user.home'},
1.57      www      4846:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4847:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4848:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4849: 		       return '';
                   4850:                    }
                   4851:                }
                   4852: 	   }
1.29      www      4853:        }
1.52      www      4854:     }
                   4855:    
                   4856: #
                   4857: # Rest of the restrictions depend on selected course
                   4858: #
                   4859: 
1.620     albertel 4860:     unless ($env{'request.course.id'}) {
1.766     albertel 4861: 	if ($thisallowed eq 'A') {
                   4862: 	    return 'A';
1.814     raeburn  4863:         } elsif ($thisallowed eq 'B') {
                   4864:             return 'B';
1.766     albertel 4865: 	} else {
                   4866: 	    return '1';
                   4867: 	}
1.52      www      4868:     }
1.29      www      4869: 
1.52      www      4870: #
                   4871: # Now user is definitely in a course
                   4872: #
1.53      www      4873: 
                   4874: 
                   4875: # Course preferences
                   4876: 
                   4877:    if ($thisallowed=~/C/) {
1.620     albertel 4878:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4879:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4880:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4881: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4882: 	   if ($priv ne 'pch') { 
                   4883: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4884: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4885: 			$env{'request.course.id'});
                   4886: 	   }
1.237     www      4887:            return '';
                   4888:        }
                   4889: 
1.620     albertel 4890:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4891: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4892: 	   if ($priv ne 'pch') { 
                   4893: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4894: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4895: 			$env{'request.course.id'});
                   4896: 	   }
1.54      www      4897:            return '';
                   4898:        }
1.53      www      4899:    }
                   4900: 
                   4901: # Resource preferences
                   4902: 
                   4903:    if ($thisallowed=~/R/) {
1.620     albertel 4904:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4905:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4906: 	   if ($priv ne 'pch') { 
                   4907: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4908: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4909: 	   }
                   4910: 	   return '';
1.54      www      4911:        }
1.53      www      4912:    }
1.30      www      4913: 
1.246     www      4914: # Restricted by state or randomout?
1.30      www      4915: 
1.52      www      4916:    if ($thisallowed=~/X/) {
1.620     albertel 4917:       if ($env{'acc.randomout'}) {
1.579     albertel 4918: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4919:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4920:             return ''; 
                   4921:          }
1.247     www      4922:       }
                   4923:       if (&condval($statecond)) {
1.52      www      4924: 	 return '2';
                   4925:       } else {
                   4926:          return '';
                   4927:       }
                   4928:    }
1.30      www      4929: 
1.766     albertel 4930:     if ($thisallowed eq 'A') {
                   4931: 	return 'A';
1.814     raeburn  4932:     } elsif ($thisallowed eq 'B') {
                   4933:         return 'B';
1.766     albertel 4934:     }
1.52      www      4935:    return 'F';
1.232     www      4936: }
                   4937: 
1.710     albertel 4938: sub split_uri_for_cond {
                   4939:     my $uri=&deversion(&declutter(shift));
                   4940:     my @uriparts=split(/\//,$uri);
                   4941:     my $filename=pop(@uriparts);
                   4942:     my $pathname=join('/',@uriparts);
                   4943:     return ($pathname,$filename);
                   4944: }
1.232     www      4945: # --------------------------------------------------- Is a resource on the map?
                   4946: 
                   4947: sub is_on_map {
1.710     albertel 4948:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4949:     #Trying to find the conditional for the file
1.620     albertel 4950:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4951: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4952:     if ($match) {
1.289     bowersj2 4953: 	return (1,$1);
                   4954:     } else {
1.434     www      4955: 	return (0,0);
1.289     bowersj2 4956:     }
1.12      www      4957: }
                   4958: 
1.427     www      4959: # --------------------------------------------------------- Get symb from alias
                   4960: 
                   4961: sub get_symb_from_alias {
                   4962:     my $symb=shift;
                   4963:     my ($map,$resid,$url)=&decode_symb($symb);
                   4964: # Already is a symb
                   4965:     if ($url) { return $symb; }
                   4966: # Must be an alias
                   4967:     my $aliassymb='';
                   4968:     my %bighash;
1.620     albertel 4969:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4970:                             &GDBM_READER(),0640)) {
                   4971:         my $rid=$bighash{'mapalias_'.$symb};
                   4972: 	if ($rid) {
                   4973: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4974: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4975: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4976: 	}
                   4977:         untie %bighash;
                   4978:     }
                   4979:     return $aliassymb;
                   4980: }
                   4981: 
1.12      www      4982: # ----------------------------------------------------------------- Define Role
                   4983: 
                   4984: sub definerole {
                   4985:   if (allowed('mcr','/')) {
                   4986:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4987:     foreach my $role (split(':',$sysrole)) {
                   4988: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4989:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4990:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4991: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4992:                return "refused:s:$crole&$cqual"; 
                   4993:             }
                   4994:         }
1.191     harris41 4995:     }
1.800     albertel 4996:     foreach my $role (split(':',$domrole)) {
                   4997: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4998:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4999:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5000: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5001:                return "refused:d:$crole&$cqual"; 
                   5002:             }
                   5003:         }
1.191     harris41 5004:     }
1.800     albertel 5005:     foreach my $role (split(':',$courole)) {
                   5006: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5007:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5008:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5009: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5010:                return "refused:c:$crole&$cqual"; 
                   5011:             }
                   5012:         }
1.191     harris41 5013:     }
1.620     albertel 5014:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5015:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5016: 	        "rolesdef_$rolename=".
                   5017:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5018:     return reply($command,$env{'user.home'});
1.12      www      5019:   } else {
                   5020:     return 'refused';
                   5021:   }
1.105     harris41 5022: }
                   5023: 
                   5024: # ---------------- Make a metadata query against the network of library servers
                   5025: 
                   5026: sub metadata_query {
1.244     matthew  5027:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5028:     my %rhash;
1.845     albertel 5029:     my %libserv = &all_library();
1.244     matthew  5030:     my @server_list = (defined($server_array) ? @$server_array
                   5031:                                               : keys(%libserv) );
                   5032:     for my $server (@server_list) {
1.118     harris41 5033: 	unless ($custom or $customshow) {
                   5034: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5035: 	    $rhash{$server}=$reply;
                   5036: 	}
                   5037: 	else {
                   5038: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5039: 			     &escape($custom).':'.&escape($customshow),
                   5040: 			     $server);
                   5041: 	    $rhash{$server}=$reply;
                   5042: 	}
1.112     harris41 5043:     }
1.118     harris41 5044:     return \%rhash;
1.240     www      5045: }
                   5046: 
                   5047: # ----------------------------------------- Send log queries and wait for reply
                   5048: 
                   5049: sub log_query {
                   5050:     my ($uname,$udom,$query,%filters)=@_;
                   5051:     my $uhome=&homeserver($uname,$udom);
                   5052:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5053:     my $uhost=&hostname($uhome);
1.800     albertel 5054:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5055:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5056:                        $uhome);
1.479     albertel 5057:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5058:     return get_query_reply($queryid);
                   5059: }
                   5060: 
1.818     raeburn  5061: # -------------------------- Update MySQL table for portfolio file
                   5062: 
                   5063: sub update_portfolio_table {
1.821     raeburn  5064:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5065:     if ($group ne '') {
                   5066:         $file_name =~s /^\Q$group\E//;
                   5067:     }
1.818     raeburn  5068:     my $homeserver = &homeserver($uname,$udom);
                   5069:     my $queryid=
1.821     raeburn  5070:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5071:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5072:     my $reply = &get_query_reply($queryid);
                   5073:     return $reply;
                   5074: }
                   5075: 
1.899     raeburn  5076: # -------------------------- Update MySQL allusers table
                   5077: 
                   5078: sub update_allusers_table {
                   5079:     my ($uname,$udom,$names) = @_;
                   5080:     my $homeserver = &homeserver($uname,$udom);
                   5081:     my $queryid=
                   5082:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5083:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5084:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5085:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5086:                'generation='.&escape($names->{'generation'}).'%%'.
                   5087:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5088:                'id='.&escape($names->{'id'}),$homeserver);
                   5089:     my $reply = &get_query_reply($queryid);
                   5090:     return $reply;
                   5091: }
                   5092: 
1.508     raeburn  5093: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5094: 
                   5095: sub fetch_enrollment_query {
1.511     raeburn  5096:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5097:     my $homeserver;
1.547     raeburn  5098:     my $maxtries = 1;
1.508     raeburn  5099:     if ($context eq 'automated') {
                   5100:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5101:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5102:     } else {
                   5103:         $homeserver = &homeserver($cnum,$dom);
                   5104:     }
1.838     albertel 5105:     my $host=&hostname($homeserver);
1.506     raeburn  5106:     my $cmd = '';
1.800     albertel 5107:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5108:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5109:     }
                   5110:     $cmd =~ s/%%$//;
                   5111:     $cmd = &escape($cmd);
                   5112:     my $query = 'fetchenrollment';
1.620     albertel 5113:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5114:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5115:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5116:         return 'error: '.$queryid;
                   5117:     }
1.506     raeburn  5118:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5119:     my $tries = 1;
                   5120:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5121:         $reply = &get_query_reply($queryid);
                   5122:         $tries ++;
                   5123:     }
1.526     raeburn  5124:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5125:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5126:     } else {
1.901     albertel 5127:         my @responses = split(/:/,$reply);
1.515     raeburn  5128:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5129:             foreach my $line (@responses) {
                   5130:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5131:                 $$replyref{$key} = $value;
                   5132:             }
                   5133:         } else {
1.506     raeburn  5134:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5135:             foreach my $line (@responses) {
                   5136:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5137:                 $$replyref{$key} = $value;
                   5138:                 if ($value > 0) {
1.800     albertel 5139:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5140:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5141:                         my $destname = $pathname.'/'.$filename;
                   5142:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5143:                         if ($xml_classlist =~ /^error/) {
                   5144:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5145:                         } else {
1.506     raeburn  5146:                             if ( open(FILE,">$destname") ) {
                   5147:                                 print FILE &unescape($xml_classlist);
                   5148:                                 close(FILE);
1.526     raeburn  5149:                             } else {
                   5150:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5151:                             }
                   5152:                         }
                   5153:                     }
                   5154:                 }
                   5155:             }
                   5156:         }
                   5157:         return 'ok';
                   5158:     }
                   5159:     return 'error';
                   5160: }
                   5161: 
1.242     www      5162: sub get_query_reply {
                   5163:     my $queryid=shift;
1.240     www      5164:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5165:     my $reply='';
                   5166:     for (1..100) {
                   5167: 	sleep 2;
                   5168:         if (-e $replyfile.'.end') {
1.448     albertel 5169: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5170: 		$reply = join('',<$fh>);
                   5171: 		close($fh);
1.240     www      5172: 	   } else { return 'error: reply_file_error'; }
1.242     www      5173:            return &unescape($reply);
                   5174: 	}
1.240     www      5175:     }
1.242     www      5176:     return 'timeout:'.$queryid;
1.240     www      5177: }
                   5178: 
                   5179: sub courselog_query {
1.241     www      5180: #
                   5181: # possible filters:
                   5182: # url: url or symb
                   5183: # username
                   5184: # domain
                   5185: # action: view, submit, grade
                   5186: # start: timestamp
                   5187: # end: timestamp
                   5188: #
1.240     www      5189:     my (%filters)=@_;
1.620     albertel 5190:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5191:     if ($filters{'url'}) {
                   5192: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5193:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5194:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5195:     }
1.620     albertel 5196:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5197:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5198:     return &log_query($cname,$cdom,'courselog',%filters);
                   5199: }
                   5200: 
                   5201: sub userlog_query {
1.858     raeburn  5202: #
                   5203: # possible filters:
                   5204: # action: log check role
                   5205: # start: timestamp
                   5206: # end: timestamp
                   5207: #
1.240     www      5208:     my ($uname,$udom,%filters)=@_;
                   5209:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5210: }
                   5211: 
1.506     raeburn  5212: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5213: 
                   5214: sub auto_run {
1.508     raeburn  5215:     my ($cnum,$cdom) = @_;
1.876     raeburn  5216:     my $response = 0;
                   5217:     my $settings;
                   5218:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5219:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5220:         $settings = $domconfig{'autoenroll'};
                   5221:         if ($settings->{'run'} eq '1') {
                   5222:             $response = 1;
                   5223:         }
                   5224:     } else {
1.934     raeburn  5225:         my $homeserver;
                   5226:         if (&is_course($cdom,$cnum)) {
                   5227:             $homeserver = &homeserver($cnum,$cdom);
                   5228:         } else {
                   5229:             $homeserver = &domain($cdom,'primary');
                   5230:         }
                   5231:         if ($homeserver ne 'no_host') {
                   5232:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5233:         }
1.876     raeburn  5234:     }
1.506     raeburn  5235:     return $response;
                   5236: }
1.776     albertel 5237: 
1.506     raeburn  5238: sub auto_get_sections {
1.508     raeburn  5239:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5240:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5241:     my @secs = ();
1.511     raeburn  5242:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5243:     unless ($response eq 'refused') {
1.901     albertel 5244:         @secs = split(/:/,$response);
1.506     raeburn  5245:     }
                   5246:     return @secs;
                   5247: }
1.776     albertel 5248: 
1.506     raeburn  5249: sub auto_new_course {
1.508     raeburn  5250:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5251:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5252:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5253:     return $response;
                   5254: }
1.776     albertel 5255: 
1.506     raeburn  5256: sub auto_validate_courseID {
1.508     raeburn  5257:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5258:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5259:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5260:     return $response;
                   5261: }
1.776     albertel 5262: 
1.506     raeburn  5263: sub auto_create_password {
1.873     raeburn  5264:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5265:     my ($homeserver,$response);
1.506     raeburn  5266:     my $create_passwd = 0;
                   5267:     my $authchk = '';
1.873     raeburn  5268:     if ($udom =~ /^$match_domain$/) {
                   5269:         $homeserver = &domain($udom,'primary');
                   5270:     }
                   5271:     if ($homeserver eq '') {
                   5272:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5273:             $homeserver = &homeserver($cnum,$cdom);
                   5274:         }
                   5275:     }
                   5276:     if ($homeserver eq '') {
                   5277:         $authchk = 'nodomain';
1.506     raeburn  5278:     } else {
1.873     raeburn  5279:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5280:         if ($response eq 'refused') {
                   5281:             $authchk = 'refused';
                   5282:         } else {
1.901     albertel 5283:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5284:         }
1.506     raeburn  5285:     }
                   5286:     return ($authparam,$create_passwd,$authchk);
                   5287: }
                   5288: 
1.706     raeburn  5289: sub auto_photo_permission {
                   5290:     my ($cnum,$cdom,$students) = @_;
                   5291:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5292:     my ($outcome,$perm_reqd,$conditions) = 
                   5293: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5294:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5295: 	return (undef,undef);
                   5296:     }
1.706     raeburn  5297:     return ($outcome,$perm_reqd,$conditions);
                   5298: }
                   5299: 
                   5300: sub auto_checkphotos {
                   5301:     my ($uname,$udom,$pid) = @_;
                   5302:     my $homeserver = &homeserver($uname,$udom);
                   5303:     my ($result,$resulttype);
                   5304:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5305: 				   &escape($uname).':'.&escape($pid),
                   5306: 				   $homeserver));
1.709     albertel 5307:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5308: 	return (undef,undef);
                   5309:     }
1.706     raeburn  5310:     if ($outcome) {
                   5311:         ($result,$resulttype) = split(/:/,$outcome);
                   5312:     } 
                   5313:     return ($result,$resulttype);
                   5314: }
                   5315: 
                   5316: sub auto_photochoice {
                   5317:     my ($cnum,$cdom) = @_;
                   5318:     my $homeserver = &homeserver($cnum,$cdom);
                   5319:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5320: 						       &escape($cdom),
                   5321: 						       $homeserver)));
1.709     albertel 5322:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5323: 	return (undef,undef);
                   5324:     }
1.706     raeburn  5325:     return ($update,$comment);
                   5326: }
                   5327: 
                   5328: sub auto_photoupdate {
                   5329:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5330:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5331:     my $host=&hostname($homeserver);
1.706     raeburn  5332:     my $cmd = '';
                   5333:     my $maxtries = 1;
1.800     albertel 5334:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5335:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5336:     }
                   5337:     $cmd =~ s/%%$//;
                   5338:     $cmd = &escape($cmd);
                   5339:     my $query = 'institutionalphotos';
                   5340:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5341:     unless ($queryid=~/^\Q$host\E\_/) {
                   5342:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5343:         return 'error: '.$queryid;
                   5344:     }
                   5345:     my $reply = &get_query_reply($queryid);
                   5346:     my $tries = 1;
                   5347:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5348:         $reply = &get_query_reply($queryid);
                   5349:         $tries ++;
                   5350:     }
                   5351:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5352:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5353:     } else {
                   5354:         my @responses = split(/:/,$reply);
                   5355:         my $outcome = shift(@responses); 
                   5356:         foreach my $item (@responses) {
                   5357:             my ($key,$value) = split(/=/,$item);
                   5358:             $$photo{$key} = $value;
                   5359:         }
                   5360:         return $outcome;
                   5361:     }
                   5362:     return 'error';
                   5363: }
                   5364: 
1.521     raeburn  5365: sub auto_instcode_format {
1.793     albertel 5366:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5367: 	$cat_order) = @_;
1.521     raeburn  5368:     my $courses = '';
1.772     raeburn  5369:     my @homeservers;
1.521     raeburn  5370:     if ($caller eq 'global') {
1.841     albertel 5371: 	my %servers = &get_servers($codedom,'library');
                   5372: 	foreach my $tryserver (keys(%servers)) {
                   5373: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5374: 		push(@homeservers,$tryserver);
                   5375: 	    }
1.584     raeburn  5376:         }
1.521     raeburn  5377:     } else {
1.772     raeburn  5378:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5379:     }
1.793     albertel 5380:     foreach my $code (keys(%{$instcodes})) {
                   5381:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5382:     }
                   5383:     chop($courses);
1.772     raeburn  5384:     my $ok_response = 0;
                   5385:     my $response;
                   5386:     while (@homeservers > 0 && $ok_response == 0) {
                   5387:         my $server = shift(@homeservers); 
                   5388:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5389:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5390:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5391: 		split(/:/,$response);
1.772     raeburn  5392:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5393:             push(@{$codetitles},&str2array($codetitles_str));
                   5394:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5395:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5396:             $ok_response = 1;
                   5397:         }
                   5398:     }
                   5399:     if ($ok_response) {
1.521     raeburn  5400:         return 'ok';
1.772     raeburn  5401:     } else {
                   5402:         return $response;
1.521     raeburn  5403:     }
                   5404: }
                   5405: 
1.792     raeburn  5406: sub auto_instcode_defaults {
                   5407:     my ($domain,$returnhash,$code_order) = @_;
                   5408:     my @homeservers;
1.841     albertel 5409: 
                   5410:     my %servers = &get_servers($domain,'library');
                   5411:     foreach my $tryserver (keys(%servers)) {
                   5412: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5413: 	    push(@homeservers,$tryserver);
                   5414: 	}
1.792     raeburn  5415:     }
1.841     albertel 5416: 
1.792     raeburn  5417:     my $response;
1.841     albertel 5418:     foreach my $server (@homeservers) {
1.792     raeburn  5419:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5420:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5421: 	
                   5422: 	foreach my $pair (split(/\&/,$response)) {
                   5423: 	    my ($name,$value)=split(/\=/,$pair);
                   5424: 	    if ($name eq 'code_order') {
                   5425: 		@{$code_order} = split(/\&/,&unescape($value));
                   5426: 	    } else {
                   5427: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5428: 	    }
                   5429: 	}
                   5430: 	return 'ok';
1.792     raeburn  5431:     }
1.841     albertel 5432: 
                   5433:     return $response;
1.792     raeburn  5434: } 
                   5435: 
1.777     albertel 5436: sub auto_validate_class_sec {
1.918     raeburn  5437:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5438:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5439:     my $ownerlist;
                   5440:     if (ref($owners) eq 'ARRAY') {
                   5441:         $ownerlist = join(',',@{$owners});
                   5442:     } else {
                   5443:         $ownerlist = $owners;
                   5444:     }
1.773     raeburn  5445:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5446:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5447:     return $response;
                   5448: }
                   5449: 
1.679     raeburn  5450: # ------------------------------------------------------- Course Group routines
                   5451: 
                   5452: sub get_coursegroups {
1.809     raeburn  5453:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5454:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5455: }
                   5456: 
1.679     raeburn  5457: sub modify_coursegroup {
                   5458:     my ($cdom,$cnum,$groupsettings) = @_;
                   5459:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5460: }
                   5461: 
1.809     raeburn  5462: sub toggle_coursegroup_status {
                   5463:     my ($cdom,$cnum,$group,$action) = @_;
                   5464:     my ($from_namespace,$to_namespace);
                   5465:     if ($action eq 'delete') {
                   5466:         $from_namespace = 'coursegroups';
                   5467:         $to_namespace = 'deleted_groups';
                   5468:     } else {
                   5469:         $from_namespace = 'deleted_groups';
                   5470:         $to_namespace = 'coursegroups';
                   5471:     }
                   5472:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5473:     if (my $tmp = &error(%curr_group)) {
                   5474:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5475:         return ('read error',$tmp);
                   5476:     } else {
                   5477:         my %savedsettings = %curr_group; 
1.809     raeburn  5478:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5479:         my $deloutcome;
                   5480:         if ($result eq 'ok') {
1.809     raeburn  5481:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5482:         } else {
                   5483:             return ('write error',$result);
                   5484:         }
                   5485:         if ($deloutcome eq 'ok') {
                   5486:             return 'ok';
                   5487:         } else {
                   5488:             return ('delete error',$deloutcome);
                   5489:         }
                   5490:     }
                   5491: }
                   5492: 
1.679     raeburn  5493: sub modify_group_roles {
1.957     raeburn  5494:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5495:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5496:     my $role = 'gr/'.&escape($userprivs);
                   5497:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5498:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5499:     if ($result eq 'ok') {
                   5500:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5501:     }
1.679     raeburn  5502:     return $result;
                   5503: }
                   5504: 
                   5505: sub modify_coursegroup_membership {
                   5506:     my ($cdom,$cnum,$membership) = @_;
                   5507:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5508:     return $result;
                   5509: }
                   5510: 
1.682     raeburn  5511: sub get_active_groups {
                   5512:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5513:     my $now = time;
                   5514:     my %groups = ();
                   5515:     foreach my $key (keys(%env)) {
1.811     albertel 5516:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5517:             my ($start,$end) = split(/\./,$env{$key});
                   5518:             if (($end!=0) && ($end<$now)) { next; }
                   5519:             if (($start!=0) && ($start>$now)) { next; }
                   5520:             if ($1 eq $cdom && $2 eq $cnum) {
                   5521:                 $groups{$3} = $env{$key} ;
                   5522:             }
                   5523:         }
                   5524:     }
                   5525:     return %groups;
                   5526: }
                   5527: 
1.683     raeburn  5528: sub get_group_membership {
                   5529:     my ($cdom,$cnum,$group) = @_;
                   5530:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5531: }
                   5532: 
                   5533: sub get_users_groups {
                   5534:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5535:     my @usersgroups;
1.683     raeburn  5536:     my $cachetime=1800;
                   5537: 
                   5538:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5539:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5540:     if (defined($cached)) {
1.734     albertel 5541:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5542:     } else {  
                   5543:         $grouplist = '';
1.816     raeburn  5544:         my $courseurl = &courseid_to_courseurl($courseid);
                   5545:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5546:         my $access_end = $env{'course.'.$courseid.
                   5547:                               '.default_enrollment_end_date'};
                   5548:         my $now = time;
                   5549:         foreach my $key (keys(%roleshash)) {
                   5550:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5551:                 my $group = $1;
                   5552:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5553:                     my $start = $2;
                   5554:                     my $end = $1;
                   5555:                     if ($start == -1) { next; } # deleted from group
                   5556:                     if (($start!=0) && ($start>$now)) { next; }
                   5557:                     if (($end!=0) && ($end<$now)) {
                   5558:                         if ($access_end && $access_end < $now) {
                   5559:                             if ($access_end - $end < 86400) {
                   5560:                                 push(@usersgroups,$group);
1.733     raeburn  5561:                             }
                   5562:                         }
1.817     raeburn  5563:                         next;
1.733     raeburn  5564:                     }
1.817     raeburn  5565:                     push(@usersgroups,$group);
1.683     raeburn  5566:                 }
                   5567:             }
                   5568:         }
1.817     raeburn  5569:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5570:         $grouplist = join(':',@usersgroups);
                   5571:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5572:     }
1.733     raeburn  5573:     return @usersgroups;
1.683     raeburn  5574: }
                   5575: 
                   5576: sub devalidate_getgroups_cache {
                   5577:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5578:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5579: 
1.683     raeburn  5580:     my $hashid="$udom:$uname:$courseid";
                   5581:     &devalidate_cache_new('getgroups',$hashid);
                   5582: }
                   5583: 
1.12      www      5584: # ------------------------------------------------------------------ Plain Text
                   5585: 
                   5586: sub plaintext {
1.742     raeburn  5587:     my ($short,$type,$cid) = @_;
1.758     albertel 5588:     if ($short =~ /^cr/) {
                   5589: 	return (split('/',$short))[-1];
                   5590:     }
1.742     raeburn  5591:     if (!defined($cid)) {
                   5592:         $cid = $env{'request.course.id'};
                   5593:     }
                   5594:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5595:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5596:                                           '.plaintext'});
                   5597:     }
                   5598:     my %rolenames = (
                   5599:                       Course => 'std',
                   5600:                       Group => 'alt1',
                   5601:                     );
                   5602:     if (defined($type) && 
                   5603:          defined($rolenames{$type}) && 
                   5604:          defined($prp{$short}{$rolenames{$type}})) {
                   5605:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5606:     } else {
                   5607:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5608:     }
1.12      www      5609: }
                   5610: 
                   5611: # ----------------------------------------------------------------- Assign Role
                   5612: 
                   5613: sub assignrole {
1.957     raeburn  5614:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5615:         $context)=@_;
1.21      www      5616:     my $mrole;
                   5617:     if ($role =~ /^cr\//) {
1.393     www      5618:         my $cwosec=$url;
1.811     albertel 5619:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5620: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5621:            &logthis('Refused custom assignrole: '.
                   5622:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5623: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5624:            return 'refused'; 
                   5625:         }
1.21      www      5626:         $mrole='cr';
1.678     raeburn  5627:     } elsif ($role =~ /^gr\//) {
                   5628:         my $cwogrp=$url;
1.811     albertel 5629:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5630:         unless (&allowed('mdg',$cwogrp)) {
                   5631:             &logthis('Refused group assignrole: '.
                   5632:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5633:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5634:             return 'refused';
                   5635:         }
                   5636:         $mrole='gr';
1.21      www      5637:     } else {
1.82      www      5638:         my $cwosec=$url;
1.811     albertel 5639:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5640:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5641:             my $refused;
                   5642:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5643:                 if (!(&allowed('c'.$role,$url))) {
                   5644:                     $refused = 1;
                   5645:                 }
                   5646:             } else {
                   5647:                 $refused = 1;
                   5648:             }
1.947     raeburn  5649:             if ($refused) {
                   5650:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5651:                     $refused = '';
                   5652:                 } else {
                   5653:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5654:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5655: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5656:                     return 'refused';
                   5657:                 }
1.932     raeburn  5658:             }
1.104     www      5659:         }
1.21      www      5660:         $mrole=$role;
                   5661:     }
1.620     albertel 5662:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5663:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5664:     if ($end) { $command.='_'.$end; }
1.21      www      5665:     if ($start) {
                   5666: 	if ($end) { 
1.81      www      5667:            $command.='_'.$start; 
1.21      www      5668:         } else {
1.81      www      5669:            $command.='_0_'.$start;
1.21      www      5670:         }
                   5671:     }
1.739     raeburn  5672:     my $origstart = $start;
                   5673:     my $origend = $end;
1.957     raeburn  5674:     my $delflag;
1.357     www      5675: # actually delete
                   5676:     if ($deleteflag) {
1.373     www      5677: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5678: # modify command to delete the role
1.620     albertel 5679:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5680:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5681: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5682: # set start and finish to negative values for userrolelog
                   5683:            $start=-1;
                   5684:            $end=-1;
1.957     raeburn  5685:            $delflag = 1;
1.357     www      5686:         }
                   5687:     }
                   5688: # send command
1.349     www      5689:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5690: # log new user role if status is ok
1.349     www      5691:     if ($answer eq 'ok') {
1.663     raeburn  5692: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5693: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5694:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5695:         unless ($role =~ /^gr/) {
                   5696:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5697:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5698:         }
1.349     www      5699:     }
                   5700:     return $answer;
1.169     harris41 5701: }
                   5702: 
                   5703: # -------------------------------------------------- Modify user authentication
1.197     www      5704: # Overrides without validation
                   5705: 
1.169     harris41 5706: sub modifyuserauth {
                   5707:     my ($udom,$uname,$umode,$upass)=@_;
                   5708:     my $uhome=&homeserver($uname,$udom);
1.197     www      5709:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5710:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5711:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5712:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5713:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5714: 		     &escape($upass),$uhome);
1.620     albertel 5715:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5716:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5717:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5718:     &log($udom,,$uname,$uhome,
1.620     albertel 5719:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5720:                                      $env{'user.name'}.', '.$umode.
1.197     www      5721:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5722:     unless ($reply eq 'ok') {
1.197     www      5723:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5724: 	return 'error: '.$reply;
                   5725:     }   
1.170     harris41 5726:     return 'ok';
1.80      www      5727: }
                   5728: 
1.81      www      5729: # --------------------------------------------------------------- Modify a user
1.80      www      5730: 
1.81      www      5731: sub modifyuser {
1.206     matthew  5732:     my ($udom,    $uname, $uid,
                   5733:         $umode,   $upass, $first,
                   5734:         $middle,  $last,  $gene,
1.963     raeburn  5735:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5736:     $udom= &LONCAPA::clean_domain($udom);
                   5737:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5738:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5739:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5740: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5741:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5742:                                      ' desiredhome not specified'). 
1.620     albertel 5743:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5744:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5745:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5746: # ----------------------------------------------------------------- Create User
1.406     albertel 5747:     if (($uhome eq 'no_host') && 
                   5748: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5749:         my $unhome='';
1.844     albertel 5750:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5751:             $unhome = $desiredhome;
1.620     albertel 5752: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5753: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5754:         } else { # load balancing routine for determining $unhome
1.81      www      5755:             my $loadm=10000000;
1.841     albertel 5756: 	    my %servers = &get_servers($udom,'library');
                   5757: 	    foreach my $tryserver (keys(%servers)) {
                   5758: 		my $answer=reply('load',$tryserver);
                   5759: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5760: 		    $loadm=$answer;
                   5761: 		    $unhome=$tryserver;
                   5762: 		}
1.80      www      5763: 	    }
                   5764:         }
                   5765:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5766: 	    return 'error: unable to find a home server for '.$uname.
                   5767:                    ' in domain '.$udom;
1.80      www      5768:         }
                   5769:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5770:                          &escape($upass),$unhome);
                   5771: 	unless ($reply eq 'ok') {
                   5772:             return 'error: '.$reply;
                   5773:         }   
1.230     stredwic 5774:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5775:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5776: 	    return 'error: unable verify users home machine.';
1.80      www      5777:         }
1.209     matthew  5778:     }   # End of creation of new user
1.80      www      5779: # ---------------------------------------------------------------------- Add ID
                   5780:     if ($uid) {
                   5781:        $uid=~tr/A-Z/a-z/;
                   5782:        my %uidhash=&idrget($udom,$uname);
1.196     www      5783:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5784:          && (!$forceid)) {
1.80      www      5785: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5786: 	      return 'error: user id "'.$uid.'" does not match '.
                   5787:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5788:           }
                   5789:        } else {
                   5790: 	  &idput($udom,($uname => $uid));
                   5791:        }
                   5792:     }
                   5793: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5794:     my @tmp=&get('environment',
1.899     raeburn  5795: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5796:                     'permanentemail','inststatus'],
1.134     albertel 5797: 		   $udom,$uname);
1.313     matthew  5798:     my %names;
                   5799:     if ($tmp[0] =~ m/^error:.*/) { 
                   5800:         %names=(); 
                   5801:     } else {
                   5802:         %names = @tmp;
                   5803:     }
1.388     www      5804: #
                   5805: # Make sure to not trash student environment if instructor does not bother
                   5806: # to supply name and email information
                   5807: #
                   5808:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5809:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5810:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5811:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5812:     if ($email) {
                   5813:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5814:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5815:     }
1.899     raeburn  5816:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5817:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5818:     my $reply = &put('environment', \%names, $udom,$uname);
                   5819:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5820:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5821:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5822:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5823:                  $umode.', '.$first.', '.$middle.', '.
                   5824: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5825:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5826:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5827:     } else {
                   5828:         $logmsg .= ' during self creation';
                   5829:     }
                   5830:     &logthis($logmsg);
1.134     albertel 5831:     return 'ok';
1.80      www      5832: }
                   5833: 
1.81      www      5834: # -------------------------------------------------------------- Modify student
1.80      www      5835: 
1.81      www      5836: sub modifystudent {
                   5837:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5838:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5839:         $selfenroll,$context)=@_;
1.455     albertel 5840:     if (!$cid) {
1.620     albertel 5841: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5842: 	    return 'not_in_class';
                   5843: 	}
1.80      www      5844:     }
                   5845: # --------------------------------------------------------------- Make the user
1.81      www      5846:     my $reply=&modifyuser
1.209     matthew  5847: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5848:          $desiredhome,$email);
1.80      www      5849:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5850:     # This will cause &modify_student_enrollment to get the uid from the
                   5851:     # students environment
                   5852:     $uid = undef if (!$forceid);
1.455     albertel 5853:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5854: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5855:     return $reply;
                   5856: }
                   5857: 
                   5858: sub modify_student_enrollment {
1.957     raeburn  5859:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5860:     my ($cdom,$cnum,$chome);
                   5861:     if (!$cid) {
1.620     albertel 5862: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5863: 	    return 'not_in_class';
                   5864: 	}
1.620     albertel 5865: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5866: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5867:     } else {
                   5868: 	($cdom,$cnum)=split(/_/,$cid);
                   5869:     }
1.620     albertel 5870:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5871:     if (!$chome) {
1.457     raeburn  5872: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5873:     }
1.455     albertel 5874:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5875:     # Make sure the user exists
1.81      www      5876:     my $uhome=&homeserver($uname,$udom);
                   5877:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5878: 	return 'error: no such user';
                   5879:     }
1.297     matthew  5880:     # Get student data if we were not given enough information
                   5881:     if (!defined($first)  || $first  eq '' || 
                   5882:         !defined($last)   || $last   eq '' || 
                   5883:         !defined($uid)    || $uid    eq '' || 
                   5884:         !defined($middle) || $middle eq '' || 
                   5885:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5886:         # They did not supply us with enough data to enroll the student, so
                   5887:         # we need to pick up more information.
1.297     matthew  5888:         my %tmp = &get('environment',
1.294     matthew  5889:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5890:                        ,$udom,$uname);
                   5891: 
1.800     albertel 5892:         #foreach my $key (keys(%tmp)) {
                   5893:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5894:         #}
1.294     matthew  5895:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5896:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5897:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5898:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5899:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5900:     }
1.556     albertel 5901:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5902:     my $reply=cput('classlist',
                   5903: 		   {"$uname:$udom" => 
1.515     raeburn  5904: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5905: 		   $cdom,$cnum);
1.81      www      5906:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5907: 	return 'error: '.$reply;
1.652     albertel 5908:     } else {
                   5909: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5910:     }
1.297     matthew  5911:     # Add student role to user
1.83      www      5912:     my $uurl='/'.$cid;
1.81      www      5913:     $uurl=~s/\_/\//g;
                   5914:     if ($usec) {
                   5915: 	$uurl.='/'.$usec;
                   5916:     }
1.957     raeburn  5917:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5918: }
                   5919: 
1.556     albertel 5920: sub format_name {
                   5921:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5922:     my $name;
                   5923:     if ($first ne 'lastname') {
                   5924: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5925:     } else {
                   5926: 	if ($lastname=~/\S/) {
                   5927: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5928: 	    $name=~s/\s+,/,/;
                   5929: 	} else {
                   5930: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5931: 	}
                   5932:     }
                   5933:     $name=~s/^\s+//;
                   5934:     $name=~s/\s+$//;
                   5935:     $name=~s/\s+/ /g;
                   5936:     return $name;
                   5937: }
                   5938: 
1.84      www      5939: # ------------------------------------------------- Write to course preferences
                   5940: 
                   5941: sub writecoursepref {
                   5942:     my ($courseid,%prefs)=@_;
                   5943:     $courseid=~s/^\///;
                   5944:     $courseid=~s/\_/\//g;
                   5945:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5946:     my $chome=homeserver($cnum,$cdomain);
                   5947:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5948: 	return 'error: no such course';
                   5949:     }
                   5950:     my $cstring='';
1.800     albertel 5951:     foreach my $pref (keys(%prefs)) {
                   5952: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5953:     }
1.84      www      5954:     $cstring=~s/\&$//;
                   5955:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5956: }
                   5957: 
                   5958: # ---------------------------------------------------------- Make/modify course
                   5959: 
                   5960: sub createcourse {
1.741     raeburn  5961:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5962:         $course_owner,$crstype)=@_;
1.84      www      5963:     $url=&declutter($url);
                   5964:     my $cid='';
1.264     matthew  5965:     unless (&allowed('ccc',$udom)) {
1.84      www      5966:         return 'refused';
                   5967:     }
                   5968: # ------------------------------------------------------------------- Create ID
1.674     www      5969:    my $uname=int(1+rand(9)).
                   5970:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5971:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5972:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5973: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5974:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5975:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5976:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5977:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5978:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5979:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5980:            return 'error: unable to generate unique course-ID';
                   5981:        } 
                   5982:    }
1.264     matthew  5983: # ------------------------------------------------ Check supplied server name
1.620     albertel 5984:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5985:     if (! &is_library($course_server)) {
1.264     matthew  5986:         return 'error:bad server name '.$course_server;
                   5987:     }
1.84      www      5988: # ------------------------------------------------------------- Make the course
                   5989:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5990:                       $course_server);
1.84      www      5991:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5992:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5993:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5994: 	return 'error: no such course';
                   5995:     }
1.271     www      5996: # ----------------------------------------------------------------- Course made
1.516     raeburn  5997: # log existence
1.918     raeburn  5998:     my $newcourse = {
                   5999:                     $udom.'_'.$uname => {
1.921     raeburn  6000:                                      description => $description,
                   6001:                                      inst_code   => $inst_code,
                   6002:                                      owner       => $course_owner,
                   6003:                                      type        => $crstype,
1.918     raeburn  6004:                                                 },
                   6005:                     };
1.921     raeburn  6006:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6007: # set toplevel url
1.271     www      6008:     my $topurl=$url;
                   6009:     unless ($nonstandard) {
                   6010: # ------------------------------------------ For standard courses, make top url
                   6011:         my $mapurl=&clutter($url);
1.278     www      6012:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6013:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6014: <map>
                   6015: <resource id="1" type="start"></resource>
                   6016: <resource id="2" src="$mapurl"></resource>
                   6017: <resource id="3" type="finish"></resource>
                   6018: <link index="1" from="1" to="2"></link>
                   6019: <link index="2" from="2" to="3"></link>
                   6020: </map>
                   6021: ENDINITMAP
                   6022:         $topurl=&declutter(
1.638     albertel 6023:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6024:                           );
                   6025:     }
                   6026: # ----------------------------------------------------------- Write preferences
1.84      www      6027:     &writecoursepref($udom.'_'.$uname,
                   6028:                      ('description' => $description,
1.271     www      6029:                       'url'         => $topurl));
1.84      www      6030:     return '/'.$udom.'/'.$uname;
                   6031: }
                   6032: 
1.813     albertel 6033: sub is_course {
                   6034:     my ($cdom,$cnum) = @_;
                   6035:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6036: 				undef,'.');
1.813     albertel 6037:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6038:         return 1;
                   6039:     }
                   6040:     return 0;
                   6041: }
                   6042: 
1.21      www      6043: # ---------------------------------------------------------- Assign Custom Role
                   6044: 
                   6045: sub assigncustomrole {
1.957     raeburn  6046:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6047:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6048:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6049: }
                   6050: 
                   6051: # ----------------------------------------------------------------- Revoke Role
                   6052: 
                   6053: sub revokerole {
1.957     raeburn  6054:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6055:     my $now=time;
1.965     raeburn  6056:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6057: }
                   6058: 
                   6059: # ---------------------------------------------------------- Revoke Custom Role
                   6060: 
                   6061: sub revokecustomrole {
1.957     raeburn  6062:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6063:     my $now=time;
1.357     www      6064:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6065:            $deleteflag,$selfenroll,$context);
1.17      www      6066: }
                   6067: 
1.533     banghart 6068: # ------------------------------------------------------------ Disk usage
1.535     albertel 6069: sub diskusage {
1.955     raeburn  6070:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6071:     $directorypath =~ s/\/$//;
                   6072:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6073:                        .&escape($getpropath).':'.&escape($uname).':'
                   6074:                        .&escape($udom),homeserver($uname,$udom));
                   6075:     if ($listing eq 'unknown_cmd') {
                   6076:         if ($getpropath) {
                   6077:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6078:         }
                   6079:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6080:     }
1.514     albertel 6081:     return $listing;
1.512     banghart 6082: }
                   6083: 
1.566     banghart 6084: sub is_locked {
                   6085:     my ($file_name, $domain, $user) = @_;
                   6086:     my @check;
                   6087:     my $is_locked;
                   6088:     push @check, $file_name;
1.613     albertel 6089:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6090: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6091:     my ($tmp)=keys(%locked);
                   6092:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6093:     
1.566     banghart 6094:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6095:         $is_locked = 'false';
                   6096:         foreach my $entry (@{$locked{$file_name}}) {
                   6097:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6098:                $is_locked = 'true';
                   6099:                last;
1.745     raeburn  6100:            }
                   6101:        }
1.566     banghart 6102:     } else {
                   6103:         $is_locked = 'false';
                   6104:     }
                   6105: }
                   6106: 
1.759     albertel 6107: sub declutter_portfile {
                   6108:     my ($file) = @_;
1.833     albertel 6109:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6110:     return $file;
                   6111: }
                   6112: 
1.559     banghart 6113: # ------------------------------------------------------------- Mark as Read Only
                   6114: 
                   6115: sub mark_as_readonly {
                   6116:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6117:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6118:     my ($tmp)=keys(%current_permissions);
                   6119:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6120:     foreach my $file (@{$files}) {
1.759     albertel 6121: 	$file = &declutter_portfile($file);
1.561     banghart 6122:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6123:     }
1.613     albertel 6124:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6125:     return;
                   6126: }
                   6127: 
1.572     banghart 6128: # ------------------------------------------------------------Save Selected Files
                   6129: 
                   6130: sub save_selected_files {
                   6131:     my ($user, $path, @files) = @_;
                   6132:     my $filename = $user."savedfiles";
1.573     banghart 6133:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6134:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6135:     foreach my $file (@files) {
1.620     albertel 6136:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6137:     }
                   6138:     foreach my $file (@other_files) {
1.574     banghart 6139:         print (OUT $file."\n");
1.572     banghart 6140:     }
1.574     banghart 6141:     close (OUT);
1.572     banghart 6142:     return 'ok';
                   6143: }
                   6144: 
1.574     banghart 6145: sub clear_selected_files {
                   6146:     my ($user) = @_;
                   6147:     my $filename = $user."savedfiles";
                   6148:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6149:     print (OUT undef);
                   6150:     close (OUT);
                   6151:     return ("ok");    
                   6152: }
                   6153: 
1.572     banghart 6154: sub files_in_path {
                   6155:     my ($user, $path) = @_;
                   6156:     my $filename = $user."savedfiles";
                   6157:     my %return_files;
1.574     banghart 6158:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6159:     while (my $line_in = <IN>) {
1.574     banghart 6160:         chomp ($line_in);
                   6161:         my @paths_and_file = split (m!/!, $line_in);
                   6162:         my $file_part = pop (@paths_and_file);
                   6163:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6164:         $path_part.='/';
                   6165:         my $path_and_file = $path_part.$file_part;
                   6166:         if ($path_part eq $path) {
                   6167:             $return_files{$file_part}= 'selected';
                   6168:         }
                   6169:     }
1.574     banghart 6170:     close (IN);
                   6171:     return (\%return_files);
1.572     banghart 6172: }
                   6173: 
                   6174: # called in portfolio select mode, to show files selected NOT in current directory
                   6175: sub files_not_in_path {
                   6176:     my ($user, $path) = @_;
                   6177:     my $filename = $user."savedfiles";
                   6178:     my @return_files;
                   6179:     my $path_part;
1.800     albertel 6180:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6181:     while (my $line = <IN>) {
1.572     banghart 6182:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6183:         my @paths_and_file = split(m|/|, $line);
                   6184:         my $file_part = pop(@paths_and_file);
                   6185:         chomp($file_part);
                   6186:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6187:         $path_part .= '/';
                   6188:         my $path_and_file = $path_part.$file_part;
                   6189:         if ($path_part ne $path) {
1.800     albertel 6190:             push(@return_files, ($path_and_file));
1.572     banghart 6191:         }
                   6192:     }
1.800     albertel 6193:     close(OUT);
1.574     banghart 6194:     return (@return_files);
1.572     banghart 6195: }
                   6196: 
1.745     raeburn  6197: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6198: 
1.745     raeburn  6199: sub get_portfile_permissions {
                   6200:     my ($domain,$user) = @_;
1.613     albertel 6201:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6202:     my ($tmp)=keys(%current_permissions);
                   6203:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6204:     return \%current_permissions;
                   6205: }
                   6206: 
                   6207: #---------------------------------------------Get portfolio file access controls
                   6208: 
1.749     raeburn  6209: sub get_access_controls {
1.745     raeburn  6210:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6211:     my %access;
                   6212:     my $real_file = $file;
                   6213:     $file =~ s/\.meta$//;
1.745     raeburn  6214:     if (defined($file)) {
1.749     raeburn  6215:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6216:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6217:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6218:             }
                   6219:         }
1.745     raeburn  6220:     } else {
1.749     raeburn  6221:         foreach my $key (keys(%{$current_permissions})) {
                   6222:             if ($key =~ /\0accesscontrol$/) {
                   6223:                 if (defined($group)) {
                   6224:                     if ($key !~ m-^\Q$group\E/-) {
                   6225:                         next;
                   6226:                     }
                   6227:                 }
                   6228:                 my ($fullpath) = split(/\0/,$key);
                   6229:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6230:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6231:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6232:                     }
                   6233:                 }
                   6234:             }
                   6235:         }
                   6236:     }
                   6237:     return %access;
                   6238: }
                   6239: 
                   6240: sub modify_access_controls {
                   6241:     my ($file_name,$changes,$domain,$user)=@_;
                   6242:     my ($outcome,$deloutcome);
                   6243:     my %store_permissions;
                   6244:     my %new_values;
                   6245:     my %new_control;
                   6246:     my %translation;
                   6247:     my @deletions = ();
                   6248:     my $now = time;
                   6249:     if (exists($$changes{'activate'})) {
                   6250:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6251:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6252:             my $numnew = scalar(@newitems);
                   6253:             for (my $i=0; $i<$numnew; $i++) {
                   6254:                 my $newkey = $newitems[$i];
                   6255:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6256:                 if ($newkey =~ /^\d+:/) { 
                   6257:                     $newkey =~ s/^(\d+)/$newid/;
                   6258:                     $translation{$1} = $newid;
                   6259:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6260:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6261:                     $translation{$1} = $newid;
                   6262:                 }
1.749     raeburn  6263:                 $new_values{$file_name."\0".$newkey} = 
                   6264:                                           $$changes{'activate'}{$newitems[$i]};
                   6265:                 $new_control{$newkey} = $now;
                   6266:             }
                   6267:         }
                   6268:     }
                   6269:     my %todelete;
                   6270:     my %changed_items;
                   6271:     foreach my $action ('delete','update') {
                   6272:         if (exists($$changes{$action})) {
                   6273:             if (ref($$changes{$action}) eq 'HASH') {
                   6274:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6275:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6276:                     if ($action eq 'delete') { 
                   6277:                         $todelete{$itemnum} = 1;
                   6278:                     } else {
                   6279:                         $changed_items{$itemnum} = $key;
                   6280:                     }
                   6281:                 }
1.745     raeburn  6282:             }
                   6283:         }
1.749     raeburn  6284:     }
                   6285:     # get lock on access controls for file.
                   6286:     my $lockhash = {
                   6287:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6288:                                                        ':'.$env{'user.domain'},
                   6289:                    }; 
                   6290:     my $tries = 0;
                   6291:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6292:    
                   6293:     while (($gotlock ne 'ok') && $tries <3) {
                   6294:         $tries ++;
                   6295:         sleep 1;
                   6296:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6297:     }
                   6298:     if ($gotlock eq 'ok') {
                   6299:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6300:         my ($tmp)=keys(%curr_permissions);
                   6301:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6302:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6303:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6304:             if (ref($curr_controls) eq 'HASH') {
                   6305:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6306:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6307:                     if (defined($todelete{$itemnum})) {
                   6308:                         push(@deletions,$file_name."\0".$control_item);
                   6309:                     } else {
                   6310:                         if (defined($changed_items{$itemnum})) {
                   6311:                             $new_control{$changed_items{$itemnum}} = $now;
                   6312:                             push(@deletions,$file_name."\0".$control_item);
                   6313:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6314:                         } else {
                   6315:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6316:                         }
                   6317:                     }
1.745     raeburn  6318:                 }
                   6319:             }
                   6320:         }
1.970     raeburn  6321:         my ($group);
                   6322:         if (&is_course($domain,$user)) {
                   6323:             ($group,my $file) = split(/\//,$file_name,2);
                   6324:         }
1.749     raeburn  6325:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6326:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6327:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6328:         #  remove lock
                   6329:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6330:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6331:         my $sqlresult =
1.970     raeburn  6332:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6333:                                     $group);
1.749     raeburn  6334:     } else {
                   6335:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6336:     }
1.749     raeburn  6337:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6338: }
                   6339: 
1.827     raeburn  6340: sub make_public_indefinitely {
                   6341:     my ($requrl) = @_;
                   6342:     my $now = time;
                   6343:     my $action = 'activate';
                   6344:     my $aclnum = 0;
                   6345:     if (&is_portfolio_url($requrl)) {
                   6346:         my (undef,$udom,$unum,$file_name,$group) =
                   6347:             &parse_portfolio_url($requrl);
                   6348:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6349:         my %access_controls = &get_access_controls($current_perms,
                   6350:                                                    $group,$file_name);
                   6351:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6352:             my ($num,$scope,$end,$start) = 
                   6353:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6354:             if ($scope eq 'public') {
                   6355:                 if ($start <= $now && $end == 0) {
                   6356:                     $action = 'none';
                   6357:                 } else {
                   6358:                     $action = 'update';
                   6359:                     $aclnum = $num;
                   6360:                 }
                   6361:                 last;
                   6362:             }
                   6363:         }
                   6364:         if ($action eq 'none') {
                   6365:              return 'ok';
                   6366:         } else {
                   6367:             my %changes;
                   6368:             my $newend = 0;
                   6369:             my $newstart = $now;
                   6370:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6371:             $changes{$action}{$newkey} = {
                   6372:                 type => 'public',
                   6373:                 time => {
                   6374:                     start => $newstart,
                   6375:                     end   => $newend,
                   6376:                 },
                   6377:             };
                   6378:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6379:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6380:             return $outcome;
                   6381:         }
                   6382:     } else {
                   6383:         return 'invalid';
                   6384:     }
                   6385: }
                   6386: 
1.745     raeburn  6387: #------------------------------------------------------Get Marked as Read Only
                   6388: 
                   6389: sub get_marked_as_readonly {
                   6390:     my ($domain,$user,$what,$group) = @_;
                   6391:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6392:     my @readonly_files;
1.629     banghart 6393:     my $cmp1=$what;
                   6394:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6395:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6396:         if (defined($group)) {
                   6397:             if ($file_name !~ m-^\Q$group\E/-) {
                   6398:                 next;
                   6399:             }
                   6400:         }
1.561     banghart 6401:         if (ref($value) eq "ARRAY"){
                   6402:             foreach my $stored_what (@{$value}) {
1.629     banghart 6403:                 my $cmp2=$stored_what;
1.759     albertel 6404:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6405:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6406:                 }
1.629     banghart 6407:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6408:                     push(@readonly_files, $file_name);
1.745     raeburn  6409:                     last;
1.563     banghart 6410:                 } elsif (!defined($what)) {
                   6411:                     push(@readonly_files, $file_name);
1.745     raeburn  6412:                     last;
1.561     banghart 6413:                 }
                   6414:             }
1.745     raeburn  6415:         }
1.561     banghart 6416:     }
                   6417:     return @readonly_files;
                   6418: }
1.577     banghart 6419: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6420: 
1.577     banghart 6421: sub get_marked_as_readonly_hash {
1.745     raeburn  6422:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6423:     my %readonly_files;
1.745     raeburn  6424:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6425:         if (defined($group)) {
                   6426:             if ($file_name !~ m-^\Q$group\E/-) {
                   6427:                 next;
                   6428:             }
                   6429:         }
1.577     banghart 6430:         if (ref($value) eq "ARRAY"){
                   6431:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6432:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6433:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6434:                         if ($lock_descriptor eq 'graded') {
                   6435:                             $readonly_files{$file_name} = 'graded';
                   6436:                         } elsif ($lock_descriptor eq 'handback') {
                   6437:                             $readonly_files{$file_name} = 'handback';
                   6438:                         } else {
                   6439:                             if (!exists($readonly_files{$file_name})) {
                   6440:                                 $readonly_files{$file_name} = 'locked';
                   6441:                             }
                   6442:                         }
1.745     raeburn  6443:                     }
1.750     banghart 6444:                 } 
1.577     banghart 6445:             }
                   6446:         } 
                   6447:     }
                   6448:     return %readonly_files;
                   6449: }
1.559     banghart 6450: # ------------------------------------------------------------ Unmark as Read Only
                   6451: 
                   6452: sub unmark_as_readonly {
1.629     banghart 6453:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6454:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6455:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6456:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6457:     my $symb_crs = $what;
                   6458:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6459:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6460:     my ($tmp)=keys(%current_permissions);
                   6461:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6462:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6463:     foreach my $file (@readonly_files) {
1.759     albertel 6464: 	my $clean_file = &declutter_portfile($file);
                   6465: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6466: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6467:         my @new_locks;
                   6468:         my @del_keys;
                   6469:         if (ref($current_locks) eq "ARRAY"){
                   6470:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6471:                 my $compare=$locker;
1.749     raeburn  6472:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6473:                     $compare=join('',@{$locker});
1.746     raeburn  6474:                     if ($compare ne $symb_crs) {
                   6475:                         push(@new_locks, $locker);
                   6476:                     }
1.563     banghart 6477:                 }
                   6478:             }
1.650     albertel 6479:             if (scalar(@new_locks) > 0) {
1.563     banghart 6480:                 $current_permissions{$file} = \@new_locks;
                   6481:             } else {
                   6482:                 push(@del_keys, $file);
1.613     albertel 6483:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6484:                 delete($current_permissions{$file});
1.563     banghart 6485:             }
                   6486:         }
1.561     banghart 6487:     }
1.613     albertel 6488:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6489:     return;
                   6490: }
1.512     banghart 6491: 
1.17      www      6492: # ------------------------------------------------------------ Directory lister
                   6493: 
                   6494: sub dirlist {
1.955     raeburn  6495:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6496:     $uri=~s/^\///;
                   6497:     $uri=~s/\/$//;
1.253     stredwic 6498:     my ($udom, $uname);
1.955     raeburn  6499:     if ($getuserdir) {
1.253     stredwic 6500:         $udom = $userdomain;
                   6501:         $uname = $username;
1.955     raeburn  6502:     } else {
                   6503:         (undef,$udom,$uname)=split(/\//,$uri);
                   6504:         if(defined($userdomain)) {
                   6505:             $udom = $userdomain;
                   6506:         }
                   6507:         if(defined($username)) {
                   6508:             $uname = $username;
                   6509:         }
1.253     stredwic 6510:     }
1.955     raeburn  6511:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6512: 
1.955     raeburn  6513:     $dirRoot = $perlvar{'lonDocRoot'};
                   6514:     if (defined($getpropath)) {
                   6515:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6516:         $dirRoot =~ s/\/$//;
1.955     raeburn  6517:     } elsif (defined($getuserdir)) {
                   6518:         my $subdir=$uname.'__';
                   6519:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6520:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6521:                    ."/$udom/$subdir/$uname";
                   6522:     } elsif (defined($alternateRoot)) {
                   6523:         $dirRoot = $alternateRoot;
1.751     banghart 6524:     }
1.253     stredwic 6525: 
                   6526:     if($udom) {
                   6527:         if($uname) {
1.955     raeburn  6528:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6529:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6530:                               .':'.&escape($uname).':'.&escape($udom),
                   6531:                               &homeserver($uname,$udom));
                   6532:             if ($listing eq 'unknown_cmd') {
                   6533:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6534:                                   &homeserver($uname,$udom));
                   6535:             } else {
                   6536:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6537:             }
1.605     matthew  6538:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6539:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6540: 				  &homeserver($uname,$udom));
1.605     matthew  6541:                 @listing_results = split(/:/,$listing);
                   6542:             } else {
                   6543:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6544:             }
                   6545:             return @listing_results;
1.955     raeburn  6546:         } elsif(!$alternateRoot) {
1.800     albertel 6547:             my %allusers;
1.841     albertel 6548: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6549:  	    foreach my $tryserver (keys(%servers)) {
                   6550:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6551:                                   &escape($udom),$tryserver);
                   6552:                 if ($listing eq 'unknown_cmd') {
                   6553: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6554: 				      $udom, $tryserver);
                   6555:                 } else {
                   6556:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6557:                 }
1.841     albertel 6558: 		if ($listing eq 'unknown_cmd') {
                   6559: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6560: 				      $udom, $tryserver);
                   6561: 		    @listing_results = split(/:/,$listing);
                   6562: 		} else {
                   6563: 		    @listing_results =
                   6564: 			map { &unescape($_); } split(/:/,$listing);
                   6565: 		}
                   6566: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6567: 		    $listing_results[0] ne 'empty'       &&
                   6568: 		    $listing_results[0] ne 'con_lost') {
                   6569: 		    foreach my $line (@listing_results) {
                   6570: 			my ($entry) = split(/&/,$line,2);
                   6571: 			$allusers{$entry} = 1;
                   6572: 		    }
                   6573: 		}
1.253     stredwic 6574:             }
                   6575:             my $alluserstr='';
1.800     albertel 6576:             foreach my $user (sort(keys(%allusers))) {
                   6577:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6578:             }
                   6579:             $alluserstr=~s/:$//;
                   6580:             return split(/:/,$alluserstr);
                   6581:         } else {
1.800     albertel 6582:             return ('missing user name');
1.253     stredwic 6583:         }
1.955     raeburn  6584:     } elsif(!defined($getpropath)) {
1.841     albertel 6585:         my @all_domains = sort(&all_domains());
1.955     raeburn  6586:         foreach my $domain (@all_domains) {
                   6587:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6588:         }
                   6589:         return @all_domains;
                   6590:     } else {
1.800     albertel 6591:         return ('missing domain');
1.275     stredwic 6592:     }
                   6593: }
                   6594: 
                   6595: # --------------------------------------------- GetFileTimestamp
                   6596: # This function utilizes dirlist and returns the date stamp for
                   6597: # when it was last modified.  It will also return an error of -1
                   6598: # if an error occurs
                   6599: 
                   6600: sub GetFileTimestamp {
1.955     raeburn  6601:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6602:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6603:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6604:     my ($fileStat) = 
                   6605:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6606:                                  undef,$getuserdir);
1.275     stredwic 6607:     my @stats = split('&', $fileStat);
                   6608:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6609:         # @stats contains first the filename, then the stat output
                   6610:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6611:     } else {
                   6612:         return -1;
1.253     stredwic 6613:     }
1.26      www      6614: }
                   6615: 
1.712     albertel 6616: sub stat_file {
                   6617:     my ($uri) = @_;
1.787     albertel 6618:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6619: 
1.955     raeburn  6620:     my ($udom,$uname,$file);
1.712     albertel 6621:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6622: 	($udom,$uname,$file) =
1.811     albertel 6623: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6624: 	$file = 'userfiles/'.$file;
                   6625:     }
                   6626:     if ($uri =~ m-^/res/-) {
                   6627: 	($udom,$uname) = 
1.807     albertel 6628: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6629: 	$file = $uri;
                   6630:     }
                   6631: 
                   6632:     if (!$udom || !$uname || !$file) {
                   6633: 	# unable to handle the uri
                   6634: 	return ();
                   6635:     }
1.956     raeburn  6636:     my $getpropath;
                   6637:     if ($file =~ /^userfiles\//) {
                   6638:         $getpropath = 1;
                   6639:     }
1.955     raeburn  6640:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6641:     my @stats = split('&', $result);
1.721     banghart 6642:     
1.712     albertel 6643:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6644: 	shift(@stats); #filename is first
                   6645: 	return @stats;
                   6646:     }
                   6647:     return ();
                   6648: }
                   6649: 
1.26      www      6650: # -------------------------------------------------------- Value of a Condition
                   6651: 
1.713     albertel 6652: # gets the value of a specific preevaluated condition
                   6653: #    stored in the string  $env{user.state.<cid>}
                   6654: # or looks up a condition reference in the bighash and if if hasn't
                   6655: # already been evaluated recurses into docondval to get the value of
                   6656: # the condition, then memoizing it to 
                   6657: #   $env{user.state.<cid>.<condition>}
1.40      www      6658: sub directcondval {
                   6659:     my $number=shift;
1.620     albertel 6660:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6661: 	&Apache::lonuserstate::evalstate();
                   6662:     }
1.713     albertel 6663:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6664: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6665:     } elsif ($number =~ /^_/) {
                   6666: 	my $sub_condition;
                   6667: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6668: 		&GDBM_READER(),0640)) {
                   6669: 	    $sub_condition=$bighash{'conditions'.$number};
                   6670: 	    untie(%bighash);
                   6671: 	}
                   6672: 	my $value = &docondval($sub_condition);
1.949     raeburn  6673: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6674: 	return $value;
                   6675:     }
1.620     albertel 6676:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6677:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6678:     } else {
                   6679:        return 2;
                   6680:     }
                   6681: }
                   6682: 
1.713     albertel 6683: # get the collection of conditions for this resource
1.26      www      6684: sub condval {
                   6685:     my $condidx=shift;
1.54      www      6686:     my $allpathcond='';
1.713     albertel 6687:     foreach my $cond (split(/\|/,$condidx)) {
                   6688: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6689: 	    $allpathcond.=
                   6690: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6691: 	}
1.191     harris41 6692:     }
1.54      www      6693:     $allpathcond=~s/\|$//;
1.713     albertel 6694:     return &docondval($allpathcond);
                   6695: }
                   6696: 
                   6697: #evaluates an expression of conditions
                   6698: sub docondval {
                   6699:     my ($allpathcond) = @_;
                   6700:     my $result=0;
                   6701:     if ($env{'request.course.id'}
                   6702: 	&& defined($allpathcond)) {
                   6703: 	my $operand='|';
                   6704: 	my @stack;
                   6705: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6706: 	    if ($chunk eq '(') {
                   6707: 		push @stack,($operand,$result);
                   6708: 	    } elsif ($chunk eq ')') {
                   6709: 		my $before=pop @stack;
                   6710: 		if (pop @stack eq '&') {
                   6711: 		    $result=$result>$before?$before:$result;
                   6712: 		} else {
                   6713: 		    $result=$result>$before?$result:$before;
                   6714: 		}
                   6715: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6716: 		$operand=$chunk;
                   6717: 	    } else {
                   6718: 		my $new=directcondval($chunk);
                   6719: 		if ($operand eq '&') {
                   6720: 		    $result=$result>$new?$new:$result;
                   6721: 		} else {
                   6722: 		    $result=$result>$new?$result:$new;
                   6723: 		}
                   6724: 	    }
                   6725: 	}
1.26      www      6726:     }
                   6727:     return $result;
1.421     albertel 6728: }
                   6729: 
                   6730: # ---------------------------------------------------- Devalidate courseresdata
                   6731: 
                   6732: sub devalidatecourseresdata {
                   6733:     my ($coursenum,$coursedomain)=@_;
                   6734:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6735:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6736: }
                   6737: 
1.763     www      6738: 
1.200     www      6739: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6740: #
                   6741: #  Parameters:
                   6742: #      $coursenum    - Number of the course.
                   6743: #      $coursedomain - Domain at which the course was created.
                   6744: #  Returns:
                   6745: #     A hash of the course parameters along (I think) with timestamps
                   6746: #     and version info.
1.877     foxr     6747: 
1.624     albertel 6748: sub get_courseresdata {
                   6749:     my ($coursenum,$coursedomain)=@_;
1.200     www      6750:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6751:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6752:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6753:     my %dumpreply;
1.417     albertel 6754:     unless (defined($cached)) {
1.624     albertel 6755: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6756: 	$result=\%dumpreply;
1.251     albertel 6757: 	my ($tmp) = keys(%dumpreply);
                   6758: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6759: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6760: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6761: 	    return $tmp;
1.416     albertel 6762: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6763: 	    $result=undef;
1.599     albertel 6764: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6765: 	}
                   6766:     }
1.624     albertel 6767:     return $result;
                   6768: }
                   6769: 
1.633     albertel 6770: sub devalidateuserresdata {
                   6771:     my ($uname,$udom)=@_;
                   6772:     my $hashid="$udom:$uname";
                   6773:     &devalidate_cache_new('userres',$hashid);
                   6774: }
                   6775: 
1.624     albertel 6776: sub get_userresdata {
                   6777:     my ($uname,$udom)=@_;
                   6778:     #most student don\'t have any data set, check if there is some data
                   6779:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6780: 
                   6781:     my $hashid="$udom:$uname";
                   6782:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6783:     if (!defined($cached)) {
                   6784: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6785: 	$result=\%resourcedata;
                   6786: 	&do_cache_new('userres',$hashid,$result,600);
                   6787:     }
                   6788:     my ($tmp)=keys(%$result);
                   6789:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6790: 	return $result;
                   6791:     }
                   6792:     #error 2 occurs when the .db doesn't exist
                   6793:     if ($tmp!~/error: 2 /) {
1.672     albertel 6794: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6795: 		 " Trying to get resource data for ".
                   6796: 		 $uname." at ".$udom.": ".
                   6797: 		 $tmp."</font>");
                   6798:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6799: 	#&EXT_cache_set($udom,$uname);
                   6800: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6801: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6802:     }
                   6803:     return $tmp;
                   6804: }
1.879     foxr     6805: #----------------------------------------------- resdata - return resource data
                   6806: #  Purpose:
                   6807: #    Return resource data for either users or for a course.
                   6808: #  Parameters:
                   6809: #     $name      - Course/user name.
                   6810: #     $domain    - Name of the domain the user/course is registered on.
                   6811: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6812: #     @which     - Array of names of resources desired.
                   6813: #  Returns:
                   6814: #     The value of the first reasource in @which that is found in the
                   6815: #     resource hash.
                   6816: #  Exceptional Conditions:
                   6817: #     If the $type passed in is not valid (not the string 'course' or 
                   6818: #     'user', an undefined  reference is returned.
                   6819: #     If none of the resources are found, an undef is returned
1.624     albertel 6820: sub resdata {
                   6821:     my ($name,$domain,$type,@which)=@_;
                   6822:     my $result;
                   6823:     if ($type eq 'course') {
                   6824: 	$result=&get_courseresdata($name,$domain);
                   6825:     } elsif ($type eq 'user') {
                   6826: 	$result=&get_userresdata($name,$domain);
                   6827:     }
                   6828:     if (!ref($result)) { return $result; }    
1.251     albertel 6829:     foreach my $item (@which) {
1.927     albertel 6830: 	if (defined($result->{$item->[0]})) {
                   6831: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6832: 	}
1.250     albertel 6833:     }
1.291     albertel 6834:     return undef;
1.200     www      6835: }
                   6836: 
1.379     matthew  6837: #
                   6838: # EXT resource caching routines
                   6839: #
                   6840: 
                   6841: sub clear_EXT_cache_status {
1.383     albertel 6842:     &delenv('cache.EXT.');
1.379     matthew  6843: }
                   6844: 
                   6845: sub EXT_cache_status {
                   6846:     my ($target_domain,$target_user) = @_;
1.383     albertel 6847:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6848:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6849:         # We know already the user has no data
                   6850:         return 1;
                   6851:     } else {
                   6852:         return 0;
                   6853:     }
                   6854: }
                   6855: 
                   6856: sub EXT_cache_set {
                   6857:     my ($target_domain,$target_user) = @_;
1.383     albertel 6858:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6859:     #&appenv({$cachename => time});
1.379     matthew  6860: }
                   6861: 
1.28      www      6862: # --------------------------------------------------------- Value of a Variable
1.58      www      6863: sub EXT {
1.715     albertel 6864: 
1.395     albertel 6865:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6866:     unless ($varname) { return ''; }
1.218     albertel 6867:     #get real user name/domain, courseid and symb
                   6868:     my $courseid;
1.359     albertel 6869:     my $publicuser;
1.427     www      6870:     if ($symbparm) {
                   6871: 	$symbparm=&get_symb_from_alias($symbparm);
                   6872:     }
1.218     albertel 6873:     if (!($uname && $udom)) {
1.790     albertel 6874:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6875:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6876:     } else {
1.620     albertel 6877: 	$courseid=$env{'request.course.id'};
1.218     albertel 6878:     }
1.48      www      6879:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6880:     my $rest;
1.320     albertel 6881:     if (defined($therest[0])) {
1.48      www      6882:        $rest=join('.',@therest);
                   6883:     } else {
                   6884:        $rest='';
                   6885:     }
1.320     albertel 6886: 
1.57      www      6887:     my $qualifierrest=$qualifier;
                   6888:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6889:     my $spacequalifierrest=$space;
                   6890:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6891:     if ($realm eq 'user') {
1.48      www      6892: # --------------------------------------------------------------- user.resource
                   6893: 	if ($space eq 'resource') {
1.651     albertel 6894: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6895: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6896: 		 &&
1.744     albertel 6897: 		 ($symbparm eq &symbread()) ) {	
                   6898: 		# if we are in the middle of processing the resource the
                   6899: 		# get the value we are planning on committing
                   6900:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6901:                     return $Apache::lonhomework::results{$qualifierrest};
                   6902:                 } else {
                   6903:                     return $Apache::lonhomework::history{$qualifierrest};
                   6904:                 }
1.335     albertel 6905: 	    } else {
1.359     albertel 6906: 		my %restored;
1.620     albertel 6907: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6908: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6909: 		} else {
                   6910: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6911: 		}
1.335     albertel 6912: 		return $restored{$qualifierrest};
                   6913: 	    }
1.48      www      6914: # ----------------------------------------------------------------- user.access
                   6915:         } elsif ($space eq 'access') {
1.218     albertel 6916: 	    # FIXME - not supporting calls for a specific user
1.48      www      6917:             return &allowed($qualifier,$rest);
                   6918: # ------------------------------------------ user.preferences, user.environment
                   6919:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6920: 	    if (($uname eq $env{'user.name'}) &&
                   6921: 		($udom eq $env{'user.domain'})) {
                   6922: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6923: 	    } else {
1.359     albertel 6924: 		my %returnhash;
                   6925: 		if (!$publicuser) {
                   6926: 		    %returnhash=&userenvironment($udom,$uname,
                   6927: 						 $qualifierrest);
                   6928: 		}
1.218     albertel 6929: 		return $returnhash{$qualifierrest};
                   6930: 	    }
1.48      www      6931: # ----------------------------------------------------------------- user.course
                   6932:         } elsif ($space eq 'course') {
1.218     albertel 6933: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6934:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6935: # ------------------------------------------------------------------- user.role
                   6936:         } elsif ($space eq 'role') {
1.218     albertel 6937: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6938:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6939:             if ($qualifier eq 'value') {
                   6940: 		return $role;
                   6941:             } elsif ($qualifier eq 'extent') {
                   6942:                 return $where;
                   6943:             }
                   6944: # ----------------------------------------------------------------- user.domain
                   6945:         } elsif ($space eq 'domain') {
1.218     albertel 6946:             return $udom;
1.48      www      6947: # ------------------------------------------------------------------- user.name
                   6948:         } elsif ($space eq 'name') {
1.218     albertel 6949:             return $uname;
1.48      www      6950: # ---------------------------------------------------- Any other user namespace
1.29      www      6951:         } else {
1.359     albertel 6952: 	    my %reply;
                   6953: 	    if (!$publicuser) {
                   6954: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6955: 	    }
                   6956: 	    return $reply{$qualifierrest};
1.48      www      6957:         }
1.236     www      6958:     } elsif ($realm eq 'query') {
                   6959: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6960:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6961: 						[$spacequalifierrest]);
1.620     albertel 6962: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6963:    } elsif ($realm eq 'request') {
1.48      www      6964: # ------------------------------------------------------------- request.browser
                   6965:         if ($space eq 'browser') {
1.430     www      6966: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6967: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6968: 		    return 1;
                   6969: 		} else {
                   6970: 		    return 0;
                   6971: 		}
                   6972: 	    } else {
1.620     albertel 6973: 		return $env{'browser.'.$qualifier};
1.430     www      6974: 	    }
1.57      www      6975: # ------------------------------------------------------------ request.filename
                   6976:         } else {
1.620     albertel 6977:             return $env{'request.'.$spacequalifierrest};
1.29      www      6978:         }
1.28      www      6979:     } elsif ($realm eq 'course') {
1.48      www      6980: # ---------------------------------------------------------- course.description
1.620     albertel 6981:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6982:     } elsif ($realm eq 'resource') {
1.165     www      6983: 
1.620     albertel 6984: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6985: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6986: 	}
1.693     albertel 6987: 
                   6988: 	if ($space eq 'title') {
                   6989: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6990: 	    return &gettitle($symbparm);
                   6991: 	}
                   6992: 	
                   6993: 	if ($space eq 'map') {
                   6994: 	    my ($map) = &decode_symb($symbparm);
                   6995: 	    return &symbread($map);
                   6996: 	}
1.905     albertel 6997: 	if ($space eq 'filename') {
                   6998: 	    if ($symbparm) {
                   6999: 		return &clutter((&decode_symb($symbparm))[2]);
                   7000: 	    }
                   7001: 	    return &hreflocation('',$env{'request.filename'});
                   7002: 	}
1.693     albertel 7003: 
                   7004: 	my ($section, $group, @groups);
1.593     albertel 7005: 	my ($courselevelm,$courselevel);
1.539     albertel 7006: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7007: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7008: 
1.218     albertel 7009: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7010: 
1.60      www      7011: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7012: 	    my $symbp=$symbparm;
1.735     albertel 7013: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7014: 
                   7015: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7016: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7017: 
1.620     albertel 7018: 	    if (($env{'user.name'} eq $uname) &&
                   7019: 		($env{'user.domain'} eq $udom)) {
                   7020: 		$section=$env{'request.course.sec'};
1.733     raeburn  7021:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7022:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7023: 	    } else {
1.539     albertel 7024: 		if (! defined($usection)) {
1.551     albertel 7025: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7026: 		} else {
                   7027: 		    $section = $usection;
                   7028: 		}
1.733     raeburn  7029:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7030: 	    }
                   7031: 
                   7032: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7033: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7034: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7035: 
1.593     albertel 7036: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7037: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7038: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7039: 
1.60      www      7040: # ----------------------------------------------------------- first, check user
1.624     albertel 7041: 
                   7042: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7043: 				       ([$courselevelr,'resource'],
                   7044: 					[$courselevelm,'map'     ],
                   7045: 					[$courselevel, 'course'  ]));
1.931     albertel 7046: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7047: 
1.594     albertel 7048: # ------------------------------------------------ second, check some of course
1.684     raeburn  7049:             my $coursereply;
1.691     raeburn  7050:             if (@groups > 0) {
                   7051:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7052:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7053:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7054:             }
1.96      www      7055: 
1.684     raeburn  7056: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7057: 				  $env{'course.'.$courseid.'.domain'},
                   7058: 				  'course',
                   7059: 				  ([$seclevelr,   'resource'],
                   7060: 				   [$seclevelm,   'map'     ],
                   7061: 				   [$seclevel,    'course'  ],
                   7062: 				   [$courselevelr,'resource']));
                   7063: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7064: 
1.60      www      7065: # ------------------------------------------------------ third, check map parms
1.218     albertel 7066: 	    my %parmhash=();
                   7067: 	    my $thisparm='';
                   7068: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7069: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7070: 		    &GDBM_READER(),0640)) {
1.218     albertel 7071: 		$thisparm=$parmhash{$symbparm};
                   7072: 		untie(%parmhash);
                   7073: 	    }
1.927     albertel 7074: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7075: 	}
1.594     albertel 7076: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7077: 
1.218     albertel 7078: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7079: 	my $filename;
                   7080: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7081: 	if ($symbparm) {
1.409     www      7082: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7083: 	} else {
1.620     albertel 7084: 	    $filename=$env{'request.filename'};
1.282     albertel 7085: 	}
                   7086: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7087: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7088: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7089: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7090: 
1.927     albertel 7091: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7092: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7093: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7094: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7095: 				     $env{'course.'.$courseid.'.domain'},
                   7096: 				     'course',
1.927     albertel 7097: 				     ([$courselevelm,'map'   ],
                   7098: 				      [$courselevel, 'course']));
                   7099: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7100: 	}
1.145     www      7101: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7102: 	unless ($space eq '0') {
1.336     albertel 7103: 	    my @parts=split(/_/,$space);
                   7104: 	    my $id=pop(@parts);
                   7105: 	    my $part=join('_',@parts);
                   7106: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7107: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7108: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7109: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7110: 	}
1.395     albertel 7111: 	if ($recurse) { return undef; }
                   7112: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7113: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7114: # ---------------------------------------------------- Any other user namespace
                   7115:     } elsif ($realm eq 'environment') {
                   7116: # ----------------------------------------------------------------- environment
1.620     albertel 7117: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7118: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7119: 	} else {
1.770     albertel 7120: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7121: 		return '';
                   7122: 	    }
1.219     albertel 7123: 	    my %returnhash=&userenvironment($udom,$uname,
                   7124: 					    $spacequalifierrest);
                   7125: 	    return $returnhash{$spacequalifierrest};
                   7126: 	}
1.28      www      7127:     } elsif ($realm eq 'system') {
1.48      www      7128: # ----------------------------------------------------------------- system.time
                   7129: 	if ($space eq 'time') {
                   7130: 	    return time;
                   7131:         }
1.696     albertel 7132:     } elsif ($realm eq 'server') {
                   7133: # ----------------------------------------------------------------- system.time
                   7134: 	if ($space eq 'name') {
                   7135: 	    return $ENV{'SERVER_NAME'};
                   7136:         }
1.28      www      7137:     }
1.48      www      7138:     return '';
1.61      www      7139: }
                   7140: 
1.927     albertel 7141: sub get_reply {
                   7142:     my ($reply_value) = @_;
1.940     raeburn  7143:     if (ref($reply_value) eq 'ARRAY') {
                   7144:         if (wantarray) {
                   7145: 	    return @$reply_value;
                   7146:         }
                   7147:         return $reply_value->[0];
                   7148:     } else {
                   7149:         return $reply_value;
1.927     albertel 7150:     }
                   7151: }
                   7152: 
1.691     raeburn  7153: sub check_group_parms {
                   7154:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7155:     my @groupitems = ();
                   7156:     my $resultitem;
1.927     albertel 7157:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7158:     foreach my $group (@{$groups}) {
                   7159:         foreach my $level (@levels) {
1.927     albertel 7160:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7161:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7162:         }
                   7163:     }
                   7164:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7165:                             $env{'course.'.$courseid.'.domain'},
                   7166:                                      'course',@groupitems);
                   7167:     return $coursereply;
                   7168: }
                   7169: 
                   7170: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7171:     my ($courseid,@groups) = @_;
                   7172:     @groups = sort(@groups);
1.691     raeburn  7173:     return @groups;
                   7174: }
                   7175: 
1.395     albertel 7176: sub packages_tab_default {
                   7177:     my ($uri,$varname)=@_;
                   7178:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7179: 
                   7180:     my (@extension,@specifics,$do_default);
                   7181:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7182: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7183: 	if ($pack_type eq 'default') {
                   7184: 	    $do_default=1;
                   7185: 	} elsif ($pack_type eq 'extension') {
                   7186: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7187: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7188: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7189: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7190: 	}
                   7191:     }
                   7192:     # first look for a package that matches the requested part id
                   7193:     foreach my $package (@specifics) {
                   7194: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7195: 	next if ($pack_part ne $part);
                   7196: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7197: 	    return $packagetab{"$pack_type&$name&default"};
                   7198: 	}
                   7199:     }
                   7200:     # look for any possible matching non extension_ package
                   7201:     foreach my $package (@specifics) {
                   7202: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7203: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7204: 	    return $packagetab{"$pack_type&$name&default"};
                   7205: 	}
1.585     albertel 7206: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7207: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7208: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7209: 	}
                   7210:     }
1.738     albertel 7211:     # look for any posible extension_ match
                   7212:     foreach my $package (@extension) {
                   7213: 	my ($package,$pack_type)=@{$package};
                   7214: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7215: 	    return $packagetab{"$pack_type&$name&default"};
                   7216: 	}
                   7217: 	if (defined($packagetab{$package."&$name&default"})) {
                   7218: 	    return $packagetab{$package."&$name&default"};
                   7219: 	}
                   7220:     }
                   7221:     # look for a global default setting
                   7222:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7223: 	return $packagetab{"default&$name&default"};
                   7224:     }
1.395     albertel 7225:     return undef;
                   7226: }
                   7227: 
1.334     albertel 7228: sub add_prefix_and_part {
                   7229:     my ($prefix,$part)=@_;
                   7230:     my $keyroot;
                   7231:     if (defined($prefix) && $prefix !~ /^__/) {
                   7232: 	# prefix that has a part already
                   7233: 	$keyroot=$prefix;
                   7234:     } elsif (defined($prefix)) {
                   7235: 	# prefix that is missing a part
                   7236: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7237:     } else {
                   7238: 	# no prefix at all
                   7239: 	if (defined($part)) { $keyroot='_'.$part; }
                   7240:     }
                   7241:     return $keyroot;
                   7242: }
                   7243: 
1.71      www      7244: # ---------------------------------------------------------------- Get metadata
                   7245: 
1.599     albertel 7246: my %metaentry;
1.71      www      7247: sub metadata {
1.176     www      7248:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7249:     $uri=&declutter($uri);
1.288     albertel 7250:     # if it is a non metadata possible uri return quickly
1.529     albertel 7251:     if (($uri eq '') || 
                   7252: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7253: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7254:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7255: 	return undef;
                   7256:     }
                   7257:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7258: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7259: 	return undef;
1.288     albertel 7260:     }
1.73      www      7261:     my $filename=$uri;
                   7262:     $uri=~s/\.meta$//;
1.172     www      7263: #
                   7264: # Is the metadata already cached?
1.177     www      7265: # Look at timestamp of caching
1.172     www      7266: # Everything is cached by the main uri, libraries are never directly cached
                   7267: #
1.428     albertel 7268:     if (!defined($liburi)) {
1.599     albertel 7269: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7270: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7271:     }
                   7272:     {
1.172     www      7273: #
                   7274: # Is this a recursive call for a library?
                   7275: #
1.599     albertel 7276: #	if (! exists($metacache{$uri})) {
                   7277: #	    $metacache{$uri}={};
                   7278: #	}
1.924     albertel 7279: 	my $cachetime = 60*60;
1.171     www      7280:         if ($liburi) {
                   7281: 	    $liburi=&declutter($liburi);
                   7282:             $filename=$liburi;
1.401     bowersj2 7283:         } else {
1.599     albertel 7284: 	    &devalidate_cache_new('meta',$uri);
                   7285: 	    undef(%metaentry);
1.401     bowersj2 7286: 	}
1.140     www      7287:         my %metathesekeys=();
1.73      www      7288:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7289: 	my $metastring;
1.924     albertel 7290: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7291: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7292: 	    $metastring = 
1.929     albertel 7293: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7294: 					  ('grade_target' => 'meta'));
                   7295: 	    $cachetime = 1; # only want this cached in the child not long term
                   7296: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7297: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7298: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7299: 	    $metastring=&getfile($file);
1.489     albertel 7300: 	}
1.208     albertel 7301:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7302:         my $token;
1.140     www      7303:         undef %metathesekeys;
1.71      www      7304:         while ($token=$parser->get_token) {
1.339     albertel 7305: 	    if ($token->[0] eq 'S') {
                   7306: 		if (defined($token->[2]->{'package'})) {
1.172     www      7307: #
                   7308: # This is a package - get package info
                   7309: #
1.339     albertel 7310: 		    my $package=$token->[2]->{'package'};
                   7311: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7312: 		    if (defined($token->[2]->{'id'})) { 
                   7313: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7314: 		    }
1.599     albertel 7315: 		    if ($metaentry{':packages'}) {
                   7316: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7317: 		    } else {
1.599     albertel 7318: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7319: 		    }
1.736     albertel 7320: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7321: 			my $part=$keyroot;
                   7322: 			$part=~s/^\_//;
1.736     albertel 7323: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7324: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7325: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7326: 			    # ignore package.tab specified default values
                   7327:                             # here &package_tab_default() will fetch those
                   7328: 			    if ($subp eq 'default') { next; }
1.736     albertel 7329: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7330: 			    my $unikey;
                   7331: 			    if ($pack =~ /_0$/) {
                   7332: 				$unikey='parameter_0_'.$name;
                   7333: 				$part=0;
                   7334: 			    } else {
                   7335: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7336: 			    }
1.339     albertel 7337: 			    if ($subp eq 'display') {
                   7338: 				$value.=' [Part: '.$part.']';
                   7339: 			    }
1.599     albertel 7340: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7341: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7342: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7343: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7344: 			    }
1.599     albertel 7345: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7346: 				$metaentry{':'.$unikey}=
                   7347: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7348: 			    }
1.339     albertel 7349: 			}
                   7350: 		    }
                   7351: 		} else {
1.172     www      7352: #
                   7353: # This is not a package - some other kind of start tag
1.339     albertel 7354: #
                   7355: 		    my $entry=$token->[1];
                   7356: 		    my $unikey;
                   7357: 		    if ($entry eq 'import') {
                   7358: 			$unikey='';
                   7359: 		    } else {
                   7360: 			$unikey=$entry;
                   7361: 		    }
                   7362: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7363: 
                   7364: 		    if (defined($token->[2]->{'id'})) { 
                   7365: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7366: 		    }
1.175     www      7367: 
1.339     albertel 7368: 		    if ($entry eq 'import') {
1.175     www      7369: #
                   7370: # Importing a library here
1.339     albertel 7371: #
                   7372: 			if ($depthcount<20) {
                   7373: 			    my $location=$parser->get_text('/import');
                   7374: 			    my $dir=$filename;
                   7375: 			    $dir=~s|[^/]*$||;
                   7376: 			    $location=&filelocation($dir,$location);
1.736     albertel 7377: 			    my $metadata = 
                   7378: 				&metadata($uri,'keys', $location,$unikey,
                   7379: 					  $depthcount+1);
                   7380: 			    foreach my $meta (split(',',$metadata)) {
                   7381: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7382: 				$metathesekeys{$meta}=1;
1.339     albertel 7383: 			    }
                   7384: 			}
                   7385: 		    } else { 
                   7386: 			
                   7387: 			if (defined($token->[2]->{'name'})) { 
                   7388: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7389: 			}
                   7390: 			$metathesekeys{$unikey}=1;
1.736     albertel 7391: 			foreach my $param (@{$token->[3]}) {
                   7392: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7393: 				$token->[2]->{$param};
1.339     albertel 7394: 			}
                   7395: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7396: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7397: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7398: 		 # only ws inside the tag, and not in default, so use default
                   7399: 		 # as value
1.599     albertel 7400: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7401: 			} elsif ( $internaltext =~ /\S/ ) {
                   7402: 		  # something interesting inside the tag
                   7403: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7404: 			} else {
1.908     albertel 7405: 		  # no interesting values, don't set a default
1.339     albertel 7406: 			}
1.172     www      7407: # end of not-a-package not-a-library import
1.339     albertel 7408: 		    }
1.172     www      7409: # end of not-a-package start tag
1.339     albertel 7410: 		}
1.172     www      7411: # the next is the end of "start tag"
1.339     albertel 7412: 	    }
                   7413: 	}
1.483     albertel 7414: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7415: 	$extension = lc($extension);
                   7416: 	if ($extension eq 'htm') { $extension='html'; }
                   7417: 
1.737     albertel 7418: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7419: 	    #no specific packages #how's our extension
                   7420: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7421: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7422: 					 \%metathesekeys);
                   7423: 	}
1.883     albertel 7424: 
                   7425: 	if (!exists($metaentry{':packages'})
                   7426: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7427: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7428: 		#no specific packages well let's get default then
                   7429: 		if ($key!~/^default&/) { next; }
1.488     albertel 7430: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7431: 					     \%metathesekeys);
                   7432: 	    }
                   7433: 	}
1.338     www      7434: # are there custom rights to evaluate
1.599     albertel 7435: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7436: 
1.338     www      7437:     #
                   7438:     # Importing a rights file here
1.339     albertel 7439:     #
                   7440: 	    unless ($depthcount) {
1.599     albertel 7441: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7442: 		my $dir=$filename;
                   7443: 		$dir=~s|[^/]*$||;
                   7444: 		$location=&filelocation($dir,$location);
1.736     albertel 7445: 		my $rights_metadata =
                   7446: 		    &metadata($uri,'keys',$location,'_rights',
                   7447: 			      $depthcount+1);
                   7448: 		foreach my $rights (split(',',$rights_metadata)) {
                   7449: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7450: 		    $metathesekeys{$rights}=1;
1.339     albertel 7451: 		}
                   7452: 	    }
                   7453: 	}
1.737     albertel 7454: 	# uniqifiy package listing
                   7455: 	my %seen;
                   7456: 	my @uniq_packages =
                   7457: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7458: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7459: 
                   7460: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7461: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7462: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7463: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7464: # this is the end of "was not already recently cached
1.71      www      7465:     }
1.599     albertel 7466:     return $metaentry{':'.$what};
1.261     albertel 7467: }
                   7468: 
1.488     albertel 7469: sub metadata_create_package_def {
1.483     albertel 7470:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7471:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7472:     if ($subp eq 'default') { next; }
                   7473:     
1.599     albertel 7474:     if (defined($metaentry{':packages'})) {
                   7475: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7476:     } else {
1.599     albertel 7477: 	$metaentry{':packages'}=$package;
1.483     albertel 7478:     }
                   7479:     my $value=$packagetab{$key};
                   7480:     my $unikey;
                   7481:     $unikey='parameter_0_'.$name;
1.599     albertel 7482:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7483:     $$metathesekeys{$unikey}=1;
1.599     albertel 7484:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7485: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7486:     }
1.599     albertel 7487:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7488: 	$metaentry{':'.$unikey}=
                   7489: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7490:     }
                   7491: }
                   7492: 
1.261     albertel 7493: sub metadata_generate_part0 {
                   7494:     my ($metadata,$metacache,$uri) = @_;
                   7495:     my %allnames;
1.737     albertel 7496:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7497: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7498: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7499: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7500: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7501: 	    $allnames{$name}=$part;
                   7502: 	  }
                   7503: 	}
                   7504:     }
                   7505:     foreach my $name (keys(%allnames)) {
                   7506:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7507:       my $key=":parameter_0_$name";
1.261     albertel 7508:       $$metacache{"$key.part"}='0';
                   7509:       $$metacache{"$key.name"}=$name;
1.428     albertel 7510:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7511: 					   $allnames{$name}.'_'.$name.
                   7512: 					   '.type'};
1.428     albertel 7513:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7514: 			     '.display'};
1.644     www      7515:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7516:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7517:       $$metacache{"$key.display"}=$olddis;
                   7518:     }
1.71      www      7519: }
                   7520: 
1.764     albertel 7521: # ------------------------------------------------------ Devalidate title cache
                   7522: 
                   7523: sub devalidate_title_cache {
                   7524:     my ($url)=@_;
                   7525:     if (!$env{'request.course.id'}) { return; }
                   7526:     my $symb=&symbread($url);
                   7527:     if (!$symb) { return; }
                   7528:     my $key=$env{'request.course.id'}."\0".$symb;
                   7529:     &devalidate_cache_new('title',$key);
                   7530: }
                   7531: 
1.301     www      7532: # ------------------------------------------------- Get the title of a resource
                   7533: 
                   7534: sub gettitle {
                   7535:     my $urlsymb=shift;
                   7536:     my $symb=&symbread($urlsymb);
1.534     albertel 7537:     if ($symb) {
1.620     albertel 7538: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7539: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7540: 	if (defined($cached)) { 
                   7541: 	    return $result;
                   7542: 	}
1.534     albertel 7543: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7544: 	my $title='';
1.907     albertel 7545: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7546: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7547: 	} else {
                   7548: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7549: 		    &GDBM_READER(),0640)) {
                   7550: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7551: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7552: 		untie(%bighash);
                   7553: 	    }
1.534     albertel 7554: 	}
                   7555: 	$title=~s/\&colon\;/\:/gs;
                   7556: 	if ($title) {
1.599     albertel 7557: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7558: 	}
                   7559: 	$urlsymb=$url;
                   7560:     }
                   7561:     my $title=&metadata($urlsymb,'title');
                   7562:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7563:     return $title;
1.301     www      7564: }
1.613     albertel 7565: 
1.614     albertel 7566: sub get_slot {
                   7567:     my ($which,$cnum,$cdom)=@_;
                   7568:     if (!$cnum || !$cdom) {
1.790     albertel 7569: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7570: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7571: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7572:     }
1.703     albertel 7573:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7574:     my %slotinfo;
                   7575:     if (exists($remembered{$key})) {
                   7576: 	$slotinfo{$which} = $remembered{$key};
                   7577:     } else {
                   7578: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7579: 	&Apache::lonhomework::showhash(%slotinfo);
                   7580: 	my ($tmp)=keys(%slotinfo);
                   7581: 	if ($tmp=~/^error:/) { return (); }
                   7582: 	$remembered{$key} = $slotinfo{$which};
                   7583:     }
1.616     albertel 7584:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7585: 	return %{$slotinfo{$which}};
                   7586:     }
                   7587:     return $slotinfo{$which};
1.614     albertel 7588: }
1.31      www      7589: # ------------------------------------------------- Update symbolic store links
                   7590: 
                   7591: sub symblist {
                   7592:     my ($mapname,%newhash)=@_;
1.438     www      7593:     $mapname=&deversion(&declutter($mapname));
1.31      www      7594:     my %hash;
1.620     albertel 7595:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7596:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7597:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7598: 	    foreach my $url (keys %newhash) {
                   7599: 		next if ($url eq 'last_known'
                   7600: 			 && $env{'form.no_update_last_known'});
                   7601: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7602: 						    $newhash{$url}->[1],
                   7603: 						    $newhash{$url}->[0]);
1.191     harris41 7604:             }
1.31      www      7605:             if (untie(%hash)) {
                   7606: 		return 'ok';
                   7607:             }
                   7608:         }
                   7609:     }
                   7610:     return 'error';
1.212     www      7611: }
                   7612: 
                   7613: # --------------------------------------------------------------- Verify a symb
                   7614: 
                   7615: sub symbverify {
1.510     www      7616:     my ($symb,$thisurl)=@_;
                   7617:     my $thisfn=$thisurl;
1.439     www      7618:     $thisfn=&declutter($thisfn);
1.215     www      7619: # direct jump to resource in page or to a sequence - will construct own symbs
                   7620:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7621: # check URL part
1.409     www      7622:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7623: 
1.431     www      7624:     unless ($url eq $thisfn) { return 0; }
1.213     www      7625: 
1.216     www      7626:     $symb=&symbclean($symb);
1.510     www      7627:     $thisurl=&deversion($thisurl);
1.439     www      7628:     $thisfn=&deversion($thisfn);
1.213     www      7629: 
                   7630:     my %bighash;
                   7631:     my $okay=0;
1.431     www      7632: 
1.620     albertel 7633:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7634:                             &GDBM_READER(),0640)) {
1.510     www      7635:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7636:         unless ($ids) { 
1.510     www      7637:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7638:         }
                   7639:         if ($ids) {
                   7640: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7641: 	    foreach my $id (split(/\,/,$ids)) {
                   7642: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7643:                if (
                   7644:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7645:    eq $symb) { 
1.620     albertel 7646: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7647: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7648: 		       $okay=1; 
                   7649: 		   }
                   7650: 	       }
1.216     www      7651: 	   }
                   7652:         }
1.213     www      7653: 	untie(%bighash);
                   7654:     }
                   7655:     return $okay;
1.31      www      7656: }
                   7657: 
1.210     www      7658: # --------------------------------------------------------------- Clean-up symb
                   7659: 
                   7660: sub symbclean {
                   7661:     my $symb=shift;
1.568     albertel 7662:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7663: # remove version from map
                   7664:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7665: 
1.210     www      7666: # remove version from URL
                   7667:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7668: 
1.507     www      7669: # remove wrapper
                   7670: 
1.510     www      7671:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7672:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7673:     return $symb;
1.409     www      7674: }
                   7675: 
                   7676: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7677: 
                   7678: sub encode_symb {
                   7679:     my ($map,$resid,$url)=@_;
                   7680:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7681: }
1.409     www      7682: 
                   7683: sub decode_symb {
1.568     albertel 7684:     my $symb=shift;
                   7685:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7686:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7687:     return (&fixversion($map),$resid,&fixversion($url));
                   7688: }
                   7689: 
                   7690: sub fixversion {
                   7691:     my $fn=shift;
1.609     banghart 7692:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7693:     my %bighash;
                   7694:     my $uri=&clutter($fn);
1.620     albertel 7695:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7696: # is this cached?
1.599     albertel 7697:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7698:     if (defined($cached)) { return $result; }
                   7699: # unfortunately not cached, or expired
1.620     albertel 7700:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7701: 	    &GDBM_READER(),0640)) {
                   7702:  	if ($bighash{'version_'.$uri}) {
                   7703:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7704:  	    unless (($version eq 'mostrecent') || 
                   7705: 		    ($version==&getversion($uri))) {
1.440     www      7706:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7707:  	    }
                   7708:  	}
                   7709:  	untie %bighash;
1.413     www      7710:     }
1.599     albertel 7711:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7712: }
                   7713: 
                   7714: sub deversion {
                   7715:     my $url=shift;
                   7716:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7717:     return $url;
1.210     www      7718: }
                   7719: 
1.31      www      7720: # ------------------------------------------------------ Return symb list entry
                   7721: 
                   7722: sub symbread {
1.249     www      7723:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7724:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7725:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7726: # no filename provided? try from environment
1.44      www      7727:     unless ($thisfn) {
1.620     albertel 7728:         if ($env{'request.symb'}) {
                   7729: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7730: 	}
1.620     albertel 7731: 	$thisfn=$env{'request.filename'};
1.44      www      7732:     }
1.569     albertel 7733:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7734: # is that filename actually a symb? Verify, clean, and return
                   7735:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7736: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7737: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7738: 	}
1.242     www      7739:     }
1.44      www      7740:     $thisfn=declutter($thisfn);
1.31      www      7741:     my %hash;
1.37      www      7742:     my %bighash;
                   7743:     my $syval='';
1.620     albertel 7744:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7745:         my $targetfn = $thisfn;
1.609     banghart 7746:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7747:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7748:         }
1.687     albertel 7749: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7750: 	    $targetfn=$1;
                   7751: 	}
1.620     albertel 7752:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7753:                       &GDBM_READER(),0640)) {
1.481     raeburn  7754: 	    $syval=$hash{$targetfn};
1.37      www      7755:             untie(%hash);
                   7756:         }
                   7757: # ---------------------------------------------------------- There was an entry
                   7758:         if ($syval) {
1.601     albertel 7759: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7760: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7761: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7762: 		    #return $env{$cache_str}='';
1.601     albertel 7763: 		#}    
                   7764: 		#$syval.=$1;
                   7765: 	    #}
1.37      www      7766:         } else {
                   7767: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7768:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7769:                             &GDBM_READER(),0640)) {
1.37      www      7770: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7771:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7772:               unless ($ids) { 
                   7773:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7774:               }
                   7775:               unless ($ids) {
                   7776: # alias?
                   7777: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7778:               }
1.37      www      7779:               if ($ids) {
                   7780: # ------------------------------------------------------------------- Has ID(s)
                   7781:                  my @possibilities=split(/\,/,$ids);
1.39      www      7782:                  if ($#possibilities==0) {
                   7783: # ----------------------------------------------- There is only one possibility
1.37      www      7784: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7785: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7786: 						    $resid,$thisfn);
1.249     www      7787:                  } elsif (!$donotrecurse) {
1.39      www      7788: # ------------------------------------------ There is more than one possibility
                   7789:                      my $realpossible=0;
1.800     albertel 7790:                      foreach my $id (@possibilities) {
                   7791: 			 my $file=$bighash{'src_'.$id};
1.39      www      7792:                          if (&allowed('bre',$file)) {
1.800     albertel 7793:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7794:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7795: 				$realpossible++;
1.626     albertel 7796:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7797: 						    $resid,$thisfn);
1.39      www      7798:                             }
                   7799: 			 }
1.191     harris41 7800:                      }
1.39      www      7801: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7802:                  } else {
                   7803:                      $syval='';
1.37      www      7804:                  }
                   7805: 	      }
                   7806:               untie(%bighash)
1.481     raeburn  7807:            }
1.31      www      7808:         }
1.62      www      7809:         if ($syval) {
1.620     albertel 7810: 	    return $env{$cache_str}=$syval;
1.62      www      7811:         }
1.31      www      7812:     }
1.949     raeburn  7813:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7814:     return $env{$cache_str}='';
1.31      www      7815: }
                   7816: 
                   7817: # ---------------------------------------------------------- Return random seed
                   7818: 
1.32      www      7819: sub numval {
                   7820:     my $txt=shift;
                   7821:     $txt=~tr/A-J/0-9/;
                   7822:     $txt=~tr/a-j/0-9/;
                   7823:     $txt=~tr/K-T/0-9/;
                   7824:     $txt=~tr/k-t/0-9/;
                   7825:     $txt=~tr/U-Z/0-5/;
                   7826:     $txt=~tr/u-z/0-5/;
                   7827:     $txt=~s/\D//g;
1.564     albertel 7828:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7829:     return int($txt);
1.368     albertel 7830: }
                   7831: 
1.484     albertel 7832: sub numval2 {
                   7833:     my $txt=shift;
                   7834:     $txt=~tr/A-J/0-9/;
                   7835:     $txt=~tr/a-j/0-9/;
                   7836:     $txt=~tr/K-T/0-9/;
                   7837:     $txt=~tr/k-t/0-9/;
                   7838:     $txt=~tr/U-Z/0-5/;
                   7839:     $txt=~tr/u-z/0-5/;
                   7840:     $txt=~s/\D//g;
                   7841:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7842:     my $total;
                   7843:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7844:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7845:     return int($total);
                   7846: }
                   7847: 
1.575     albertel 7848: sub numval3 {
                   7849:     use integer;
                   7850:     my $txt=shift;
                   7851:     $txt=~tr/A-J/0-9/;
                   7852:     $txt=~tr/a-j/0-9/;
                   7853:     $txt=~tr/K-T/0-9/;
                   7854:     $txt=~tr/k-t/0-9/;
                   7855:     $txt=~tr/U-Z/0-5/;
                   7856:     $txt=~tr/u-z/0-5/;
                   7857:     $txt=~s/\D//g;
                   7858:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7859:     my $total;
                   7860:     foreach my $val (@txts) { $total+=$val; }
                   7861:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7862:     return $total;
                   7863: }
                   7864: 
1.675     albertel 7865: sub digest {
                   7866:     my ($data)=@_;
                   7867:     my $digest=&Digest::MD5::md5($data);
                   7868:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7869:     my ($e,$f);
                   7870:     {
                   7871:         use integer;
                   7872:         $e=($a+$b);
                   7873:         $f=($c+$d);
                   7874:         if ($_64bit) {
                   7875:             $e=(($e<<32)>>32);
                   7876:             $f=(($f<<32)>>32);
                   7877:         }
                   7878:     }
                   7879:     if (wantarray) {
                   7880: 	return ($e,$f);
                   7881:     } else {
                   7882: 	my $g;
                   7883: 	{
                   7884: 	    use integer;
                   7885: 	    $g=($e+$f);
                   7886: 	    if ($_64bit) {
                   7887: 		$g=(($g<<32)>>32);
                   7888: 	    }
                   7889: 	}
                   7890: 	return $g;
                   7891:     }
                   7892: }
                   7893: 
1.368     albertel 7894: sub latest_rnd_algorithm_id {
1.675     albertel 7895:     return '64bit5';
1.366     albertel 7896: }
1.32      www      7897: 
1.503     albertel 7898: sub get_rand_alg {
                   7899:     my ($courseid)=@_;
1.790     albertel 7900:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7901:     if ($courseid) {
1.620     albertel 7902: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7903:     }
                   7904:     return &latest_rnd_algorithm_id();
                   7905: }
                   7906: 
1.562     albertel 7907: sub validCODE {
                   7908:     my ($CODE)=@_;
                   7909:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7910:     return 0;
                   7911: }
                   7912: 
1.491     albertel 7913: sub getCODE {
1.620     albertel 7914:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7915:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7916: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7917: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7918: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7919:     }
                   7920:     return undef;
                   7921: }
                   7922: 
1.31      www      7923: sub rndseed {
1.155     albertel 7924:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7925:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7926:     if (!defined($symb)) {
1.366     albertel 7927: 	unless ($symb=$wsymb) { return time; }
                   7928:     }
                   7929:     if (!$courseid) { $courseid=$wcourseid; }
                   7930:     if (!$domain) { $domain=$wdomain; }
                   7931:     if (!$username) { $username=$wusername }
1.503     albertel 7932:     my $which=&get_rand_alg();
1.803     albertel 7933: 
1.491     albertel 7934:     if (defined(&getCODE())) {
1.675     albertel 7935: 	if ($which eq '64bit5') {
                   7936: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7937: 	} elsif ($which eq '64bit4') {
1.575     albertel 7938: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7939: 	} else {
                   7940: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7941: 	}
1.675     albertel 7942:     } elsif ($which eq '64bit5') {
                   7943: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7944:     } elsif ($which eq '64bit4') {
                   7945: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7946:     } elsif ($which eq '64bit3') {
                   7947: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7948:     } elsif ($which eq '64bit2') {
                   7949: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7950:     } elsif ($which eq '64bit') {
                   7951: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7952:     }
                   7953:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7954: }
                   7955: 
                   7956: sub rndseed_32bit {
                   7957:     my ($symb,$courseid,$domain,$username)=@_;
                   7958:     {
                   7959: 	use integer;
                   7960: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7961: 	my $symbseed=numval($symb) << 22;
                   7962: 	my $namechck=unpack("%32C*",$username) << 17;
                   7963: 	my $nameseed=numval($username) << 12;
                   7964: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7965: 	my $courseseed=unpack("%32C*",$courseid);
                   7966: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7967: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7968: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7969: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7970: 	return $num;
                   7971:     }
                   7972: }
                   7973: 
                   7974: sub rndseed_64bit {
                   7975:     my ($symb,$courseid,$domain,$username)=@_;
                   7976:     {
                   7977: 	use integer;
                   7978: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7979: 	my $symbseed=numval($symb) << 10;
                   7980: 	my $namechck=unpack("%32S*",$username);
                   7981: 	
                   7982: 	my $nameseed=numval($username) << 21;
                   7983: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7984: 	my $courseseed=unpack("%32S*",$courseid);
                   7985: 	
                   7986: 	my $num1=$symbchck+$symbseed+$namechck;
                   7987: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7988: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7989: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7990: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7991: 	return "$num1,$num2";
1.155     albertel 7992:     }
1.366     albertel 7993: }
                   7994: 
1.443     albertel 7995: sub rndseed_64bit2 {
                   7996:     my ($symb,$courseid,$domain,$username)=@_;
                   7997:     {
                   7998: 	use integer;
                   7999: 	# strings need to be an even # of cahracters long, it it is odd the
                   8000:         # last characters gets thrown away
                   8001: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8002: 	my $symbseed=numval($symb) << 10;
                   8003: 	my $namechck=unpack("%32S*",$username.' ');
                   8004: 	
                   8005: 	my $nameseed=numval($username) << 21;
1.501     albertel 8006: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8007: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8008: 	
                   8009: 	my $num1=$symbchck+$symbseed+$namechck;
                   8010: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8011: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8012: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8013: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8014: 	return "$num1,$num2";
                   8015:     }
                   8016: }
                   8017: 
                   8018: sub rndseed_64bit3 {
                   8019:     my ($symb,$courseid,$domain,$username)=@_;
                   8020:     {
                   8021: 	use integer;
                   8022: 	# strings need to be an even # of cahracters long, it it is odd the
                   8023:         # last characters gets thrown away
                   8024: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8025: 	my $symbseed=numval2($symb) << 10;
                   8026: 	my $namechck=unpack("%32S*",$username.' ');
                   8027: 	
                   8028: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8029: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8030: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8031: 	
                   8032: 	my $num1=$symbchck+$symbseed+$namechck;
                   8033: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8034: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8035: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8036: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8037: 	
1.503     albertel 8038: 	return "$num1:$num2";
1.443     albertel 8039:     }
                   8040: }
                   8041: 
1.575     albertel 8042: sub rndseed_64bit4 {
                   8043:     my ($symb,$courseid,$domain,$username)=@_;
                   8044:     {
                   8045: 	use integer;
                   8046: 	# strings need to be an even # of cahracters long, it it is odd the
                   8047:         # last characters gets thrown away
                   8048: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8049: 	my $symbseed=numval3($symb) << 10;
                   8050: 	my $namechck=unpack("%32S*",$username.' ');
                   8051: 	
                   8052: 	my $nameseed=numval3($username) << 21;
                   8053: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8054: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8055: 	
                   8056: 	my $num1=$symbchck+$symbseed+$namechck;
                   8057: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8058: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8059: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8060: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8061: 	
                   8062: 	return "$num1:$num2";
                   8063:     }
                   8064: }
                   8065: 
1.675     albertel 8066: sub rndseed_64bit5 {
                   8067:     my ($symb,$courseid,$domain,$username)=@_;
                   8068:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8069:     return "$num1:$num2";
                   8070: }
                   8071: 
1.366     albertel 8072: sub rndseed_CODE_64bit {
                   8073:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8074:     {
1.366     albertel 8075: 	use integer;
1.443     albertel 8076: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8077: 	my $symbseed=numval2($symb);
1.491     albertel 8078: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8079: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8080: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8081: 	my $num1=$symbseed+$CODEchck;
                   8082: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8083: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8084: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8085: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8086: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8087: 	return "$num1:$num2";
1.366     albertel 8088:     }
                   8089: }
                   8090: 
1.575     albertel 8091: sub rndseed_CODE_64bit4 {
                   8092:     my ($symb,$courseid,$domain,$username)=@_;
                   8093:     {
                   8094: 	use integer;
                   8095: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8096: 	my $symbseed=numval3($symb);
                   8097: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8098: 	my $CODEseed=numval3(&getCODE());
                   8099: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8100: 	my $num1=$symbseed+$CODEchck;
                   8101: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8102: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8103: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8104: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8105: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8106: 	return "$num1:$num2";
                   8107:     }
                   8108: }
                   8109: 
1.675     albertel 8110: sub rndseed_CODE_64bit5 {
                   8111:     my ($symb,$courseid,$domain,$username)=@_;
                   8112:     my $code = &getCODE();
                   8113:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8114:     return "$num1:$num2";
                   8115: }
                   8116: 
1.366     albertel 8117: sub setup_random_from_rndseed {
                   8118:     my ($rndseed)=@_;
1.503     albertel 8119:     if ($rndseed =~/([,:])/) {
                   8120: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8121: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8122:     } else {
                   8123: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8124:     }
1.36      albertel 8125: }
                   8126: 
1.474     albertel 8127: sub latest_receipt_algorithm_id {
1.835     albertel 8128:     return 'receipt3';
1.474     albertel 8129: }
                   8130: 
1.480     www      8131: sub recunique {
                   8132:     my $fucourseid=shift;
                   8133:     my $unique;
1.835     albertel 8134:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8135: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8136: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8137:     } else {
                   8138: 	$unique=$perlvar{'lonReceipt'};
                   8139:     }
                   8140:     return unpack("%32C*",$unique);
                   8141: }
                   8142: 
                   8143: sub recprefix {
                   8144:     my $fucourseid=shift;
                   8145:     my $prefix;
1.835     albertel 8146:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8147: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8148: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8149:     } else {
                   8150: 	$prefix=$perlvar{'lonHostID'};
                   8151:     }
                   8152:     return unpack("%32C*",$prefix);
                   8153: }
                   8154: 
1.76      www      8155: sub ireceipt {
1.474     albertel 8156:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8157: 
                   8158:     my $return =&recprefix($fucourseid).'-';
                   8159: 
                   8160:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8161: 	$env{'request.state'} eq 'construct') {
                   8162: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8163: 	return $return;
                   8164:     }
                   8165: 
1.76      www      8166:     my $cuname=unpack("%32C*",$funame);
                   8167:     my $cudom=unpack("%32C*",$fudom);
                   8168:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8169:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8170:     my $cunique=&recunique($fucourseid);
1.474     albertel 8171:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8172:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8173: 
1.790     albertel 8174: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8175: 			       
                   8176: 	$return.= ($cunique%$cuname+
                   8177: 		   $cunique%$cudom+
                   8178: 		   $cusymb%$cuname+
                   8179: 		   $cusymb%$cudom+
                   8180: 		   $cucourseid%$cuname+
                   8181: 		   $cucourseid%$cudom+
                   8182: 		   $cpart%$cuname+
                   8183: 		   $cpart%$cudom);
                   8184:     } else {
                   8185: 	$return.= ($cunique%$cuname+
                   8186: 		   $cunique%$cudom+
                   8187: 		   $cusymb%$cuname+
                   8188: 		   $cusymb%$cudom+
                   8189: 		   $cucourseid%$cuname+
                   8190: 		   $cucourseid%$cudom);
                   8191:     }
                   8192:     return $return;
1.76      www      8193: }
                   8194: 
                   8195: sub receipt {
1.474     albertel 8196:     my ($part)=@_;
1.790     albertel 8197:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8198:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8199: }
1.260     ng       8200: 
1.790     albertel 8201: sub whichuser {
                   8202:     my ($passedsymb)=@_;
                   8203:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8204:     if (defined($env{'form.grade_symb'})) {
                   8205: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8206: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8207: 	if (!$allowed &&
                   8208: 	    exists($env{'request.course.sec'}) &&
                   8209: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8210: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8211: 			      '/'.$env{'request.course.sec'});
                   8212: 	}
                   8213: 	if ($allowed) {
                   8214: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8215: 	    $courseid=$tmp_courseid;
                   8216: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8217: 	    ($name)=&get_env_multiple('form.grade_username');
                   8218: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8219: 	}
                   8220:     }
                   8221:     if (!$passedsymb) {
                   8222: 	$symb=&symbread();
                   8223:     } else {
                   8224: 	$symb=$passedsymb;
                   8225:     }
                   8226:     $courseid=$env{'request.course.id'};
                   8227:     $domain=$env{'user.domain'};
                   8228:     $name=$env{'user.name'};
                   8229:     if ($name eq 'public' && $domain eq 'public') {
                   8230: 	if (!defined($env{'form.username'})) {
                   8231: 	    $env{'form.username'}.=time.rand(10000000);
                   8232: 	}
                   8233: 	$name.=$env{'form.username'};
                   8234:     }
                   8235:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8236: 
                   8237: }
                   8238: 
1.36      albertel 8239: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8240: # returns either the contents of the file or 
                   8241: # -1 if the file doesn't exist
1.481     raeburn  8242: #
                   8243: # if the target is a file that was uploaded via DOCS, 
                   8244: # a check will be made to see if a current copy exists on the local server,
                   8245: # if it does this will be served, otherwise a copy will be retrieved from
                   8246: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8247: # the local server.   
1.472     albertel 8248: 
1.36      albertel 8249: sub getfile {
1.538     albertel 8250:     my ($file) = @_;
1.609     banghart 8251:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8252:     &repcopy($file);
                   8253:     return &readfile($file);
                   8254: }
                   8255: 
                   8256: sub repcopy_userfile {
                   8257:     my ($file)=@_;
1.609     banghart 8258:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8259:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8260:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8261: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8262:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8263:     if (-e "$file") {
1.828     www      8264: # we already have a local copy, check it out
1.538     albertel 8265: 	my @fileinfo = stat($file);
1.828     www      8266: 	my $rtncode;
                   8267: 	my $info;
1.538     albertel 8268: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8269: 	if ($lwpresp ne 'ok') {
1.828     www      8270: # there is no such file anymore, even though we had a local copy
1.482     albertel 8271: 	    if ($rtncode eq '404') {
1.538     albertel 8272: 		unlink($file);
1.482     albertel 8273: 	    }
                   8274: 	    return -1;
                   8275: 	}
                   8276: 	if ($info < $fileinfo[9]) {
1.828     www      8277: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8278: 	    return 'ok';
1.828     www      8279: 	} else {
                   8280: # the file is outdated, get rid of it
                   8281: 	    unlink($file);
1.482     albertel 8282: 	}
1.828     www      8283:     }
                   8284: # one way or the other, at this point, we don't have the file
                   8285: # construct the correct path for the file
                   8286:     my @parts = ($cdom,$cnum); 
                   8287:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8288: 	push @parts, split(/\//,$1);
                   8289:     }
                   8290:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8291:     foreach my $part (@parts) {
                   8292: 	$path .= '/'.$part;
                   8293: 	if (!-e $path) {
                   8294: 	    mkdir($path,0770);
1.482     albertel 8295: 	}
                   8296:     }
1.828     www      8297: # now the path exists for sure
                   8298: # get a user agent
                   8299:     my $ua=new LWP::UserAgent;
                   8300:     my $transferfile=$file.'.in.transfer';
                   8301: # FIXME: this should flock
                   8302:     if (-e $transferfile) { return 'ok'; }
                   8303:     my $request;
                   8304:     $uri=~s/^\///;
1.976.2.3  raeburn  8305:     my $homeserver = &homeserver($cnum,$cdom);
                   8306:     my $protocol = $protocol{$homeserver};
                   8307:     $protocol = 'http' if ($protocol ne 'https');
                   8308:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8309:     my $response=$ua->request($request,$transferfile);
                   8310: # did it work?
                   8311:     if ($response->is_error()) {
                   8312: 	unlink($transferfile);
                   8313: 	&logthis("Userfile repcopy failed for $uri");
                   8314: 	return -1;
                   8315:     }
                   8316: # worked, rename the transfer file
                   8317:     rename($transferfile,$file);
1.607     raeburn  8318:     return 'ok';
1.481     raeburn  8319: }
                   8320: 
1.517     albertel 8321: sub tokenwrapper {
                   8322:     my $uri=shift;
1.976.2.3  raeburn  8323:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8324:     $uri=~s|^/||;
1.620     albertel 8325:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8326:     my $token=$1;
1.552     albertel 8327:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8328:     if ($udom && $uname && $file) {
                   8329: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8330:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.976.2.3  raeburn  8331:         my $homeserver = &homeserver($uname,$udom);
                   8332:         my $protocol = $protocol{$homeserver};
                   8333:         $protocol = 'http' if ($protocol ne 'https');
                   8334:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8335:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8336:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8337:     } else {
                   8338:         return '/adm/notfound.html';
                   8339:     }
                   8340: }
                   8341: 
1.828     www      8342: # call with reqtype HEAD: get last modification time
                   8343: # call with reqtype GET: get the file contents
                   8344: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8345: #
1.481     raeburn  8346: sub getuploaded {
                   8347:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8348:     $uri=~s/^\///;
1.976.2.3  raeburn  8349:     my $homeserver = &homeserver($cnum,$cdom);
                   8350:     my $protocol = $protocol{$homeserver};
                   8351:     $protocol = 'http' if ($protocol ne 'https');
                   8352:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8353:     my $ua=new LWP::UserAgent;
                   8354:     my $request=new HTTP::Request($reqtype,$uri);
                   8355:     my $response=$ua->request($request);
                   8356:     $$rtncode = $response->code;
1.482     albertel 8357:     if (! $response->is_success()) {
                   8358: 	return 'failed';
                   8359:     }      
                   8360:     if ($reqtype eq 'HEAD') {
1.486     www      8361: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8362:     } elsif ($reqtype eq 'GET') {
                   8363: 	$$info = $response->content;
1.472     albertel 8364:     }
1.482     albertel 8365:     return 'ok';
1.36      albertel 8366: }
                   8367: 
1.481     raeburn  8368: sub readfile {
                   8369:     my $file = shift;
                   8370:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8371:     my $fh;
                   8372:     open($fh,"<$file");
                   8373:     my $a='';
1.800     albertel 8374:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8375:     return $a;
                   8376: }
                   8377: 
1.36      albertel 8378: sub filelocation {
1.590     banghart 8379:     my ($dir,$file) = @_;
                   8380:     my $location;
                   8381:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8382: 
                   8383:     if ($file =~ m-^/adm/-) {
                   8384: 	$file=~s-^/adm/wrapper/-/-;
                   8385: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8386:     }
1.882     albertel 8387: 
1.590     banghart 8388:     if ($file=~m:^/~:) { # is a contruction space reference
                   8389:         $location = $file;
                   8390:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8391:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8392: 	# is a correct contruction space reference
                   8393:         $location = $file;
1.956     raeburn  8394:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8395:         $location = $file;
1.609     banghart 8396:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8397:         my ($udom,$uname,$filename)=
1.811     albertel 8398:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8399:         my $home=&homeserver($uname,$udom);
                   8400:         my $is_me=0;
                   8401:         my @ids=&current_machine_ids();
                   8402:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8403:         if ($is_me) {
1.955     raeburn  8404:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8405:         } else {
                   8406:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8407:   	      $udom.'/'.$uname.'/'.$filename;
                   8408:         }
1.882     albertel 8409:     } elsif ($file =~ m-^/adm/-) {
                   8410: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8411:     } else {
                   8412:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8413:         $file=~s:^/res/:/:;
                   8414:         if ( !( $file =~ m:^/:) ) {
                   8415:             $location = $dir. '/'.$file;
                   8416:         } else {
                   8417:             $location = '/home/httpd/html/res'.$file;
                   8418:         }
1.59      albertel 8419:     }
1.590     banghart 8420:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8421:     while ($location=~m{/\.\./}) {
                   8422: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8423: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8424: 	} else {
                   8425: 	    $location=~ s{/\.\./}{/}g;
                   8426: 	}
                   8427:     } #remove dir/..
1.590     banghart 8428:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8429:     return $location;
1.46      www      8430: }
1.36      albertel 8431: 
1.46      www      8432: sub hreflocation {
                   8433:     my ($dir,$file)=@_;
1.976.2.3  raeburn  8434:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8435: 	$file=filelocation($dir,$file);
1.700     albertel 8436:     } elsif ($file=~m-^/adm/-) {
                   8437: 	$file=~s-^/adm/wrapper/-/-;
                   8438: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8439:     }
                   8440:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8441: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8442:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8443: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8444:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8445: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8446: 	    -/uploaded/$1/$2/-x;
1.46      www      8447:     }
1.913     albertel 8448:     if ($file=~ m{^/userfiles/}) {
                   8449: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8450:     }
1.462     albertel 8451:     return $file;
1.465     albertel 8452: }
                   8453: 
                   8454: sub current_machine_domains {
1.853     albertel 8455:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8456: }
                   8457: 
                   8458: sub machine_domains {
                   8459:     my ($hostname) = @_;
1.465     albertel 8460:     my @domains;
1.838     albertel 8461:     my %hostname = &all_hostnames();
1.465     albertel 8462:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8463: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8464: 	if ($hostname eq $name) {
1.844     albertel 8465: 	    push(@domains,&host_domain($id));
1.465     albertel 8466: 	}
                   8467:     }
                   8468:     return @domains;
                   8469: }
                   8470: 
                   8471: sub current_machine_ids {
1.853     albertel 8472:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8473: }
                   8474: 
                   8475: sub machine_ids {
                   8476:     my ($hostname) = @_;
                   8477:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8478:     my @ids;
1.888     albertel 8479:     my %name_to_host = &all_names();
1.889     albertel 8480:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8481: 	return @{ $name_to_host{$hostname} };
                   8482:     }
                   8483:     return;
1.31      www      8484: }
                   8485: 
1.824     raeburn  8486: sub additional_machine_domains {
                   8487:     my @domains;
                   8488:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8489:     while( my $line = <$fh>) {
                   8490:         $line =~ s/\s//g;
                   8491:         push(@domains,$line);
                   8492:     }
                   8493:     return @domains;
                   8494: }
                   8495: 
                   8496: sub default_login_domain {
                   8497:     my $domain = $perlvar{'lonDefDomain'};
                   8498:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8499:     foreach my $posdom (&current_machine_domains(),
                   8500:                         &additional_machine_domains()) {
                   8501:         if (lc($posdom) eq lc($testdomain)) {
                   8502:             $domain=$posdom;
                   8503:             last;
                   8504:         }
                   8505:     }
                   8506:     return $domain;
                   8507: }
                   8508: 
1.31      www      8509: # ------------------------------------------------------------- Declutters URLs
                   8510: 
                   8511: sub declutter {
                   8512:     my $thisfn=shift;
1.569     albertel 8513:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8514:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8515:     $thisfn=~s/^\///;
1.697     albertel 8516:     $thisfn=~s|^adm/wrapper/||;
                   8517:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8518:     $thisfn=~s/^res\///;
1.235     www      8519:     $thisfn=~s/\?.+$//;
1.268     www      8520:     return $thisfn;
                   8521: }
                   8522: 
                   8523: # ------------------------------------------------------------- Clutter up URLs
                   8524: 
                   8525: sub clutter {
                   8526:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8527:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8528: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8529:        $thisfn='/res'.$thisfn; 
                   8530:     }
1.694     albertel 8531:     if ($thisfn !~m|/adm|) {
1.695     albertel 8532: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8533: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8534: 	} else {
                   8535: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8536: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8537: 	    if ($embstyle eq 'ssi'
                   8538: 		|| ($embstyle eq 'hdn')
                   8539: 		|| ($embstyle eq 'rat')
                   8540: 		|| ($embstyle eq 'prv')
                   8541: 		|| ($embstyle eq 'ign')) {
                   8542: 		#do nothing with these
                   8543: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8544: 		|| ($embstyle eq 'emb')
                   8545: 		|| ($embstyle eq 'wrp')) {
                   8546: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8547: 	    } elsif ($embstyle eq 'unk'
                   8548: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8549: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8550: 	    } else {
1.718     www      8551: #		&logthis("Got a blank emb style");
1.695     albertel 8552: 	    }
1.694     albertel 8553: 	}
                   8554:     }
1.31      www      8555:     return $thisfn;
1.12      www      8556: }
                   8557: 
1.787     albertel 8558: sub clutter_with_no_wrapper {
                   8559:     my $uri = &clutter(shift);
                   8560:     if ($uri =~ m-^/adm/-) {
                   8561: 	$uri =~ s-^/adm/wrapper/-/-;
                   8562: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8563:     }
                   8564:     return $uri;
                   8565: }
                   8566: 
1.557     albertel 8567: sub freeze_escape {
                   8568:     my ($value)=@_;
                   8569:     if (ref($value)) {
                   8570: 	$value=&nfreeze($value);
                   8571: 	return '__FROZEN__'.&escape($value);
                   8572:     }
                   8573:     return &escape($value);
                   8574: }
                   8575: 
1.11      www      8576: 
1.557     albertel 8577: sub thaw_unescape {
                   8578:     my ($value)=@_;
                   8579:     if ($value =~ /^__FROZEN__/) {
                   8580: 	substr($value,0,10,undef);
                   8581: 	$value=&unescape($value);
                   8582: 	return &thaw($value);
                   8583:     }
                   8584:     return &unescape($value);
                   8585: }
                   8586: 
1.436     albertel 8587: sub correct_line_ends {
                   8588:     my ($result)=@_;
                   8589:     $$result =~s/\r\n/\n/mg;
                   8590:     $$result =~s/\r/\n/mg;
1.415     albertel 8591: }
1.1       albertel 8592: # ================================================================ Main Program
                   8593: 
1.184     www      8594: sub goodbye {
1.204     albertel 8595:    &logthis("Starting Shut down");
1.443     albertel 8596: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8597:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8598: #converted
1.599     albertel 8599: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8600:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8601: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8602: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8603: #1.1 only
1.870     albertel 8604: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8605: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8606: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8607: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8608:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8609:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8610:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8611:    &flushcourselogs();
                   8612:    &logthis("Shutting down");
                   8613: }
                   8614: 
1.852     albertel 8615: sub get_dns {
1.869     albertel 8616:     my ($url,$func,$ignore_cache) = @_;
                   8617:     if (!$ignore_cache) {
                   8618: 	my ($content,$cached)=
                   8619: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8620: 	if ($cached) {
                   8621: 	    &$func($content);
                   8622: 	    return;
                   8623: 	}
                   8624:     }
                   8625: 
                   8626:     my %alldns;
1.852     albertel 8627:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8628:     foreach my $dns (<$config>) {
                   8629: 	next if ($dns !~ /^\^(\S*)/x);
1.976.2.2  raeburn  8630:         my $line = $1;
                   8631:         my ($host,$protocol) = split(/:/,$line);
                   8632:         if ($protocol ne 'https') {
                   8633:             $protocol = 'http';
                   8634:         }
                   8635: 	$alldns{$host} = $protocol;
1.869     albertel 8636:     }
                   8637:     while (%alldns) {
                   8638: 	my ($dns) = keys(%alldns);
1.852     albertel 8639: 	my $ua=new LWP::UserAgent;
1.976.2.2  raeburn  8640: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8641: 	my $response=$ua->request($request);
1.976.2.2  raeburn  8642:         delete($alldns{$dns});
1.852     albertel 8643: 	next if ($response->is_error());
                   8644: 	my @content = split("\n",$response->content);
1.869     albertel 8645: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8646: 	&$func(\@content);
1.869     albertel 8647: 	return;
1.852     albertel 8648:     }
                   8649:     close($config);
1.871     albertel 8650:     my $which = (split('/',$url))[3];
                   8651:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8652:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8653:     my @content = <$config>;
                   8654:     &$func(\@content);
                   8655:     return;
1.852     albertel 8656: }
1.327     albertel 8657: # ------------------------------------------------------------ Read domain file
                   8658: {
1.852     albertel 8659:     my $loaded;
1.846     albertel 8660:     my %domain;
                   8661: 
1.852     albertel 8662:     sub parse_domain_tab {
                   8663: 	my ($lines) = @_;
                   8664: 	foreach my $line (@$lines) {
                   8665: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8666: 
1.846     albertel 8667: 	    chomp($line);
1.852     albertel 8668: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8669: 	    my %this_domain;
                   8670: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8671: 			       'lang_def', 'city', 'longi', 'lati',
                   8672: 			       'primary') {
                   8673: 		$this_domain{$field} = shift(@elements);
                   8674: 	    }
                   8675: 	    $domain{$name} = \%this_domain;
1.852     albertel 8676: 	}
                   8677:     }
1.864     albertel 8678: 
                   8679:     sub reset_domain_info {
                   8680: 	undef($loaded);
                   8681: 	undef(%domain);
                   8682:     }
                   8683: 
1.852     albertel 8684:     sub load_domain_tab {
1.869     albertel 8685: 	my ($ignore_cache) = @_;
                   8686: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8687: 	my $fh;
                   8688: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8689: 	    my @lines = <$fh>;
                   8690: 	    &parse_domain_tab(\@lines);
1.448     albertel 8691: 	}
1.852     albertel 8692: 	close($fh);
                   8693: 	$loaded = 1;
1.327     albertel 8694:     }
1.846     albertel 8695: 
                   8696:     sub domain {
1.852     albertel 8697: 	&load_domain_tab() if (!$loaded);
                   8698: 
1.846     albertel 8699: 	my ($name,$what) = @_;
                   8700: 	return if ( !exists($domain{$name}) );
                   8701: 
                   8702: 	if (!$what) {
                   8703: 	    return $domain{$name}{'description'};
                   8704: 	}
                   8705: 	return $domain{$name}{$what};
                   8706:     }
1.974     raeburn  8707: 
                   8708:     sub domain_info {
                   8709:         &load_domain_tab() if (!$loaded);
                   8710:         return %domain;
                   8711:     }
                   8712: 
1.327     albertel 8713: }
                   8714: 
                   8715: 
1.1       albertel 8716: # ------------------------------------------------------------- Read hosts file
                   8717: {
1.838     albertel 8718:     my %hostname;
1.844     albertel 8719:     my %hostdom;
1.845     albertel 8720:     my %libserv;
1.852     albertel 8721:     my $loaded;
1.888     albertel 8722:     my %name_to_host;
1.852     albertel 8723: 
                   8724:     sub parse_hosts_tab {
                   8725: 	my ($file) = @_;
                   8726: 	foreach my $configline (@$file) {
                   8727: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8728: 	    next if ($configline =~ /^\^/);
                   8729: 	    chomp($configline);
1.968     raeburn  8730: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8731: 	    $name=~s/\s//g;
                   8732: 	    if ($id && $domain && $role && $name) {
                   8733: 		$hostname{$id}=$name;
1.888     albertel 8734: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8735: 		$hostdom{$id}=$domain;
                   8736: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8737:                 if (defined($protocol)) {
                   8738:                     if ($protocol eq 'https') {
                   8739:                         $protocol{$id} = $protocol;
                   8740:                     } else {
                   8741:                         $protocol{$id} = 'http'; 
                   8742:                     }
1.968     raeburn  8743:                 } else {
1.969     raeburn  8744:                     $protocol{$id} = 'http';
1.968     raeburn  8745:                 }
1.852     albertel 8746: 	    }
                   8747: 	}
                   8748:     }
1.864     albertel 8749:     
                   8750:     sub reset_hosts_info {
1.897     albertel 8751: 	&purge_remembered();
1.864     albertel 8752: 	&reset_domain_info();
                   8753: 	&reset_hosts_ip_info();
1.892     albertel 8754: 	undef(%name_to_host);
1.864     albertel 8755: 	undef(%hostname);
                   8756: 	undef(%hostdom);
                   8757: 	undef(%libserv);
                   8758: 	undef($loaded);
                   8759:     }
1.1       albertel 8760: 
1.852     albertel 8761:     sub load_hosts_tab {
1.869     albertel 8762: 	my ($ignore_cache) = @_;
                   8763: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8764: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8765: 	my @config = <$config>;
                   8766: 	&parse_hosts_tab(\@config);
                   8767: 	close($config);
                   8768: 	$loaded=1;
1.1       albertel 8769:     }
1.852     albertel 8770: 
1.838     albertel 8771:     sub hostname {
1.852     albertel 8772: 	&load_hosts_tab() if (!$loaded);
                   8773: 
1.838     albertel 8774: 	my ($lonid) = @_;
                   8775: 	return $hostname{$lonid};
                   8776:     }
1.845     albertel 8777: 
1.838     albertel 8778:     sub all_hostnames {
1.852     albertel 8779: 	&load_hosts_tab() if (!$loaded);
                   8780: 
1.838     albertel 8781: 	return %hostname;
                   8782:     }
1.845     albertel 8783: 
1.888     albertel 8784:     sub all_names {
                   8785: 	&load_hosts_tab() if (!$loaded);
                   8786: 
                   8787: 	return %name_to_host;
                   8788:     }
                   8789: 
1.974     raeburn  8790:     sub all_host_domain {
                   8791:         &load_hosts_tab() if (!$loaded);
                   8792:         return %hostdom;
                   8793:     }
                   8794: 
1.845     albertel 8795:     sub is_library {
1.852     albertel 8796: 	&load_hosts_tab() if (!$loaded);
                   8797: 
1.845     albertel 8798: 	return exists($libserv{$_[0]});
                   8799:     }
                   8800: 
                   8801:     sub all_library {
1.852     albertel 8802: 	&load_hosts_tab() if (!$loaded);
                   8803: 
1.845     albertel 8804: 	return %libserv;
                   8805:     }
                   8806: 
1.841     albertel 8807:     sub get_servers {
1.852     albertel 8808: 	&load_hosts_tab() if (!$loaded);
                   8809: 
1.841     albertel 8810: 	my ($domain,$type) = @_;
                   8811: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8812: 	                                          : %hostname;
                   8813: 	my %result;
1.842     albertel 8814: 	if (ref($domain) eq 'ARRAY') {
                   8815: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8816: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8817: 		    $result{$host} = $hostname;
                   8818: 		}
                   8819: 	    }
                   8820: 	} else {
                   8821: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8822: 		if ($hostdom{$host} eq $domain) {
                   8823: 		    $result{$host} = $hostname;
                   8824: 		}
1.841     albertel 8825: 	    }
                   8826: 	}
                   8827: 	return %result;
                   8828:     }
1.845     albertel 8829: 
1.844     albertel 8830:     sub host_domain {
1.852     albertel 8831: 	&load_hosts_tab() if (!$loaded);
                   8832: 
1.844     albertel 8833: 	my ($lonid) = @_;
                   8834: 	return $hostdom{$lonid};
                   8835:     }
                   8836: 
1.841     albertel 8837:     sub all_domains {
1.852     albertel 8838: 	&load_hosts_tab() if (!$loaded);
                   8839: 
1.841     albertel 8840: 	my %seen;
                   8841: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8842: 	return @uniq;
                   8843:     }
1.1       albertel 8844: }
                   8845: 
1.847     albertel 8846: { 
                   8847:     my %iphost;
1.856     albertel 8848:     my %name_to_ip;
                   8849:     my %lonid_to_ip;
1.869     albertel 8850: 
1.847     albertel 8851:     sub get_hosts_from_ip {
                   8852: 	my ($ip) = @_;
                   8853: 	my %iphosts = &get_iphost();
                   8854: 	if (ref($iphosts{$ip})) {
                   8855: 	    return @{$iphosts{$ip}};
                   8856: 	}
                   8857: 	return;
1.839     albertel 8858:     }
1.864     albertel 8859:     
                   8860:     sub reset_hosts_ip_info {
                   8861: 	undef(%iphost);
                   8862: 	undef(%name_to_ip);
                   8863: 	undef(%lonid_to_ip);
                   8864:     }
1.856     albertel 8865: 
                   8866:     sub get_host_ip {
                   8867: 	my ($lonid) = @_;
                   8868: 	if (exists($lonid_to_ip{$lonid})) {
                   8869: 	    return $lonid_to_ip{$lonid};
                   8870: 	}
                   8871: 	my $name=&hostname($lonid);
                   8872:    	my $ip = gethostbyname($name);
                   8873: 	return if (!$ip || length($ip) ne 4);
                   8874: 	$ip=inet_ntoa($ip);
                   8875: 	$name_to_ip{$name}   = $ip;
                   8876: 	$lonid_to_ip{$lonid} = $ip;
                   8877: 	return $ip;
                   8878:     }
1.847     albertel 8879:     
                   8880:     sub get_iphost {
1.869     albertel 8881: 	my ($ignore_cache) = @_;
1.894     albertel 8882: 
1.869     albertel 8883: 	if (!$ignore_cache) {
                   8884: 	    if (%iphost) {
                   8885: 		return %iphost;
                   8886: 	    }
                   8887: 	    my ($ip_info,$cached)=
                   8888: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8889: 	    if ($cached) {
                   8890: 		%iphost      = %{$ip_info->[0]};
                   8891: 		%name_to_ip  = %{$ip_info->[1]};
                   8892: 		%lonid_to_ip = %{$ip_info->[2]};
                   8893: 		return %iphost;
                   8894: 	    }
                   8895: 	}
1.894     albertel 8896: 
                   8897: 	# get yesterday's info for fallback
                   8898: 	my %old_name_to_ip;
                   8899: 	my ($ip_info,$cached)=
                   8900: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8901: 	if ($cached) {
                   8902: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8903: 	}
                   8904: 
1.888     albertel 8905: 	my %name_to_host = &all_names();
                   8906: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8907: 	    my $ip;
                   8908: 	    if (!exists($name_to_ip{$name})) {
                   8909: 		$ip = gethostbyname($name);
                   8910: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8911: 		    if (defined($old_name_to_ip{$name})) {
                   8912: 			$ip = $old_name_to_ip{$name};
                   8913: 			&logthis("Can't find $name defaulting to old $ip");
                   8914: 		    } else {
                   8915: 			&logthis("Name $name no IP found");
                   8916: 			next;
                   8917: 		    }
                   8918: 		} else {
                   8919: 		    $ip=inet_ntoa($ip);
1.847     albertel 8920: 		}
                   8921: 		$name_to_ip{$name} = $ip;
                   8922: 	    } else {
                   8923: 		$ip = $name_to_ip{$name};
1.653     albertel 8924: 	    }
1.888     albertel 8925: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8926: 		$lonid_to_ip{$id} = $ip;
                   8927: 	    }
                   8928: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8929: 	}
1.869     albertel 8930: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8931: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8932: 				      48*60*60);
1.869     albertel 8933: 
1.847     albertel 8934: 	return %iphost;
1.598     albertel 8935:     }
                   8936: }
                   8937: 
1.862     albertel 8938: BEGIN {
                   8939: 
                   8940: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8941:     unless ($readit) {
                   8942: {
                   8943:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8944:     %perlvar = (%perlvar,%{$configvars});
                   8945: }
                   8946: 
                   8947: 
1.1       albertel 8948: # ------------------------------------------------------ Read spare server file
                   8949: {
1.448     albertel 8950:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8951: 
                   8952:     while (my $configline=<$config>) {
                   8953:        chomp($configline);
1.284     matthew  8954:        if ($configline) {
1.784     albertel 8955: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8956: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8957: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8958:        }
                   8959:     }
1.448     albertel 8960:     close($config);
1.1       albertel 8961: }
1.11      www      8962: # ------------------------------------------------------------ Read permissions
                   8963: {
1.448     albertel 8964:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8965: 
                   8966:     while (my $configline=<$config>) {
1.448     albertel 8967: 	chomp($configline);
                   8968: 	if ($configline) {
                   8969: 	    my ($role,$perm)=split(/ /,$configline);
                   8970: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8971: 	}
1.11      www      8972:     }
1.448     albertel 8973:     close($config);
1.11      www      8974: }
                   8975: 
                   8976: # -------------------------------------------- Read plain texts for permissions
                   8977: {
1.448     albertel 8978:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8979: 
                   8980:     while (my $configline=<$config>) {
1.448     albertel 8981: 	chomp($configline);
                   8982: 	if ($configline) {
1.742     raeburn  8983: 	    my ($short,@plain)=split(/:/,$configline);
                   8984:             %{$prp{$short}} = ();
                   8985: 	    if (@plain > 0) {
                   8986:                 $prp{$short}{'std'} = $plain[0];
                   8987:                 for (my $i=1; $i<@plain; $i++) {
                   8988:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8989:                 }
                   8990:             }
1.448     albertel 8991: 	}
1.135     www      8992:     }
1.448     albertel 8993:     close($config);
1.135     www      8994: }
                   8995: 
                   8996: # ---------------------------------------------------------- Read package table
                   8997: {
1.448     albertel 8998:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8999: 
                   9000:     while (my $configline=<$config>) {
1.483     albertel 9001: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9002: 	chomp($configline);
                   9003: 	my ($short,$plain)=split(/:/,$configline);
                   9004: 	my ($pack,$name)=split(/\&/,$short);
                   9005: 	if ($plain ne '') {
                   9006: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9007: 	    $packagetab{$short}=$plain; 
                   9008: 	}
1.11      www      9009:     }
1.448     albertel 9010:     close($config);
1.329     matthew  9011: }
                   9012: 
                   9013: # ------------- set up temporary directory
                   9014: {
                   9015:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9016: 
1.11      www      9017: }
                   9018: 
1.794     albertel 9019: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9020: 				'compress_threshold'=> 20_000,
                   9021:  			        });
1.185     www      9022: 
1.281     www      9023: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9024: $dumpcount=0;
1.958     www      9025: $locknum=0;
1.22      www      9026: 
1.163     harris41 9027: &logtouch();
1.672     albertel 9028: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9029: $readit=1;
1.564     albertel 9030:     {
                   9031: 	use integer;
                   9032: 	my $test=(2**32)+1;
1.568     albertel 9033: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9034: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9035:     }
1.195     www      9036: }
1.1       albertel 9037: }
1.179     www      9038: 
1.1       albertel 9039: 1;
1.191     harris41 9040: __END__
                   9041: 
1.243     albertel 9042: =pod
                   9043: 
1.191     harris41 9044: =head1 NAME
                   9045: 
1.243     albertel 9046: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9047: 
                   9048: =head1 SYNOPSIS
                   9049: 
1.243     albertel 9050: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9051: 
                   9052:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9053: 
1.243     albertel 9054: Common parameters:
                   9055: 
                   9056: =over 4
                   9057: 
                   9058: =item *
                   9059: 
                   9060: $uname : an internal username (if $cname expecting a course Id specifically)
                   9061: 
                   9062: =item *
                   9063: 
                   9064: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9065: 
                   9066: =item *
                   9067: 
                   9068: $symb : a resource instance identifier
                   9069: 
                   9070: =item *
                   9071: 
                   9072: $namespace : the name of a .db file that contains the data needed or
                   9073: being set.
                   9074: 
                   9075: =back
                   9076: 
1.394     bowersj2 9077: =head1 OVERVIEW
1.191     harris41 9078: 
1.394     bowersj2 9079: lonnet provides subroutines which interact with the
                   9080: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9081: about classes, users, and resources.
1.243     albertel 9082: 
                   9083: For many of these objects you can also use this to store data about
                   9084: them or modify them in various ways.
1.191     harris41 9085: 
1.394     bowersj2 9086: =head2 Symbs
1.191     harris41 9087: 
1.394     bowersj2 9088: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9089: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9090: map, the resource number of the resource in the map, and the URL of
                   9091: the resource itself. The latter is somewhat redundant, but might help
                   9092: if maps change.
                   9093: 
                   9094: An example is
                   9095: 
                   9096:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9097: 
                   9098: The respective map entry is
                   9099: 
                   9100:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9101:   title="Problem 2">
                   9102:  </resource>
                   9103: 
                   9104: Symbs are used by the random number generator, as well as to store and
                   9105: restore data specific to a certain instance of for example a problem.
                   9106: 
                   9107: =head2 Storing And Retrieving Data
                   9108: 
                   9109: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9110: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9111: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9112: is is the non-critical message twin of cstore. These functions are for
                   9113: handlers to store a perl hash to a user's permanent data space in an
                   9114: easy manner, and to retrieve it again on another call. It is expected
                   9115: that a handler would use this once at the beginning to retrieve data,
                   9116: and then again once at the end to send only the new data back.
                   9117: 
                   9118: The data is stored in the user's data directory on the user's
                   9119: homeserver under the ID of the course.
                   9120: 
                   9121: The hash that is returned by restore will have all of the previous
                   9122: value for all of the elements of the hash.
                   9123: 
                   9124: Example:
                   9125: 
                   9126:  #creating a hash
                   9127:  my %hash;
                   9128:  $hash{'foo'}='bar';
                   9129: 
                   9130:  #storing it
                   9131:  &Apache::lonnet::cstore(\%hash);
                   9132: 
                   9133:  #changing a value
                   9134:  $hash{'foo'}='notbar';
                   9135: 
                   9136:  #adding a new value
                   9137:  $hash{'bar'}='foo';
                   9138:  &Apache::lonnet::cstore(\%hash);
                   9139: 
                   9140:  #retrieving the hash
                   9141:  my %history=&Apache::lonnet::restore();
                   9142: 
                   9143:  #print the hash
                   9144:  foreach my $key (sort(keys(%history))) {
                   9145:    print("\%history{$key} = $history{$key}");
                   9146:  }
                   9147: 
                   9148: Will print out:
1.191     harris41 9149: 
1.394     bowersj2 9150:  %history{1:foo} = bar
                   9151:  %history{1:keys} = foo:timestamp
                   9152:  %history{1:timestamp} = 990455579
                   9153:  %history{2:bar} = foo
                   9154:  %history{2:foo} = notbar
                   9155:  %history{2:keys} = foo:bar:timestamp
                   9156:  %history{2:timestamp} = 990455580
                   9157:  %history{bar} = foo
                   9158:  %history{foo} = notbar
                   9159:  %history{timestamp} = 990455580
                   9160:  %history{version} = 2
                   9161: 
                   9162: Note that the special hash entries C<keys>, C<version> and
                   9163: C<timestamp> were added to the hash. C<version> will be equal to the
                   9164: total number of versions of the data that have been stored. The
                   9165: C<timestamp> attribute will be the UNIX time the hash was
                   9166: stored. C<keys> is available in every historical section to list which
                   9167: keys were added or changed at a specific historical revision of a
                   9168: hash.
                   9169: 
                   9170: B<Warning>: do not store the hash that restore returns directly. This
                   9171: will cause a mess since it will restore the historical keys as if the
                   9172: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9173: 
1.394     bowersj2 9174: Calling convention:
1.191     harris41 9175: 
1.394     bowersj2 9176:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9177:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9178: 
1.394     bowersj2 9179: For more detailed information, see lonnet specific documentation.
1.191     harris41 9180: 
1.394     bowersj2 9181: =head1 RETURN MESSAGES
1.191     harris41 9182: 
1.394     bowersj2 9183: =over 4
1.191     harris41 9184: 
1.394     bowersj2 9185: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9186: 
1.394     bowersj2 9187: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9188: when the connection is brought back up
1.191     harris41 9189: 
1.394     bowersj2 9190: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9191: for later delivery
1.191     harris41 9192: 
1.967     bisitz   9193: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9194: 
1.394     bowersj2 9195: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9196: that was requested
1.191     harris41 9197: 
1.243     albertel 9198: =back
1.191     harris41 9199: 
1.243     albertel 9200: =head1 PUBLIC SUBROUTINES
1.191     harris41 9201: 
1.243     albertel 9202: =head2 Session Environment Functions
1.191     harris41 9203: 
1.243     albertel 9204: =over 4
1.191     harris41 9205: 
1.394     bowersj2 9206: =item * 
                   9207: X<appenv()>
1.949     raeburn  9208: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9209: the user envirnoment file, and will be restored for each access this
1.620     albertel 9210: user makes during this session, also modifies the %env for the current
1.949     raeburn  9211: process. Optional rolesarrayref - if defined contains a reference to an array
                   9212: of roles which are exempt from the restriction on modifying user.role entries 
                   9213: in the user's environment.db and in %env.    
1.191     harris41 9214: 
                   9215: =item *
1.394     bowersj2 9216: X<delenv()>
                   9217: B<delenv($regexp)>: removes all items from the session
                   9218: environment file that matches the regular expression in $regexp. The
1.620     albertel 9219: values are also delted from the current processes %env.
1.191     harris41 9220: 
1.795     albertel 9221: =item * get_env_multiple($name) 
                   9222: 
                   9223: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9224: values may be defined and end up as an array ref.
                   9225: 
                   9226: returns an array of values
                   9227: 
1.243     albertel 9228: =back
                   9229: 
                   9230: =head2 User Information
1.191     harris41 9231: 
1.243     albertel 9232: =over 4
1.191     harris41 9233: 
                   9234: =item *
1.394     bowersj2 9235: X<queryauthenticate()>
                   9236: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9237: authentication scheme
                   9238: 
                   9239: =item *
1.394     bowersj2 9240: X<authenticate()>
                   9241: B<authenticate($uname,$upass,$udom)>: try to
                   9242: authenticate user from domain's lib servers (first use the current
                   9243: one). C<$upass> should be the users password.
1.191     harris41 9244: 
                   9245: =item *
1.394     bowersj2 9246: X<homeserver()>
                   9247: B<homeserver($uname,$udom)>: find the server which has
                   9248: the user's directory and files (there must be only one), this caches
                   9249: the answer, and also caches if there is a borken connection.
1.191     harris41 9250: 
                   9251: =item *
1.394     bowersj2 9252: X<idget()>
                   9253: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9254: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9255: username, and only 1 username per ID in a specific domain) (returns
                   9256: hash: id=>name,id=>name)
1.191     harris41 9257: 
                   9258: =item *
1.394     bowersj2 9259: X<idrget()>
                   9260: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9261: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9262: 
                   9263: =item *
1.394     bowersj2 9264: X<idput()>
                   9265: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9266: 
                   9267: =item *
1.394     bowersj2 9268: X<rolesinit()>
                   9269: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9270: 
                   9271: =item *
1.551     albertel 9272: X<getsection()>
                   9273: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9274: course $cname, return section name/number or '' for "not in course"
                   9275: and '-1' for "no section"
                   9276: 
                   9277: =item *
1.394     bowersj2 9278: X<userenvironment()>
                   9279: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9280: passed in @what from the requested user's environment, returns a hash
                   9281: 
1.858     raeburn  9282: =item * 
                   9283: X<userlog_query()>
1.859     albertel 9284: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9285: activity.log file. %filters defines filters applied when parsing the
                   9286: log file. These can be start or end timestamps, or the type of action
                   9287: - log to look for Login or Logout events, check for Checkin or
                   9288: Checkout, role for role selection. The response is in the form
                   9289: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9290: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9291: 
1.243     albertel 9292: =back
                   9293: 
                   9294: =head2 User Roles
                   9295: 
                   9296: =over 4
                   9297: 
                   9298: =item *
                   9299: 
1.810     raeburn  9300: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9301:  F: full access
                   9302:  U,I,K: authentication modes (cxx only)
                   9303:  '': forbidden
                   9304:  1: user needs to choose course
                   9305:  2: browse allowed
1.766     albertel 9306:  A: passphrase authentication needed
1.243     albertel 9307: 
                   9308: =item *
                   9309: 
                   9310: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9311: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9312: and course level
                   9313: 
                   9314: =item *
                   9315: 
                   9316: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9317: explanation of a user role term
                   9318: 
1.832     raeburn  9319: =item *
                   9320: 
1.935     raeburn  9321: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9322: All arguments are optional. Returns a hash of a roles, either for
                   9323: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9324: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9325: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9326: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9327: For each key, value is set to colon-separated start and end times for
                   9328: the role.  If no username and domain are specified, will default to
1.934     raeburn  9329: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9330: of role statuses (active, future or previous), roles 
                   9331: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9332: to restrict the list of roles reported. If no array ref is 
                   9333: provided for types, will default to return only active roles.
1.834     albertel 9334: 
1.243     albertel 9335: =back
                   9336: 
                   9337: =head2 User Modification
                   9338: 
                   9339: =over 4
                   9340: 
                   9341: =item *
                   9342: 
1.957     raeburn  9343: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9344: user for the level given by URL.  Optional start and end dates (leave empty
                   9345: string or zero for "no date")
1.191     harris41 9346: 
                   9347: =item *
                   9348: 
1.243     albertel 9349: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9350: change a users, password, possible return values are: ok,
                   9351: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9352: refused
1.191     harris41 9353: 
                   9354: =item *
                   9355: 
1.243     albertel 9356: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9357: 
                   9358: =item *
                   9359: 
1.963     raeburn  9360: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9361:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9362: modify user
1.191     harris41 9363: 
                   9364: =item *
                   9365: 
1.286     matthew  9366: modifystudent
                   9367: 
1.957     raeburn  9368: modify a student's enrollment and identification information.
1.286     matthew  9369: The course id is resolved based on the current users environment.  
                   9370: This means the envoking user must be a course coordinator or otherwise
                   9371: associated with a course.
                   9372: 
1.297     matthew  9373: This call is essentially a wrapper for lonnet::modifyuser and
                   9374: lonnet::modify_student_enrollment
1.286     matthew  9375: 
                   9376: Inputs: 
                   9377: 
                   9378: =over 4
                   9379: 
1.957     raeburn  9380: =item B<$udom> Student's loncapa domain
1.286     matthew  9381: 
1.957     raeburn  9382: =item B<$uname> Student's loncapa login name
1.286     matthew  9383: 
1.964     bisitz   9384: =item B<$uid> Student/Employee ID
1.286     matthew  9385: 
1.957     raeburn  9386: =item B<$umode> Student's authentication mode
1.286     matthew  9387: 
1.957     raeburn  9388: =item B<$upass> Student's password
1.286     matthew  9389: 
1.957     raeburn  9390: =item B<$first> Student's first name
1.286     matthew  9391: 
1.957     raeburn  9392: =item B<$middle> Student's middle name
1.286     matthew  9393: 
1.957     raeburn  9394: =item B<$last> Student's last name
1.286     matthew  9395: 
1.957     raeburn  9396: =item B<$gene> Student's generation
1.286     matthew  9397: 
1.957     raeburn  9398: =item B<$usec> Student's section in course
1.286     matthew  9399: 
                   9400: =item B<$end> Unix time of the roles expiration
                   9401: 
                   9402: =item B<$start> Unix time of the roles start date
                   9403: 
                   9404: =item B<$forceid> If defined, allow $uid to be changed
                   9405: 
                   9406: =item B<$desiredhome> server to use as home server for student
                   9407: 
1.957     raeburn  9408: =item B<$email> Student's permanent e-mail address
                   9409: 
                   9410: =item B<$type> Type of enrollment (auto or manual)
                   9411: 
1.963     raeburn  9412: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9413: 
                   9414: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9415: 
1.963     raeburn  9416: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9417: 
1.963     raeburn  9418: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9419: 
1.963     raeburn  9420: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9421: 
1.286     matthew  9422: =back
1.297     matthew  9423: 
                   9424: =item *
                   9425: 
                   9426: modify_student_enrollment
                   9427: 
                   9428: Change a students enrollment status in a class.  The environment variable
                   9429: 'role.request.course' must be defined for this function to proceed.
                   9430: 
                   9431: Inputs:
                   9432: 
                   9433: =over 4
                   9434: 
                   9435: =item $udom, students domain
                   9436: 
                   9437: =item $uname, students name
                   9438: 
                   9439: =item $uid, students user id
                   9440: 
                   9441: =item $first, students first name
                   9442: 
                   9443: =item $middle
                   9444: 
                   9445: =item $last
                   9446: 
                   9447: =item $gene
                   9448: 
                   9449: =item $usec
                   9450: 
                   9451: =item $end
                   9452: 
                   9453: =item $start
                   9454: 
1.957     raeburn  9455: =item $type
                   9456: 
                   9457: =item $locktype
                   9458: 
                   9459: =item $cid
                   9460: 
                   9461: =item $selfenroll
                   9462: 
                   9463: =item $context
                   9464: 
1.297     matthew  9465: =back
                   9466: 
1.191     harris41 9467: 
                   9468: =item *
                   9469: 
1.243     albertel 9470: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9471: custom role; give a custom role to a user for the level given by URL.  Specify
                   9472: name and domain of role author, and role name
1.191     harris41 9473: 
                   9474: =item *
                   9475: 
1.243     albertel 9476: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9477: 
                   9478: =item *
                   9479: 
1.243     albertel 9480: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9481: 
                   9482: =back
                   9483: 
                   9484: =head2 Course Infomation
                   9485: 
                   9486: =over 4
1.191     harris41 9487: 
                   9488: =item *
                   9489: 
1.631     albertel 9490: coursedescription($courseid) : returns a hash of information about the
                   9491: specified course id, including all environment settings for the
                   9492: course, the description of the course will be in the hash under the
                   9493: key 'description'
1.191     harris41 9494: 
                   9495: =item *
                   9496: 
1.624     albertel 9497: resdata($name,$domain,$type,@which) : request for current parameter
                   9498: setting for a specific $type, where $type is either 'course' or 'user',
                   9499: @what should be a list of parameters to ask about. This routine caches
                   9500: answers for 5 minutes.
1.243     albertel 9501: 
1.877     foxr     9502: =item *
                   9503: 
                   9504: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9505: data base, returning a hash that is keyed by the resource name and has
                   9506: values that are the resource value.  I believe that the timestamps and
                   9507: versions are also returned.
                   9508: 
                   9509: 
1.243     albertel 9510: =back
                   9511: 
                   9512: =head2 Course Modification
                   9513: 
                   9514: =over 4
1.191     harris41 9515: 
                   9516: =item *
                   9517: 
1.243     albertel 9518: writecoursepref($courseid,%prefs) : write preferences (environment
                   9519: database) for a course
1.191     harris41 9520: 
                   9521: =item *
                   9522: 
1.243     albertel 9523: createcourse($udom,$description,$url) : make/modify course
                   9524: 
                   9525: =back
                   9526: 
                   9527: =head2 Resource Subroutines
                   9528: 
                   9529: =over 4
1.191     harris41 9530: 
                   9531: =item *
                   9532: 
1.243     albertel 9533: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9534: 
                   9535: =item *
                   9536: 
1.243     albertel 9537: repcopy($filename) : subscribes to the requested file, and attempts to
                   9538: replicate from the owning library server, Might return
1.607     raeburn  9539: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9540: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9541: resource. Expects the local filesystem pathname
                   9542: (/home/httpd/html/res/....)
                   9543: 
                   9544: =back
                   9545: 
                   9546: =head2 Resource Information
                   9547: 
                   9548: =over 4
1.191     harris41 9549: 
                   9550: =item *
                   9551: 
1.243     albertel 9552: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9553: a vairety of different possible values, $varname should be a request
                   9554: string, and the other parameters can be used to specify who and what
                   9555: one is asking about.
                   9556: 
                   9557: Possible values for $varname are environment.lastname (or other item
                   9558: from the envirnment hash), user.name (or someother aspect about the
                   9559: user), resource.0.maxtries (or some other part and parameter of a
                   9560: resource)
1.204     albertel 9561: 
                   9562: =item *
                   9563: 
1.243     albertel 9564: directcondval($number) : get current value of a condition; reads from a state
                   9565: string
1.204     albertel 9566: 
                   9567: =item *
                   9568: 
1.243     albertel 9569: condval($condidx) : value of condition index based on state
1.204     albertel 9570: 
                   9571: =item *
                   9572: 
1.243     albertel 9573: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9574: resource's metadata, $what should be either a specific key, or either
                   9575: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9576: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9577: 
                   9578: this function automatically caches all requests
1.191     harris41 9579: 
                   9580: =item *
                   9581: 
1.243     albertel 9582: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9583: network of library servers; returns file handle of where SQL and regex results
                   9584: will be stored for query
1.191     harris41 9585: 
                   9586: =item *
                   9587: 
1.243     albertel 9588: symbread($filename) : return symbolic list entry (filename argument optional);
                   9589: returns the data handle
1.191     harris41 9590: 
                   9591: =item *
                   9592: 
1.243     albertel 9593: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9594: a possible symb for the URL in $thisfn, and if is an encryypted
                   9595: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9596: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9597: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9598: 
1.191     harris41 9599: 
                   9600: =item *
                   9601: 
1.243     albertel 9602: symbclean($symb) : removes versions numbers from a symb, returns the
                   9603: cleaned symb
1.191     harris41 9604: 
                   9605: =item *
                   9606: 
1.243     albertel 9607: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9608: course map, user must be in a course for it to work.
1.191     harris41 9609: 
                   9610: =item *
                   9611: 
1.243     albertel 9612: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9613: 
                   9614: =item *
                   9615: 
1.243     albertel 9616: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9617: a random seed, all arguments are optional, if they aren't sent it uses the
                   9618: environment to derive them. Note: if symb isn't sent and it can't get one
                   9619: from &symbread it will use the current time as its return value
1.191     harris41 9620: 
                   9621: =item *
                   9622: 
1.243     albertel 9623: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9624: unfakeable, receipt
1.191     harris41 9625: 
                   9626: =item *
                   9627: 
1.620     albertel 9628: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9629: 
                   9630: =item *
                   9631: 
1.243     albertel 9632: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9633: 
                   9634: =item *
                   9635: 
1.243     albertel 9636: 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
1.191     harris41 9637: 
                   9638: =item *
                   9639: 
1.243     albertel 9640: 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)
1.191     harris41 9641: 
                   9642: =item *
                   9643: 
1.243     albertel 9644: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9645: 
                   9646: =item *
                   9647: 
1.243     albertel 9648: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9649: forcing spreadsheet to reevaluate the resource scores next time.
                   9650: 
                   9651: =back
                   9652: 
                   9653: =head2 Storing/Retreiving Data
                   9654: 
                   9655: =over 4
1.191     harris41 9656: 
                   9657: =item *
                   9658: 
1.243     albertel 9659: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9660: for this url; hashref needs to be given and should be a \%hashname; the
                   9661: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9662: be derived from the env
1.191     harris41 9663: 
                   9664: =item *
                   9665: 
1.243     albertel 9666: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9667: uses critical subroutine
1.191     harris41 9668: 
                   9669: =item *
                   9670: 
1.243     albertel 9671: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9672: all args are optional
1.191     harris41 9673: 
                   9674: =item *
                   9675: 
1.717     albertel 9676: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9677: dumps the complete (or key matching regexp) namespace into a hash
                   9678: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9679: normally &store()ed into
                   9680: 
                   9681: $range should be either an integer '100' (give me the first 100
                   9682:                                            matching records)
                   9683:               or be  two integers sperated by a - with no spaces
                   9684:                  '30-50' (give me the 30th through the 50th matching
                   9685:                           records)
                   9686: 
                   9687: 
                   9688: =item *
                   9689: 
                   9690: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9691: replaces a &store() version of data with a replacement set of data
                   9692: for a particular resource in a namespace passed in the $storehash hash 
                   9693: reference
                   9694: 
                   9695: =item *
                   9696: 
1.243     albertel 9697: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9698: works very similar to store/cstore, but all data is stored in a
                   9699: temporary location and can be reset using tmpreset, $storehash should
                   9700: be a hash reference, returns nothing on success
1.191     harris41 9701: 
                   9702: =item *
                   9703: 
1.243     albertel 9704: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9705: similar to restore, but all data is stored in a temporary location and
                   9706: can be reset using tmpreset. Returns a hash of values on success,
                   9707: error string otherwise.
1.191     harris41 9708: 
                   9709: =item *
                   9710: 
1.243     albertel 9711: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9712: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9713: 
                   9714: =item *
                   9715: 
1.243     albertel 9716: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9717: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9718: 
                   9719: =item *
                   9720: 
1.243     albertel 9721: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9722: namesp ($udom and $uname are optional)
1.191     harris41 9723: 
                   9724: =item *
                   9725: 
1.702     albertel 9726: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9727: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9728: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9729: 
1.702     albertel 9730: $range should be either an integer '100' (give me the first 100
                   9731:                                            matching records)
                   9732:               or be  two integers sperated by a - with no spaces
                   9733:                  '30-50' (give me the 30th through the 50th matching
                   9734:                           records)
1.449     matthew  9735: =item *
                   9736: 
                   9737: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9738: $store can be a scalar, an array reference, or if the amount to be 
                   9739: incremented is > 1, a hash reference.
                   9740: 
                   9741: ($udom and $uname are optional)
1.191     harris41 9742: 
                   9743: =item *
                   9744: 
1.243     albertel 9745: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9746: ($udom and $uname are optional)
1.191     harris41 9747: 
                   9748: =item *
                   9749: 
1.243     albertel 9750: cput($namespace,$storehash,$udom,$uname) : critical put
                   9751: ($udom and $uname are optional)
1.191     harris41 9752: 
                   9753: =item *
                   9754: 
1.748     albertel 9755: newput($namespace,$storehash,$udom,$uname) :
                   9756: 
                   9757: Attempts to store the items in the $storehash, but only if they don't
                   9758: currently exist, if this succeeds you can be certain that you have 
                   9759: successfully created a new key value pair in the $namespace db.
                   9760: 
                   9761: 
                   9762: Args:
                   9763:  $namespace: name of database to store values to
                   9764:  $storehash: hashref to store to the db
                   9765:  $udom: (optional) domain of user containing the db
                   9766:  $uname: (optional) name of user caontaining the db
                   9767: 
                   9768: Returns:
                   9769:  'ok' -> succeeded in storing all keys of $storehash
                   9770:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9771:                         least <key> already existed in the db (other
                   9772:                         requested keys may also already exist)
1.967     bisitz   9773:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9774:  'con_lost' -> unable to contact request server
                   9775:  'refused' -> action was not allowed by remote machine
                   9776: 
                   9777: 
                   9778: =item *
                   9779: 
1.243     albertel 9780: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9781: reference filled in from namesp (encrypts the return communication)
                   9782: ($udom and $uname are optional)
1.191     harris41 9783: 
                   9784: =item *
                   9785: 
1.243     albertel 9786: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9787: critical subroutine
                   9788: 
1.806     raeburn  9789: =item *
                   9790: 
1.860     raeburn  9791: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9792: array reference filled in from namespace found in domain level on either
                   9793: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9794: 
                   9795: =item *
                   9796: 
1.860     raeburn  9797: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9798: domain level either on specified domain server ($uhome) or primary domain 
                   9799: server ($udom and $uhome are optional)
1.806     raeburn  9800: 
1.943     raeburn  9801: =item * 
                   9802: 
                   9803: get_domain_defaults($target_domain) : returns hash with defaults for
                   9804: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9805: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9806: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9807: Values are retrieved from cache (if current), or from domain's configuration.db
                   9808: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9809: or lonTabs/domain.tab. 
                   9810: 
                   9811: %domdefaults = &get_auth_defaults($target_domain);
                   9812: 
1.243     albertel 9813: =back
                   9814: 
                   9815: =head2 Network Status Functions
                   9816: 
                   9817: =over 4
1.191     harris41 9818: 
                   9819: =item *
                   9820: 
                   9821: dirlist($uri) : return directory list based on URI
                   9822: 
                   9823: =item *
                   9824: 
1.243     albertel 9825: spareserver() : find server with least workload from spare.tab
                   9826: 
                   9827: =back
                   9828: 
                   9829: =head2 Apache Request
                   9830: 
                   9831: =over 4
1.191     harris41 9832: 
                   9833: =item *
                   9834: 
1.243     albertel 9835: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9836: localhost, posts hash
                   9837: 
                   9838: =back
                   9839: 
                   9840: =head2 Data to String to Data
                   9841: 
                   9842: =over 4
1.191     harris41 9843: 
                   9844: =item *
                   9845: 
1.243     albertel 9846: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9847: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9848: 
                   9849: =item *
                   9850: 
1.243     albertel 9851: hashref2str($hashref) : convert a hashref into a string complete with
                   9852: escaping and '=' and '&' separators, supports elements that are
                   9853: arrayrefs and hashrefs
1.191     harris41 9854: 
                   9855: =item *
                   9856: 
1.243     albertel 9857: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9858: with escaping and '&' separators, supports elements that are arrayrefs
                   9859: and hashrefs
1.191     harris41 9860: 
                   9861: =item *
                   9862: 
1.243     albertel 9863: str2hash($string) : convert string to hash using unescaping and
                   9864: splitting on '=' and '&', supports elements that are arrayrefs and
                   9865: hashrefs
1.191     harris41 9866: 
                   9867: =item *
                   9868: 
1.243     albertel 9869: str2array($string) : convert string to hash using unescaping and
                   9870: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9871: 
                   9872: =back
                   9873: 
                   9874: =head2 Logging Routines
                   9875: 
                   9876: =over 4
                   9877: 
                   9878: These routines allow one to make log messages in the lonnet.log and
                   9879: lonnet.perm logfiles.
1.191     harris41 9880: 
                   9881: =item *
                   9882: 
1.243     albertel 9883: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9884: 
                   9885: =item *
                   9886: 
1.243     albertel 9887: logthis() : append message to the normal lonnet.log file, it gets
                   9888: preiodically rolled over and deleted.
1.191     harris41 9889: 
                   9890: =item *
                   9891: 
1.243     albertel 9892: logperm() : append a permanent message to lonnet.perm.log, this log
                   9893: file never gets deleted by any automated portion of the system, only
                   9894: messages of critical importance should go in here.
                   9895: 
                   9896: =back
                   9897: 
                   9898: =head2 General File Helper Routines
                   9899: 
                   9900: =over 4
1.191     harris41 9901: 
                   9902: =item *
                   9903: 
1.481     raeburn  9904: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9905: (a) files in /uploaded
                   9906:   (i) If a local copy of the file exists - 
                   9907:       compares modification date of local copy with last-modified date for 
                   9908:       definitive version stored on home server for course. If local copy is 
                   9909:       stale, requests a new version from the home server and stores it. 
                   9910:       If the original has been removed from the home server, then local copy 
                   9911:       is unlinked.
                   9912:   (ii) If local copy does not exist -
                   9913:       requests the file from the home server and stores it. 
                   9914:   
                   9915:   If $caller is 'uploadrep':  
                   9916:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9917:     for request for files originally uploaded via DOCS. 
                   9918:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9919:   
                   9920:   Otherwise:
                   9921:      This indicates a call from the content generation phase of the request.
                   9922:      -  returns the entire contents of the file or -1.
                   9923:      
                   9924: (b) files in /res
                   9925:    - returns the entire contents of a file or -1; 
                   9926:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9927: 
1.712     albertel 9928: 
                   9929: =item *
                   9930: 
                   9931: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9932:                   reference
                   9933: 
                   9934: returns either a stat() list of data about the file or an empty list
                   9935: if the file doesn't exist or couldn't find out about it (connection
                   9936: problems or user unknown)
                   9937: 
1.191     harris41 9938: =item *
                   9939: 
1.243     albertel 9940: filelocation($dir,$file) : returns file system location of a file
                   9941: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9942: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9943: and a file of ../bob will become /a/bob)
1.191     harris41 9944: 
                   9945: =item *
                   9946: 
                   9947: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9948: filelocation except for hrefs
                   9949: 
                   9950: =item *
                   9951: 
                   9952: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9953: 
1.243     albertel 9954: =back
                   9955: 
1.608     albertel 9956: =head2 Usererfile file routines (/uploaded*)
                   9957: 
                   9958: =over 4
                   9959: 
                   9960: =item *
                   9961: 
                   9962: userfileupload(): main rotine for putting a file in a user or course's
                   9963:                   filespace, arguments are,
                   9964: 
1.620     albertel 9965:  formname - required - this is the name of the element in $env where the
1.608     albertel 9966:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9967:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9968:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9969:  coursedoc - if true, store the file in the course of the active role
                   9970:              of the current user
                   9971:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9972:          if undefined, it will be placed in "unknown"
                   9973: 
                   9974:  (This routine calls clean_filename() to remove any dangerous
                   9975:  characters from the filename, and then calls finuserfileupload() to
                   9976:  complete the transaction)
                   9977: 
                   9978:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9979:  and /adm/notfound.html if unsuccessful
                   9980: 
                   9981: =item *
                   9982: 
                   9983: clean_filename(): routine for cleaing a filename up for storage in
                   9984:                  userfile space, argument is:
                   9985: 
                   9986:  filename - proposed filename
                   9987: 
                   9988: returns: the new clean filename
                   9989: 
                   9990: =item *
                   9991: 
                   9992: finishuserfileupload(): routine that creaes and sends the file to
                   9993: userspace, probably shouldn't be called directly
                   9994: 
                   9995:   docuname: username or courseid of destination for the file
                   9996:   docudom: domain of user/course of destination for the file
                   9997:   formname: same as for userfileupload()
                   9998:   fname: filename (inculding subdirectories) for the file
                   9999: 
                   10000:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10001:  and /adm/notfound.html if unsuccessful
                   10002: 
                   10003: =item *
                   10004: 
                   10005: renameuserfile(): renames an existing userfile to a new name
                   10006: 
                   10007:   Args:
                   10008:    docuname: username or courseid of destination for the file
                   10009:    docudom: domain of user/course of destination for the file
                   10010:    old: current file name (including any subdirs under userfiles)
                   10011:    new: desired file name (including any subdirs under userfiles)
                   10012: 
                   10013: =item *
                   10014: 
                   10015: mkdiruserfile(): creates a directory is a userfiles dir
                   10016: 
                   10017:   Args:
                   10018:    docuname: username or courseid of destination for the file
                   10019:    docudom: domain of user/course of destination for the file
                   10020:    dir: dir to create (including any subdirs under userfiles)
                   10021: 
                   10022: =item *
                   10023: 
                   10024: removeuserfile(): removes a file that exists in userfiles
                   10025: 
                   10026:   Args:
                   10027:    docuname: username or courseid of destination for the file
                   10028:    docudom: domain of user/course of destination for the file
                   10029:    fname: filname to delete (including any subdirs under userfiles)
                   10030: 
                   10031: =item *
                   10032: 
                   10033: removeuploadedurl(): convience function for removeuserfile()
                   10034: 
                   10035:   Args:
                   10036:    url:  a full /uploaded/... url to delete
                   10037: 
1.747     albertel 10038: =item * 
                   10039: 
                   10040: get_portfile_permissions():
                   10041:   Args:
                   10042:     domain: domain of user or course contain the portfolio files
                   10043:     user: name of user or num of course contain the portfolio files
                   10044:   Returns:
                   10045:     hashref of a dump of the proper file_permissions.db
                   10046:    
                   10047: 
                   10048: =item * 
                   10049: 
                   10050: get_access_controls():
                   10051: 
                   10052: Args:
                   10053:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10054:   group: (optional) the group you want the files associated with
                   10055:   file: (optional) the file you want access info on
                   10056: 
                   10057: Returns:
1.749     raeburn  10058:     a hash (keys are file names) of hashes containing
                   10059:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10060:         values are XML containing access control settings (see below) 
1.747     albertel 10061: 
                   10062: Internal notes:
                   10063: 
1.749     raeburn  10064:  access controls are stored in file_permissions.db as key=value pairs.
                   10065:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10066:         where scope -> public,guest,course,group,domains or users.
                   10067:               end -> UNIX time for end of access (0 -> no end date)
                   10068:               start -> UNIX time for start of access
                   10069: 
                   10070:     value -> XML description of access control
                   10071:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10072:             <start></start>
                   10073:             <end></end>
                   10074: 
                   10075:             <password></password>  for scope type = guest
                   10076: 
                   10077:             <domain></domain>     for scope type = course or group
                   10078:             <number></number>
                   10079:             <roles id="">
                   10080:              <role></role>
                   10081:              <access></access>
                   10082:              <section></section>
                   10083:              <group></group>
                   10084:             </roles>
                   10085: 
                   10086:             <dom></dom>         for scope type = domains
                   10087: 
                   10088:             <users>             for scope type = users
                   10089:              <user>
                   10090:               <uname></uname>
                   10091:               <udom></udom>
                   10092:              </user>
                   10093:             </users>
                   10094:            </scope> 
                   10095:               
                   10096:  Access data is also aggregated for each file in an additional key=value pair:
                   10097:  key -> path to file/file_name\0accesscontrol 
                   10098:  value -> reference to hash
                   10099:           hash contains key = value pairs
                   10100:           where key = uniqueID:scope_end_start
                   10101:                 value = UNIX time record was last updated
                   10102: 
                   10103:           Used to improve speed of look-ups of access controls for each file.  
                   10104:  
                   10105:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10106: 
                   10107: modify_access_controls():
                   10108: 
                   10109: Modifies access controls for a portfolio file
                   10110: Args
                   10111: 1. file name
                   10112: 2. reference to hash of required changes,
                   10113: 3. domain
                   10114: 4. username
                   10115:   where domain,username are the domain of the portfolio owner 
                   10116:   (either a user or a course) 
                   10117: 
                   10118: Returns:
                   10119: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10120: 2. result of deletions ('ok' or 'error', with error message).
                   10121: 3. reference to hash of any new or updated access controls.
                   10122: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10123:    key = integer (inbound ID)
                   10124:    value = uniqueID  
1.747     albertel 10125: 
1.608     albertel 10126: =back
                   10127: 
1.243     albertel 10128: =head2 HTTP Helper Routines
                   10129: 
                   10130: =over 4
                   10131: 
1.191     harris41 10132: =item *
                   10133: 
                   10134: escape() : unpack non-word characters into CGI-compatible hex codes
                   10135: 
                   10136: =item *
                   10137: 
                   10138: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10139: 
1.243     albertel 10140: =back
                   10141: 
                   10142: =head1 PRIVATE SUBROUTINES
                   10143: 
                   10144: =head2 Underlying communication routines (Shouldn't call)
                   10145: 
                   10146: =over 4
                   10147: 
                   10148: =item *
                   10149: 
                   10150: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10151: 
                   10152: =item *
                   10153: 
                   10154: reply() : uses subreply to send a message to remote machine, logs all failures
                   10155: 
                   10156: =item *
                   10157: 
                   10158: critical() : passes a critical message to another server; if cannot
                   10159: get through then place message in connection buffer directory and
                   10160: returns con_delayed, if incapable of saving message, returns
                   10161: con_failed
                   10162: 
                   10163: =item *
                   10164: 
                   10165: reconlonc() : tries to reconnect lonc client processes.
                   10166: 
                   10167: =back
                   10168: 
                   10169: =head2 Resource Access Logging
                   10170: 
                   10171: =over 4
                   10172: 
                   10173: =item *
                   10174: 
                   10175: flushcourselogs() : flush (save) buffer logs and access logs
                   10176: 
                   10177: =item *
                   10178: 
                   10179: courselog($what) : save message for course in hash
                   10180: 
                   10181: =item *
                   10182: 
                   10183: courseacclog($what) : save message for course using &courselog().  Perform
                   10184: special processing for specific resource types (problems, exams, quizzes, etc).
                   10185: 
1.191     harris41 10186: =item *
                   10187: 
                   10188: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10189: as a PerlChildExitHandler
1.243     albertel 10190: 
                   10191: =back
                   10192: 
                   10193: =head2 Other
                   10194: 
                   10195: =over 4
                   10196: 
                   10197: =item *
                   10198: 
                   10199: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10200: 
                   10201: =back
                   10202: 
                   10203: =cut
1.877     foxr     10204: 

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