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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.976.2.4! raeburn     4: # $Id: lonnet.pm,v 1.976.2.3 2008/12/21 15:26:50 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;
1.976     raeburn  1230:     my ($defauthtype,$defautharg,$deflang,%deftools);
1.943     raeburn  1231:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1232:     if (defined($cached)) {
                   1233:         if (ref($result) eq 'HASH') {
                   1234:             return %{$result};
                   1235:         }
                   1236:     }
                   1237:     my %domdefaults;
                   1238:     my %domconfig =
1.976     raeburn  1239:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1240:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1241:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1242:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1243:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1244:     } else {
                   1245:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1246:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1247:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1248:     }
1.976     raeburn  1249:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1250:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1251:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1252:         } else {
                   1253:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1254:         } 
                   1255:         my @usertools = ('aboutme','blog','portfolio');
                   1256:         foreach my $item (@usertools) {
                   1257:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1258:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1259:             }
                   1260:         }
                   1261:     }
1.943     raeburn  1262:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1263:                                   $cachetime);
                   1264:     return %domdefaults;
                   1265: }
                   1266: 
1.344     www      1267: # --------------------------------------------------- Assign a key to a student
                   1268: 
                   1269: sub assign_access_key {
1.364     www      1270: #
                   1271: # a valid key looks like uname:udom#comments
                   1272: # comments are being appended
                   1273: #
1.498     www      1274:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1275:     $kdom=
1.620     albertel 1276:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1277:     $knum=
1.620     albertel 1278:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1279:     $cdom=
1.620     albertel 1280:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1281:     $cnum=
1.620     albertel 1282:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1283:     $udom=$env{'user.name'} unless (defined($udom));
                   1284:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1285:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1286:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1287:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1288:                                                   # assigned to this person
                   1289:                                                   # - this should not happen,
1.345     www      1290:                                                   # unless something went wrong
                   1291:                                                   # the first time around
                   1292: # ready to assign
1.364     www      1293:         $logentry=$1.'; '.$logentry;
1.496     www      1294:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1295:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1296: # key now belongs to user
1.346     www      1297: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1298:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1299:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1300:                 return 'ok';
                   1301:             } else {
                   1302:                 return 
                   1303:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1304: 	    }
                   1305:         } else {
                   1306:             return 'error: Could not assign key, try again later.';
                   1307:         }
1.364     www      1308:     } elsif (!$existing{$ckey}) {
1.345     www      1309: # the key does not exist
                   1310: 	return 'error: The key does not exist';
                   1311:     } else {
                   1312: # the key is somebody else's
                   1313: 	return 'error: The key is already in use';
                   1314:     }
1.344     www      1315: }
                   1316: 
1.364     www      1317: # ------------------------------------------ put an additional comment on a key
                   1318: 
                   1319: sub comment_access_key {
                   1320: #
                   1321: # a valid key looks like uname:udom#comments
                   1322: # comments are being appended
                   1323: #
                   1324:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1325:     $cdom=
1.620     albertel 1326:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1327:     $cnum=
1.620     albertel 1328:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1329:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1330:     if ($existing{$ckey}) {
                   1331:         $existing{$ckey}.='; '.$logentry;
                   1332: # ready to assign
1.367     www      1333:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1334:                                                  $cdom,$cnum) eq 'ok') {
                   1335: 	    return 'ok';
                   1336:         } else {
                   1337: 	    return 'error: Count not store comment.';
                   1338:         }
                   1339:     } else {
                   1340: # the key does not exist
                   1341: 	return 'error: The key does not exist';
                   1342:     }
                   1343: }
                   1344: 
1.344     www      1345: # ------------------------------------------------------ Generate a set of keys
                   1346: 
                   1347: sub generate_access_keys {
1.364     www      1348:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1349:     $cdom=
1.620     albertel 1350:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1351:     $cnum=
1.620     albertel 1352:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1353:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1354:     unless (($cdom) && ($cnum)) { return 0; }
                   1355:     if ($number>10000) { return 0; }
                   1356:     sleep(2); # make sure don't get same seed twice
                   1357:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1358:     my $total=0;
                   1359:     for (my $i=1;$i<=$number;$i++) {
                   1360:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1361:                   sprintf("%lx",int(100000*rand)).'-'.
                   1362:                   sprintf("%lx",int(100000*rand));
                   1363:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1364:        $newkey=~s/0/h/g; # and also 0 and O
                   1365:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1366:        if ($existing{$newkey}) {
                   1367:            $i--;
                   1368:        } else {
1.364     www      1369: 	  if (&put('accesskeys',
                   1370:               { $newkey => '# generated '.localtime().
1.620     albertel 1371:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1372:                            '; '.$logentry },
                   1373: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1374:               $total++;
                   1375: 	  }
                   1376:        }
                   1377:     }
1.620     albertel 1378:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1379:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1380:     return $total;
                   1381: }
                   1382: 
                   1383: # ------------------------------------------------------- Validate an accesskey
                   1384: 
                   1385: sub validate_access_key {
                   1386:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1387:     $cdom=
1.620     albertel 1388:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1389:     $cnum=
1.620     albertel 1390:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1391:     $udom=$env{'user.domain'} unless (defined($udom));
                   1392:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1393:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1394:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1395: }
                   1396: 
                   1397: # ------------------------------------- Find the section of student in a course
1.652     albertel 1398: sub devalidate_getsection_cache {
                   1399:     my ($udom,$unam,$courseid)=@_;
                   1400:     my $hashid="$udom:$unam:$courseid";
                   1401:     &devalidate_cache_new('getsection',$hashid);
                   1402: }
1.298     matthew  1403: 
1.815     albertel 1404: sub courseid_to_courseurl {
                   1405:     my ($courseid) = @_;
                   1406:     #already url style courseid
                   1407:     return $courseid if ($courseid =~ m{^/});
                   1408: 
                   1409:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1410: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1411: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1412: 	return "/$cdom/$cnum";
                   1413:     }
                   1414: 
                   1415:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1416:     if (exists($courseinfo{'num'})) {
                   1417: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1418:     }
                   1419: 
                   1420:     return undef;
                   1421: }
                   1422: 
1.298     matthew  1423: sub getsection {
                   1424:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1425:     my $cachetime=1800;
1.551     albertel 1426: 
                   1427:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1428:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1429:     if (defined($cached)) { return $result; }
                   1430: 
1.298     matthew  1431:     my %Pending; 
                   1432:     my %Expired;
                   1433:     #
                   1434:     # Each role can either have not started yet (pending), be active, 
                   1435:     #    or have expired.
                   1436:     #
                   1437:     # If there is an active role, we are done.
                   1438:     #
                   1439:     # If there is more than one role which has not started yet, 
                   1440:     #     choose the one which will start sooner
                   1441:     # If there is one role which has not started yet, return it.
                   1442:     #
                   1443:     # If there is more than one expired role, choose the one which ended last.
                   1444:     # If there is a role which has expired, return it.
                   1445:     #
1.815     albertel 1446:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1447:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1448:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1449:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1450:         my $section=$1;
                   1451:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1452:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1453:         my $now=time;
1.548     albertel 1454:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1455:             $Expired{$end}=$section;
                   1456:             next;
                   1457:         }
1.548     albertel 1458:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1459:             $Pending{$start}=$section;
                   1460:             next;
                   1461:         }
1.599     albertel 1462:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1463:     }
                   1464:     #
                   1465:     # Presumedly there will be few matching roles from the above
                   1466:     # loop and the sorting time will be negligible.
                   1467:     if (scalar(keys(%Pending))) {
                   1468:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1469:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1470:     } 
                   1471:     if (scalar(keys(%Expired))) {
                   1472:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1473:         my $time = pop(@sorted);
1.599     albertel 1474:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1475:     }
1.599     albertel 1476:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1477: }
1.70      www      1478: 
1.599     albertel 1479: sub save_cache {
                   1480:     &purge_remembered();
1.722     albertel 1481:     #&Apache::loncommon::validate_page();
1.620     albertel 1482:     undef(%env);
1.780     albertel 1483:     undef($env_loaded);
1.599     albertel 1484: }
1.452     albertel 1485: 
1.599     albertel 1486: my $to_remember=-1;
                   1487: my %remembered;
                   1488: my %accessed;
                   1489: my $kicks=0;
                   1490: my $hits=0;
1.849     albertel 1491: sub make_key {
                   1492:     my ($name,$id) = @_;
1.872     albertel 1493:     if (length($id) > 65 
                   1494: 	&& length(&escape($id)) > 200) {
                   1495: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1496:     }
1.849     albertel 1497:     return &escape($name.':'.$id);
                   1498: }
                   1499: 
1.599     albertel 1500: sub devalidate_cache_new {
                   1501:     my ($name,$id,$debug) = @_;
                   1502:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1503:     $id=&make_key($name,$id);
1.599     albertel 1504:     $memcache->delete($id);
                   1505:     delete($remembered{$id});
                   1506:     delete($accessed{$id});
                   1507: }
                   1508: 
                   1509: sub is_cached_new {
                   1510:     my ($name,$id,$debug) = @_;
1.849     albertel 1511:     $id=&make_key($name,$id);
1.599     albertel 1512:     if (exists($remembered{$id})) {
                   1513: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1514: 	$accessed{$id}=[&gettimeofday()];
                   1515: 	$hits++;
                   1516: 	return ($remembered{$id},1);
                   1517:     }
                   1518:     my $value = $memcache->get($id);
                   1519:     if (!(defined($value))) {
                   1520: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1521: 	return (undef,undef);
1.416     albertel 1522:     }
1.599     albertel 1523:     if ($value eq '__undef__') {
                   1524: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1525: 	$value=undef;
                   1526:     }
                   1527:     &make_room($id,$value,$debug);
                   1528:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1529:     return ($value,1);
                   1530: }
                   1531: 
                   1532: sub do_cache_new {
                   1533:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1534:     $id=&make_key($name,$id);
1.599     albertel 1535:     my $setvalue=$value;
                   1536:     if (!defined($setvalue)) {
                   1537: 	$setvalue='__undef__';
                   1538:     }
1.623     albertel 1539:     if (!defined($time) ) {
                   1540: 	$time=600;
                   1541:     }
1.599     albertel 1542:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1543:     my $result = $memcache->set($id,$setvalue,$time);
                   1544:     if (! $result) {
1.872     albertel 1545: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1546: 	$memcache->disconnect_all();
1.872     albertel 1547:     }
1.600     albertel 1548:     # need to make a copy of $value
1.919     albertel 1549:     &make_room($id,$value,$debug);
1.599     albertel 1550:     return $value;
                   1551: }
                   1552: 
                   1553: sub make_room {
                   1554:     my ($id,$value,$debug)=@_;
1.919     albertel 1555: 
                   1556:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1557:                                     : $value;
1.599     albertel 1558:     if ($to_remember<0) { return; }
                   1559:     $accessed{$id}=[&gettimeofday()];
                   1560:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1561:     my $to_kick;
                   1562:     my $max_time=0;
                   1563:     foreach my $other (keys(%accessed)) {
                   1564: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1565: 	    $to_kick=$other;
                   1566: 	    $max_time=&tv_interval($accessed{$other});
                   1567: 	}
                   1568:     }
                   1569:     delete($remembered{$to_kick});
                   1570:     delete($accessed{$to_kick});
                   1571:     $kicks++;
                   1572:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1573:     return;
                   1574: }
                   1575: 
1.599     albertel 1576: sub purge_remembered {
1.604     albertel 1577:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1578:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1579:     undef(%remembered);
                   1580:     undef(%accessed);
1.428     albertel 1581: }
1.70      www      1582: # ------------------------------------- Read an entry from a user's environment
                   1583: 
                   1584: sub userenvironment {
                   1585:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1586:     my $items;
                   1587:     foreach my $item (@what) {
                   1588:         $items.=&escape($item).'&';
                   1589:     }
                   1590:     $items=~s/\&$//;
1.70      www      1591:     my %returnhash=();
                   1592:     my @answer=split(/\&/,
1.976     raeburn  1593:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1594:                       &homeserver($unam,$udom)));
                   1595:     my $i;
                   1596:     for ($i=0;$i<=$#what;$i++) {
                   1597: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1598:     }
                   1599:     return %returnhash;
1.1       albertel 1600: }
                   1601: 
1.617     albertel 1602: # ---------------------------------------------------------- Get a studentphoto
                   1603: sub studentphoto {
                   1604:     my ($udom,$unam,$ext) = @_;
                   1605:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1606:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1607:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1608:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1609:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1610:             } else {
                   1611:                 my ($result,$perm_reqd)=
1.707     albertel 1612: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1613:                 if ($result eq 'ok') {
                   1614:                     if (!($perm_reqd eq 'yes')) {
                   1615:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1616:                     }
                   1617:                 }
                   1618:             }
                   1619:         }
                   1620:     } else {
                   1621:         my ($result,$perm_reqd) = 
1.707     albertel 1622: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1623:         if ($result eq 'ok') {
                   1624:             if (!($perm_reqd eq 'yes')) {
                   1625:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1626:             }
                   1627:         }
                   1628:     }
                   1629:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1630: }
                   1631: 
                   1632: sub retrievestudentphoto {
                   1633:     my ($udom,$unam,$ext,$type) = @_;
                   1634:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1635:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1636:     if ($ret eq 'ok') {
                   1637:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1638:         if ($type eq 'thumbnail') {
                   1639:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1640:         }
                   1641:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1642:         return $tokenurl;
                   1643:     } else {
                   1644:         if ($type eq 'thumbnail') {
                   1645:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1646:         } else { 
                   1647:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1648:         }
1.617     albertel 1649:     }
                   1650: }
                   1651: 
1.263     www      1652: # -------------------------------------------------------------------- New chat
                   1653: 
                   1654: sub chatsend {
1.724     raeburn  1655:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1656:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1658:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1659:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1660: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1661: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1662: }
                   1663: 
                   1664: # ------------------------------------------ Find current version of a resource
                   1665: 
                   1666: sub getversion {
                   1667:     my $fname=&clutter(shift);
                   1668:     unless ($fname=~/^\/res\//) { return -1; }
                   1669:     return &currentversion(&filelocation('',$fname));
                   1670: }
                   1671: 
                   1672: sub currentversion {
                   1673:     my $fname=shift;
1.599     albertel 1674:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1675:     if (defined($cached)) { return $result; }
1.292     www      1676:     my $author=$fname;
                   1677:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1678:     my ($udom,$uname)=split(/\//,$author);
                   1679:     my $home=homeserver($uname,$udom);
                   1680:     if ($home eq 'no_host') { 
                   1681:         return -1; 
                   1682:     }
                   1683:     my $answer=reply("currentversion:$fname",$home);
                   1684:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1685: 	return -1;
                   1686:     }
1.599     albertel 1687:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1688: }
                   1689: 
1.1       albertel 1690: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1691: 
1.1       albertel 1692: sub subscribe {
                   1693:     my $fname=shift;
1.761     raeburn  1694:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1695:     $fname=~s/[\n\r]//g;
1.1       albertel 1696:     my $author=$fname;
                   1697:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1698:     my ($udom,$uname)=split(/\//,$author);
                   1699:     my $home=homeserver($uname,$udom);
1.335     albertel 1700:     if ($home eq 'no_host') {
                   1701:         return 'not_found';
1.1       albertel 1702:     }
                   1703:     my $answer=reply("sub:$fname",$home);
1.64      www      1704:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1705: 	$answer.=' by '.$home;
                   1706:     }
1.1       albertel 1707:     return $answer;
                   1708: }
                   1709:     
1.8       www      1710: # -------------------------------------------------------------- Replicate file
                   1711: 
                   1712: sub repcopy {
                   1713:     my $filename=shift;
1.23      www      1714:     $filename=~s/\/+/\//g;
1.607     raeburn  1715:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1716:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1717:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1718: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1719: 	return &repcopy_userfile($filename);
                   1720:     }
1.532     albertel 1721:     $filename=~s/[\n\r]//g;
1.8       www      1722:     my $transname="$filename.in.transfer";
1.828     www      1723: # FIXME: this should flock
1.607     raeburn  1724:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1725:     my $remoteurl=subscribe($filename);
1.64      www      1726:     if ($remoteurl =~ /^con_lost by/) {
                   1727: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1728:            return 'unavailable';
1.8       www      1729:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1730: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1731: 	   return 'not_found';
1.64      www      1732:     } elsif ($remoteurl =~ /^rejected by/) {
                   1733: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1734:            return 'forbidden';
1.20      www      1735:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1736:            return 'ok';
1.8       www      1737:     } else {
1.290     www      1738:         my $author=$filename;
                   1739:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1740:         my ($udom,$uname)=split(/\//,$author);
                   1741:         my $home=homeserver($uname,$udom);
                   1742:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1743:            my @parts=split(/\//,$filename);
                   1744:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1745:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1746:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1747: 	       return 'bad_request';
1.8       www      1748:            }
                   1749:            my $count;
                   1750:            for ($count=5;$count<$#parts;$count++) {
                   1751:                $path.="/$parts[$count]";
                   1752:                if ((-e $path)!=1) {
                   1753: 		   mkdir($path,0777);
                   1754:                }
                   1755:            }
                   1756:            my $ua=new LWP::UserAgent;
                   1757:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1758:            my $response=$ua->request($request,$transname);
                   1759:            if ($response->is_error()) {
                   1760: 	       unlink($transname);
                   1761:                my $message=$response->status_line;
1.672     albertel 1762:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1763:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1764:                return 'unavailable';
1.8       www      1765:            } else {
1.16      www      1766: 	       if ($remoteurl!~/\.meta$/) {
                   1767:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1768:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1769:                   if ($mresponse->is_error()) {
                   1770: 		      unlink($filename.'.meta');
                   1771:                       &logthis(
1.672     albertel 1772:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1773:                   }
                   1774: 	       }
1.8       www      1775:                rename($transname,$filename);
1.607     raeburn  1776:                return 'ok';
1.8       www      1777:            }
1.290     www      1778:        }
1.8       www      1779:     }
1.330     www      1780: }
                   1781: 
                   1782: # ------------------------------------------------ Get server side include body
                   1783: sub ssi_body {
1.381     albertel 1784:     my ($filelink,%form)=@_;
1.606     matthew  1785:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1786:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1787:     }
1.953     www      1788:     my $output='';
                   1789:     my $response;
1.976.2.3  raeburn  1790:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1791:        ($output,$response)=&externalssi($filelink);
1.953     www      1792:     } else {
                   1793:        ($output,$response)=&ssi($filelink,%form);
                   1794:     }
1.778     albertel 1795:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1796:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1797:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1798:     if (wantarray) {
                   1799:         return ($output, $response);
                   1800:     } else {
                   1801:         return $output;
                   1802:     }
1.8       www      1803: }
                   1804: 
1.15      www      1805: # --------------------------------------------------------- Server Side Include
                   1806: 
1.782     albertel 1807: sub absolute_url {
                   1808:     my ($host_name) = @_;
                   1809:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1810:     if ($host_name eq '') {
                   1811: 	$host_name = $ENV{'SERVER_NAME'};
                   1812:     }
                   1813:     return $protocol.$host_name;
                   1814: }
                   1815: 
1.942     foxr     1816: #
                   1817: #   Server side include.
                   1818: # Parameters:
                   1819: #  fn     Possibly encrypted resource name/id.
                   1820: #  form   Hash that describes how the rendering should be done
                   1821: #         and other things.
1.944     foxr     1822: # Returns:
1.950     raeburn  1823: #   Scalar context: The content of the response.
                   1824: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1825: #     
1.15      www      1826: sub ssi {
                   1827: 
1.944     foxr     1828:     my ($fn,%form)=@_;
1.15      www      1829:     my $ua=new LWP::UserAgent;
1.23      www      1830:     my $request;
1.711     albertel 1831: 
                   1832:     $form{'no_update_last_known'}=1;
1.895     albertel 1833:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1834:     if (%form) {
1.782     albertel 1835:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1836:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1837:     } else {
1.782     albertel 1838:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1839:     }
                   1840: 
1.15      www      1841:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1842:     my $response=$ua->request($request);
                   1843: 
1.944     foxr     1844:     if (wantarray) {
                   1845: 	return ($response->content, $response);
                   1846:     } else {
                   1847: 	return $response->content;
1.942     foxr     1848:     }
1.324     www      1849: }
                   1850: 
                   1851: sub externalssi {
                   1852:     my ($url)=@_;
                   1853:     my $ua=new LWP::UserAgent;
                   1854:     my $request=new HTTP::Request('GET',$url);
                   1855:     my $response=$ua->request($request);
1.954     raeburn  1856:     if (wantarray) {
                   1857:         return ($response->content, $response);
                   1858:     } else {
                   1859:         return $response->content;
                   1860:     }
1.15      www      1861: }
1.254     www      1862: 
1.492     albertel 1863: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1864: 
                   1865: sub allowuploaded {
                   1866:     my ($srcurl,$url)=@_;
                   1867:     $url=&clutter(&declutter($url));
                   1868:     my $dir=$url;
                   1869:     $dir=~s/\/[^\/]+$//;
                   1870:     my %httpref=();
                   1871:     my $httpurl=&hreflocation('',$url);
                   1872:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1873:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1874: }
1.477     raeburn  1875: 
1.478     albertel 1876: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1877: # input: action, courseID, current domain, intended
1.637     raeburn  1878: #        path to file, source of file, instruction to parse file for objects,
                   1879: #        ref to hash for embedded objects,
                   1880: #        ref to hash for codebase of java objects.
                   1881: #
1.485     raeburn  1882: # output: url to file (if action was uploaddoc), 
                   1883: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1884: #
1.478     albertel 1885: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1886: # course.
1.477     raeburn  1887: #
1.478     albertel 1888: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1889: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1890: #          course's home server.
1.477     raeburn  1891: #
1.478     albertel 1892: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1893: #          be copied from $source (current location) to 
                   1894: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1895: #         and will then be copied to
                   1896: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1897: #         course's home server.
1.485     raeburn  1898: #
1.481     raeburn  1899: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1900: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1901: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1902: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1903: #         in course's home server.
1.637     raeburn  1904: #
1.477     raeburn  1905: 
                   1906: sub process_coursefile {
1.638     albertel 1907:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1908:     my $fetchresult;
1.638     albertel 1909:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1910:     if ($action eq 'propagate') {
1.638     albertel 1911:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1912: 			     $home);
1.481     raeburn  1913:     } else {
1.477     raeburn  1914:         my $fpath = '';
                   1915:         my $fname = $file;
1.478     albertel 1916:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1917:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1918:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1919:         if ($action eq 'copy') {
                   1920:             if ($source eq '') {
                   1921:                 $fetchresult = 'no source file';
                   1922:                 return $fetchresult;
                   1923:             } else {
                   1924:                 my $destination = $filepath.'/'.$fname;
                   1925:                 rename($source,$destination);
                   1926:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1927:                                  $home);
1.481     raeburn  1928:             }
                   1929:         } elsif ($action eq 'uploaddoc') {
                   1930:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1931:             print $fh $env{'form.'.$source};
1.481     raeburn  1932:             close($fh);
1.637     raeburn  1933:             if ($parser eq 'parse') {
1.961     raeburn  1934:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1935:                 unless ($parse_result eq 'ok') {
                   1936:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1937:                 }
                   1938:             }
1.477     raeburn  1939:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1940:                                  $home);
1.481     raeburn  1941:             if ($fetchresult eq 'ok') {
                   1942:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1943:             } else {
                   1944:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1945:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1946:                 return '/adm/notfound.html';
                   1947:             }
1.477     raeburn  1948:         }
                   1949:     }
1.485     raeburn  1950:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1951:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1952:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1953:     }
                   1954:     return $fetchresult;
                   1955: }
                   1956: 
1.637     raeburn  1957: sub build_filepath {
                   1958:     my ($fpath) = @_;
                   1959:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1960:     unless ($fpath eq '') {
                   1961:         my @parts=split('/',$fpath);
                   1962:         foreach my $part (@parts) {
                   1963:             $filepath.= '/'.$part;
                   1964:             if ((-e $filepath)!=1) {
                   1965:                 mkdir($filepath,0777);
                   1966:             }
                   1967:         }
                   1968:     }
                   1969:     return $filepath;
                   1970: }
                   1971: 
                   1972: sub store_edited_file {
1.638     albertel 1973:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1974:     my $file = $primary_url;
                   1975:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1976:     my $fpath = '';
                   1977:     my $fname = $file;
                   1978:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1979:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1980:     my $filepath = &build_filepath($fpath);
                   1981:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1982:     print $fh $content;
                   1983:     close($fh);
1.638     albertel 1984:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1985:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1986: 			  $home);
1.637     raeburn  1987:     if ($$fetchresult eq 'ok') {
                   1988:         return '/uploaded/'.$fpath.'/'.$fname;
                   1989:     } else {
1.638     albertel 1990:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1991: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1992:         return '/adm/notfound.html';
                   1993:     }
                   1994: }
                   1995: 
1.531     albertel 1996: sub clean_filename {
1.831     albertel 1997:     my ($fname,$args)=@_;
1.315     www      1998: # Replace Windows backslashes by forward slashes
1.257     www      1999:     $fname=~s/\\/\//g;
1.831     albertel 2000:     if (!$args->{'keep_path'}) {
                   2001:         # Get rid of everything but the actual filename
                   2002: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2003:     }
1.315     www      2004: # Replace spaces by underscores
                   2005:     $fname=~s/\s+/\_/g;
                   2006: # Replace all other weird characters by nothing
1.831     albertel 2007:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2008: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2009: # numbers
                   2010:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2011:     return $fname;
                   2012: }
                   2013: 
1.608     albertel 2014: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2015: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2016: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2017: #        $coursedoc - if true up to the current course
                   2018: #                     if false
                   2019: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2020: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2021: #        $allfiles - reference to hash for embedded objects
                   2022: #        $codebase - reference to hash for codebase of java objects
                   2023: #        $desuname - username for permanent storage of uploaded file
                   2024: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2025: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2026: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2027: # 
1.686     albertel 2028: # output: url of file in userspace, or error: <message> 
                   2029: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2030: 
                   2031: 
1.531     albertel 2032: sub userfileupload {
1.860     raeburn  2033:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2034:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2035:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2036:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2037:     $fname=&clean_filename($fname);
1.315     www      2038: # See if there is anything left
1.257     www      2039:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2040:     chop($env{'form.'.$formname});
1.523     raeburn  2041:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2042:         my $now = time;
                   2043:         my $filepath = 'tmp/helprequests/'.$now;
                   2044:         my @parts=split(/\//,$filepath);
                   2045:         my $fullpath = $perlvar{'lonDaemons'};
                   2046:         for (my $i=0;$i<@parts;$i++) {
                   2047:             $fullpath .= '/'.$parts[$i];
                   2048:             if ((-e $fullpath)!=1) {
                   2049:                 mkdir($fullpath,0777);
                   2050:             }
                   2051:         }
                   2052:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2053:         print $fh $env{'form.'.$formname};
1.523     raeburn  2054:         close($fh);
1.741     raeburn  2055:         return $fullpath.'/'.$fname;
                   2056:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2057:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2058:                        '_'.$env{'user.domain'}.'/pending';
                   2059:         my @parts=split(/\//,$filepath);
                   2060:         my $fullpath = $perlvar{'lonDaemons'};
                   2061:         for (my $i=0;$i<@parts;$i++) {
                   2062:             $fullpath .= '/'.$parts[$i];
                   2063:             if ((-e $fullpath)!=1) {
                   2064:                 mkdir($fullpath,0777);
                   2065:             }
                   2066:         }
                   2067:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2068:         print $fh $env{'form.'.$formname};
                   2069:         close($fh);
                   2070:         return $fullpath.'/'.$fname;
1.523     raeburn  2071:     }
1.719     banghart 2072:     
1.258     www      2073: # Create the directory if not present
1.493     albertel 2074:     $fname="$subdir/$fname";
1.259     www      2075:     if ($coursedoc) {
1.638     albertel 2076: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2077: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2078:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2079:             return &finishuserfileupload($docuname,$docudom,
                   2080: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2081: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2082:         } else {
1.620     albertel 2083:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2084:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2085: 				       $fname,$formname,$parser,
                   2086: 				       $allfiles,$codebase);
1.481     raeburn  2087:         }
1.719     banghart 2088:     } elsif (defined($destuname)) {
                   2089:         my $docuname=$destuname;
                   2090:         my $docudom=$destudom;
1.860     raeburn  2091: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2092: 				     $parser,$allfiles,$codebase,
                   2093:                                      $thumbwidth,$thumbheight);
1.719     banghart 2094:         
1.259     www      2095:     } else {
1.638     albertel 2096:         my $docuname=$env{'user.name'};
                   2097:         my $docudom=$env{'user.domain'};
1.714     raeburn  2098:         if (exists($env{'form.group'})) {
                   2099:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2100:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2101:         }
1.860     raeburn  2102: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2103: 				     $parser,$allfiles,$codebase,
                   2104:                                      $thumbwidth,$thumbheight);
1.259     www      2105:     }
1.271     www      2106: }
                   2107: 
                   2108: sub finishuserfileupload {
1.860     raeburn  2109:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2110:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2111:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2112:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2113:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2114:     $file=$fname;
                   2115:     if ($fname=~m|/|) {
                   2116:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2117: 	$path.=$fnamepath.'/';
                   2118:     }
1.259     www      2119:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2120:     my $count;
                   2121:     for ($count=4;$count<=$#parts;$count++) {
                   2122:         $filepath.="/$parts[$count]";
                   2123:         if ((-e $filepath)!=1) {
                   2124: 	    mkdir($filepath,0777);
                   2125:         }
                   2126:     }
                   2127: # Save the file
                   2128:     {
1.701     albertel 2129: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2130: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2131: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2132: 	    return '/adm/notfound.html';
                   2133: 	}
                   2134: 	if (!print FH ($env{'form.'.$formname})) {
                   2135: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2136: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2137: 	    return '/adm/notfound.html';
                   2138: 	}
1.570     albertel 2139: 	close(FH);
1.258     www      2140:     }
1.637     raeburn  2141:     if ($parser eq 'parse') {
1.961     raeburn  2142:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2143: 						   $codebase);
1.637     raeburn  2144:         unless ($parse_result eq 'ok') {
1.638     albertel 2145:             &logthis('Failed to parse '.$filepath.$file.
                   2146: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2147:         }
                   2148:     }
1.860     raeburn  2149:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2150:         my $input = $filepath.'/'.$file;
                   2151:         my $output = $filepath.'/'.'tn-'.$file;
                   2152:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2153:         system("convert -sample $thumbsize $input $output");
                   2154:         if (-e $filepath.'/'.'tn-'.$file) {
                   2155:             $fetchthumb  = 1; 
                   2156:         }
                   2157:     }
1.858     raeburn  2158:  
1.259     www      2159: # Notify homeserver to grep it
                   2160: #
1.638     albertel 2161:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2162:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2163:     if ($fetchresult eq 'ok') {
1.860     raeburn  2164:         if ($fetchthumb) {
                   2165:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2166:             if ($thumbresult ne 'ok') {
                   2167:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2168:                          $docuhome.': '.$thumbresult);
                   2169:             }
                   2170:         }
1.259     www      2171: #
1.258     www      2172: # Return the URL to it
1.494     albertel 2173:         return '/uploaded/'.$path.$file;
1.263     www      2174:     } else {
1.494     albertel 2175:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2176: 		 ': '.$fetchresult);
1.263     www      2177:         return '/adm/notfound.html';
1.858     raeburn  2178:     }
1.493     albertel 2179: }
                   2180: 
1.637     raeburn  2181: sub extract_embedded_items {
1.961     raeburn  2182:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2183:     my @state = ();
                   2184:     my %javafiles = (
                   2185:                       codebase => '',
                   2186:                       code => '',
                   2187:                       archive => ''
                   2188:                     );
                   2189:     my %mediafiles = (
                   2190:                       src => '',
                   2191:                       movie => '',
                   2192:                      );
1.648     raeburn  2193:     my $p;
                   2194:     if ($content) {
                   2195:         $p = HTML::LCParser->new($content);
                   2196:     } else {
1.961     raeburn  2197:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2198:     }
1.641     albertel 2199:     while (my $t=$p->get_token()) {
1.640     albertel 2200: 	if ($t->[0] eq 'S') {
                   2201: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2202: 	    push(@state, $tagname);
1.648     raeburn  2203:             if (lc($tagname) eq 'allow') {
                   2204:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2205:             }
1.640     albertel 2206: 	    if (lc($tagname) eq 'img') {
                   2207: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2208: 	    }
1.886     albertel 2209: 	    if (lc($tagname) eq 'a') {
                   2210: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2211: 	    }
1.645     raeburn  2212:             if (lc($tagname) eq 'script') {
                   2213:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2214:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2215:                 } else {
                   2216:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2217:                 }
                   2218:             }
                   2219:             if (lc($tagname) eq 'link') {
                   2220:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2221:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2222:                 }
                   2223:             }
1.640     albertel 2224: 	    if (lc($tagname) eq 'object' ||
                   2225: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2226: 		foreach my $item (keys(%javafiles)) {
                   2227: 		    $javafiles{$item} = '';
                   2228: 		}
                   2229: 	    }
                   2230: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2231: 		my $name = lc($attr->{'name'});
                   2232: 		foreach my $item (keys(%javafiles)) {
                   2233: 		    if ($name eq $item) {
                   2234: 			$javafiles{$item} = $attr->{'value'};
                   2235: 			last;
                   2236: 		    }
                   2237: 		}
                   2238: 		foreach my $item (keys(%mediafiles)) {
                   2239: 		    if ($name eq $item) {
                   2240: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2241: 			last;
                   2242: 		    }
                   2243: 		}
                   2244: 	    }
                   2245: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2246: 		foreach my $item (keys(%javafiles)) {
                   2247: 		    if ($attr->{$item}) {
                   2248: 			$javafiles{$item} = $attr->{$item};
                   2249: 			last;
                   2250: 		    }
                   2251: 		}
                   2252: 		foreach my $item (keys(%mediafiles)) {
                   2253: 		    if ($attr->{$item}) {
                   2254: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2255: 			last;
                   2256: 		    }
                   2257: 		}
                   2258: 	    }
                   2259: 	} elsif ($t->[0] eq 'E') {
                   2260: 	    my ($tagname) = ($t->[1]);
                   2261: 	    if ($javafiles{'codebase'} ne '') {
                   2262: 		$javafiles{'codebase'} .= '/';
                   2263: 	    }  
                   2264: 	    if (lc($tagname) eq 'applet' ||
                   2265: 		lc($tagname) eq 'object' ||
                   2266: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2267: 		) {
                   2268: 		foreach my $item (keys(%javafiles)) {
                   2269: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2270: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2271: 			&add_filetype($allfiles,$file,$item);
                   2272: 		    }
                   2273: 		}
                   2274: 	    } 
                   2275: 	    pop @state;
                   2276: 	}
                   2277:     }
1.637     raeburn  2278:     return 'ok';
                   2279: }
                   2280: 
1.639     albertel 2281: sub add_filetype {
                   2282:     my ($allfiles,$file,$type)=@_;
                   2283:     if (exists($allfiles->{$file})) {
                   2284: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2285: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2286: 	}
                   2287:     } else {
                   2288: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2289:     }
                   2290: }
                   2291: 
1.493     albertel 2292: sub removeuploadedurl {
                   2293:     my ($url)=@_;
                   2294:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2295:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2296: }
                   2297: 
                   2298: sub removeuserfile {
                   2299:     my ($docuname,$docudom,$fname)=@_;
                   2300:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2301:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2302:     if ($result eq 'ok') {
                   2303:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2304:             my $metafile = $fname.'.meta';
                   2305:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2306: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2307:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2308:             my $sqlresult = 
1.823     albertel 2309:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2310:                                         'portfolio_metadata',$group,
                   2311:                                         'delete');
1.798     raeburn  2312:         }
                   2313:     }
                   2314:     return $result;
1.257     www      2315: }
1.15      www      2316: 
1.530     albertel 2317: sub mkdiruserfile {
                   2318:     my ($docuname,$docudom,$dir)=@_;
                   2319:     my $home=&homeserver($docuname,$docudom);
                   2320:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2321: }
                   2322: 
1.531     albertel 2323: sub renameuserfile {
                   2324:     my ($docuname,$docudom,$old,$new)=@_;
                   2325:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2326:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2327:                         &escape("$old").':'.&escape("$new"),$home);
                   2328:     if ($result eq 'ok') {
                   2329:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2330:             my $oldmeta = $old.'.meta';
                   2331:             my $newmeta = $new.'.meta';
                   2332:             my $metaresult = 
                   2333:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2334: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2335:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2336:             my $sqlresult = 
1.823     albertel 2337:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2338:                                         'portfolio_metadata',$group,
                   2339:                                         'delete');
1.798     raeburn  2340:         }
                   2341:     }
                   2342:     return $result;
1.531     albertel 2343: }
                   2344: 
1.14      www      2345: # ------------------------------------------------------------------------- Log
                   2346: 
                   2347: sub log {
                   2348:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2349:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2350: }
                   2351: 
                   2352: # ------------------------------------------------------------------ Course Log
1.352     www      2353: #
                   2354: # This routine flushes several buffers of non-mission-critical nature
                   2355: #
1.157     www      2356: 
                   2357: sub flushcourselogs {
1.352     www      2358:     &logthis('Flushing log buffers');
                   2359: #
                   2360: # course logs
                   2361: # This is a log of all transactions in a course, which can be used
                   2362: # for data mining purposes
                   2363: #
                   2364: # It also collects the courseid database, which lists last transaction
                   2365: # times and course titles for all courseids
                   2366: #
                   2367:     my %courseidbuffer=();
1.921     raeburn  2368:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2369:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2370: 		          &escape($courselogs{$crsid}),
                   2371: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2372: 	    delete $courselogs{$crsid};
                   2373:         } else {
                   2374:             &logthis('Failed to flush log buffer for '.$crsid);
                   2375:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2376:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2377:                         " exceeded maximum size, deleting.</font>");
                   2378:                delete $courselogs{$crsid};
                   2379:             }
1.352     www      2380:         }
1.920     raeburn  2381:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2382:             'description' => $coursedescrbuf{$crsid},
                   2383:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2384:             'type'        => $coursetypebuf{$crsid},
                   2385:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2386:         };
1.191     harris41 2387:     }
1.352     www      2388: #
                   2389: # Write course id database (reverse lookup) to homeserver of courses 
                   2390: # Is used in pickcourse
                   2391: #
1.840     albertel 2392:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2393:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2394:                                     $courseidbuffer{$crs_home},
                   2395:                                     $crs_home,'timeonly');
1.352     www      2396:     }
                   2397: #
                   2398: # File accesses
                   2399: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2400: #
1.449     matthew  2401:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2402:         if ($entry =~ /___count$/) {
                   2403:             my ($dom,$name);
1.807     albertel 2404:             ($dom,$name,undef)=
1.811     albertel 2405: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2406:             if (! defined($dom) || $dom eq '' || 
                   2407:                 ! defined($name) || $name eq '') {
1.620     albertel 2408:                 my $cid = $env{'request.course.id'};
                   2409:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2410:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2411:             }
1.450     matthew  2412:             my $value = $accesshash{$entry};
                   2413:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2414:             my %temphash=($url => $value);
1.449     matthew  2415:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2416:             if ($result eq 'ok') {
                   2417:                 delete $accesshash{$entry};
                   2418:             } elsif ($result eq 'unknown_cmd') {
                   2419:                 # Target server has old code running on it.
1.450     matthew  2420:                 my %temphash=($entry => $value);
1.449     matthew  2421:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2422:                     delete $accesshash{$entry};
                   2423:                 }
                   2424:             }
                   2425:         } else {
1.811     albertel 2426:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2427:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2428:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2429:                 delete $accesshash{$entry};
                   2430:             }
1.185     www      2431:         }
1.191     harris41 2432:     }
1.352     www      2433: #
                   2434: # Roles
                   2435: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2436: #
1.800     albertel 2437:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2438:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2439: 	    split(/\:/,$entry);
                   2440:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2441:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2442:                 $rudom,$runame) eq 'ok') {
                   2443: 	    delete $userrolehash{$entry};
                   2444:         }
                   2445:     }
1.662     raeburn  2446: #
                   2447: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2448: #
                   2449:     my %domrolebuffer = ();
                   2450:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2451:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2452:         if ($domrolebuffer{$rudom}) {
                   2453:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2454:                       '='.&escape($domainrolehash{$entry});
                   2455:         } else {
                   2456:             $domrolebuffer{$rudom}.=&escape($entry).
                   2457:                       '='.&escape($domainrolehash{$entry});
                   2458:         }
                   2459:         delete $domainrolehash{$entry};
                   2460:     }
                   2461:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2462: 	my %servers = &get_servers($dom,'library');
                   2463: 	foreach my $tryserver (keys(%servers)) {
                   2464: 	    unless (&reply('domroleput:'.$dom.':'.
                   2465: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2466: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2467: 	    }
1.662     raeburn  2468:         }
                   2469:     }
1.186     www      2470:     $dumpcount++;
1.157     www      2471: }
                   2472: 
                   2473: sub courselog {
                   2474:     my $what=shift;
1.158     www      2475:     $what=time.':'.$what;
1.620     albertel 2476:     unless ($env{'request.course.id'}) { return ''; }
                   2477:     $coursedombuf{$env{'request.course.id'}}=
                   2478:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2479:     $coursenumbuf{$env{'request.course.id'}}=
                   2480:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2481:     $coursehombuf{$env{'request.course.id'}}=
                   2482:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2483:     $coursedescrbuf{$env{'request.course.id'}}=
                   2484:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2485:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2486:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2487:     $courseownerbuf{$env{'request.course.id'}}=
                   2488:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2489:     $coursetypebuf{$env{'request.course.id'}}=
                   2490:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2491:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2492: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2493:     } else {
1.620     albertel 2494: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2495:     }
1.620     albertel 2496:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2497: 	&flushcourselogs();
                   2498:     }
1.158     www      2499: }
                   2500: 
                   2501: sub courseacclog {
                   2502:     my $fnsymb=shift;
1.620     albertel 2503:     unless ($env{'request.course.id'}) { return ''; }
                   2504:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2505:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2506:         $what.=':POST';
1.583     matthew  2507:         # FIXME: Probably ought to escape things....
1.800     albertel 2508: 	foreach my $key (keys(%env)) {
                   2509:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2510:                 my $formitem = $1;
                   2511:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2512:                     $what.=':'.$formitem.'='.$env{$key};
                   2513:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2514:                     $what.=':'.$formitem.'='.$env{$key};
                   2515:                 }
1.158     www      2516:             }
1.191     harris41 2517:         }
1.583     matthew  2518:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2519:         # FIXME: We should not be depending on a form parameter that someone
                   2520:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2521:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2522:             $what.= ':POST';
                   2523:             # FIXME: Probably ought to escape things....
                   2524:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2525:                                  'crsdiscuss') {
1.620     albertel 2526:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2527:             }
                   2528:         }
1.158     www      2529:     }
                   2530:     &courselog($what);
1.149     www      2531: }
                   2532: 
1.185     www      2533: sub countacc {
                   2534:     my $url=&declutter(shift);
1.458     matthew  2535:     return if (! defined($url) || $url eq '');
1.620     albertel 2536:     unless ($env{'request.course.id'}) { return ''; }
                   2537:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2538:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2539:     $accesshash{$key}++;
1.185     www      2540: }
1.349     www      2541: 
1.361     www      2542: sub linklog {
                   2543:     my ($from,$to)=@_;
                   2544:     $from=&declutter($from);
                   2545:     $to=&declutter($to);
                   2546:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2547:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2548: }
                   2549:   
1.349     www      2550: sub userrolelog {
                   2551:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2552:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2553:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2554:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2555:         ($trole=~/^ta/)) {
1.350     www      2556:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2557:        $userrolehash
                   2558:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2559:                     =$tend.':'.$tstart;
1.662     raeburn  2560:     }
1.898     albertel 2561:     if (($env{'request.role'} =~ /dc\./) &&
                   2562: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2563: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2564: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2565:        $userrolehash
                   2566:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2567:                     =$tend.':'.$tstart;
                   2568:     }
1.662     raeburn  2569:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2570:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2571:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2572:         ($trole=~/^sc/)) {
                   2573:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2574:        $domainrolehash
                   2575:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2576:                     = $tend.':'.$tstart;
                   2577:     }
1.351     www      2578: }
                   2579: 
1.957     raeburn  2580: sub courserolelog {
                   2581:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2582:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2583:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2584:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2585:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2586:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2587:             my $cdom = $1;
                   2588:             my $cnum = $2;
                   2589:             my $sec = $3;
                   2590:             my $namespace = 'rolelog';
                   2591:             my %storehash = (
                   2592:                                role    => $trole,
                   2593:                                start   => $tstart,
                   2594:                                end     => $tend,
                   2595:                                selfenroll => $selfenroll,
                   2596:                                context    => $context,
                   2597:                             );
                   2598:             if ($trole eq 'gr') {
                   2599:                 $namespace = 'groupslog';
                   2600:                 $storehash{'group'} = $sec;
                   2601:             } else {
                   2602:                 $storehash{'section'} = $sec;
                   2603:             }
                   2604:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2605:         }
                   2606:     }
                   2607:     return;
                   2608: }
                   2609: 
1.351     www      2610: sub get_course_adv_roles {
1.948     raeburn  2611:     my ($cid,$codes) = @_;
1.620     albertel 2612:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2613:     my %coursehash=&coursedescription($cid);
1.470     www      2614:     my %nothide=();
1.800     albertel 2615:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2616:         if ($user !~ /:/) {
                   2617: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2618:         } else {
                   2619:             $nothide{$user}=1;
                   2620:         }
1.470     www      2621:     }
1.351     www      2622:     my %returnhash=();
                   2623:     my %dumphash=
                   2624:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2625:     my $now=time;
1.800     albertel 2626:     foreach my $entry (keys %dumphash) {
                   2627: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2628:         if (($tstart) && ($tstart<0)) { next; }
                   2629:         if (($tend) && ($tend<$now)) { next; }
                   2630:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2631:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2632: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2633: 	if ((&privileged($username,$domain)) && 
                   2634: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2635: 	if ($role eq 'cr') { next; }
1.948     raeburn  2636:         if ($codes) {
                   2637:             if ($section) { $role .= ':'.$section; }
                   2638:             if ($returnhash{$role}) {
                   2639:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2640:             } else {
                   2641:                 $returnhash{$role}=$username.':'.$domain;
                   2642:             }
1.351     www      2643:         } else {
1.948     raeburn  2644:             my $key=&plaintext($role);
1.973     bisitz   2645:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2646:             if ($returnhash{$key}) {
                   2647: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2648:             } else {
                   2649:                 $returnhash{$key}=$username.':'.$domain;
                   2650:             }
1.351     www      2651:         }
1.948     raeburn  2652:     }
1.400     www      2653:     return %returnhash;
                   2654: }
                   2655: 
                   2656: sub get_my_roles {
1.937     raeburn  2657:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2658:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2659:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2660:     my (%dumphash,%nothide);
1.858     raeburn  2661:     if ($context eq 'userroles') { 
                   2662:         %dumphash = &dump('roles',$udom,$uname);
                   2663:     } else {
                   2664:         %dumphash=
1.400     www      2665:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2666:         if ($hidepriv) {
                   2667:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2668:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2669:                 if ($user !~ /:/) {
                   2670:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2671:                 } else {
                   2672:                     $nothide{$user} = 1;
                   2673:                 }
                   2674:             }
                   2675:         }
1.858     raeburn  2676:     }
1.400     www      2677:     my %returnhash=();
                   2678:     my $now=time;
1.800     albertel 2679:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2680:         my ($role,$tend,$tstart);
                   2681:         if ($context eq 'userroles') {
                   2682: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2683:         } else {
                   2684:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2685:         }
1.400     www      2686:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2687:         my $status = 'active';
1.939     raeburn  2688:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2689:             $status = 'previous';
                   2690:         } 
                   2691:         if (($tstart) && ($now<$tstart)) {
                   2692:             $status = 'future';
                   2693:         }
                   2694:         if (ref($types) eq 'ARRAY') {
                   2695:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2696:                 next;
                   2697:             } 
                   2698:         } else {
                   2699:             if ($status ne 'active') {
                   2700:                 next;
                   2701:             }
                   2702:         }
1.867     raeburn  2703:         my ($rolecode,$username,$domain,$section,$area);
                   2704:         if ($context eq 'userroles') {
                   2705:             ($area,$rolecode) = split(/_/,$entry);
                   2706:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2707:         } else {
                   2708:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2709:         }
1.832     raeburn  2710:         if (ref($roledoms) eq 'ARRAY') {
                   2711:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2712:                 next;
                   2713:             }
                   2714:         }
                   2715:         if (ref($roles) eq 'ARRAY') {
                   2716:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2717:                 if ($role =~ /^cr\//) {
                   2718:                     if (!grep(/^cr$/,@{$roles})) {
                   2719:                         next;
                   2720:                     }
                   2721:                 } else {
                   2722:                     next;
                   2723:                 }
1.832     raeburn  2724:             }
1.867     raeburn  2725:         }
1.937     raeburn  2726:         if ($hidepriv) {
                   2727:             if ((&privileged($username,$domain)) &&
                   2728:                 (!$nothide{$username.':'.$domain})) { 
                   2729:                 next;
                   2730:             }
                   2731:         }
1.933     raeburn  2732:         if ($withsec) {
                   2733:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2734:                 $tstart.':'.$tend;
                   2735:         } else {
                   2736:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2737:         }
1.832     raeburn  2738:     }
1.373     www      2739:     return %returnhash;
1.399     www      2740: }
                   2741: 
                   2742: # ----------------------------------------------------- Frontpage Announcements
                   2743: #
                   2744: #
                   2745: 
                   2746: sub postannounce {
                   2747:     my ($server,$text)=@_;
1.844     albertel 2748:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2749:     unless ($text=~/\w/) { $text=''; }
                   2750:     return &reply('setannounce:'.&escape($text),$server);
                   2751: }
                   2752: 
                   2753: sub getannounce {
1.448     albertel 2754: 
                   2755:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2756: 	my $announcement='';
1.800     albertel 2757: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2758: 	close($fh);
1.399     www      2759: 	if ($announcement=~/\w/) { 
                   2760: 	    return 
                   2761:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2762:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2763: 	} else {
                   2764: 	    return '';
                   2765: 	}
                   2766:     } else {
                   2767: 	return '';
                   2768:     }
1.351     www      2769: }
1.353     www      2770: 
                   2771: # ---------------------------------------------------------- Course ID routines
                   2772: # Deal with domain's nohist_courseid.db files
                   2773: #
                   2774: 
                   2775: sub courseidput {
1.921     raeburn  2776:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2777:     my $outcome;
                   2778:     if ($caller eq 'timeonly') {
                   2779:         my $cids = '';
                   2780:         foreach my $item (keys(%$storehash)) {
                   2781:             $cids.=&escape($item).'&';
                   2782:         }
                   2783:         $cids=~s/\&$//;
                   2784:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2785:                           $coursehome);       
                   2786:     } else {
                   2787:         my $items = '';
                   2788:         foreach my $item (keys(%$storehash)) {
                   2789:             $items.= &escape($item).'='.
                   2790:                      &freeze_escape($$storehash{$item}).'&';
                   2791:         }
                   2792:         $items=~s/\&$//;
                   2793:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2794:                           $coursehome);
1.918     raeburn  2795:     }
                   2796:     if ($outcome eq 'unknown_cmd') {
                   2797:         my $what;
                   2798:         foreach my $cid (keys(%$storehash)) {
                   2799:             $what .= &escape($cid).'=';
1.921     raeburn  2800:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2801:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2802:             }
                   2803:             $what =~ s/\:$/&/;
                   2804:         }
                   2805:         $what =~ s/\&$//;  
                   2806:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2807:     } else {
                   2808:         return $outcome;
                   2809:     }
1.353     www      2810: }
                   2811: 
                   2812: sub courseiddump {
1.921     raeburn  2813:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2814:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2815:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2816:     my $as_hash = 1;
                   2817:     my %returnhash;
                   2818:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2819:     my %libserv = &all_library();
                   2820:     foreach my $tryserver (keys(%libserv)) {
                   2821:         if ( (  $hostidflag == 1 
                   2822: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2823: 	     || (!defined($hostidflag)) ) {
                   2824: 
1.918     raeburn  2825: 	    if (($domfilter eq '') ||
                   2826: 		(&host_domain($tryserver) eq $domfilter)) {
                   2827:                 my $rep = 
                   2828:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2829:                          $sincefilter.':'.&escape($descfilter).':'.
                   2830:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2831:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2832:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2833:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2834:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2835:                 my @pairs=split(/\&/,$rep);
                   2836:                 foreach my $item (@pairs) {
                   2837:                     my ($key,$value)=split(/\=/,$item,2);
                   2838:                     $key = &unescape($key);
                   2839:                     next if ($key =~ /^error: 2 /);
                   2840:                     my $result = &thaw_unescape($value);
                   2841:                     if (ref($result) eq 'HASH') {
                   2842:                         $returnhash{$key}=$result;
                   2843:                     } else {
1.921     raeburn  2844:                         my @responses = split(/:/,$value);
                   2845:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2846:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2847:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2848:                         }
                   2849:                     } 
1.353     www      2850:                 }
                   2851:             }
                   2852:         }
                   2853:     }
                   2854:     return %returnhash;
                   2855: }
                   2856: 
1.658     raeburn  2857: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2858: 
                   2859: sub dcmailput {
1.685     raeburn  2860:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2861:     my $status = &Apache::lonnet::critical(
1.740     www      2862:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2863:        &escape($message),$server);
1.662     raeburn  2864:     return $status;
                   2865: }
                   2866: 
1.658     raeburn  2867: sub dcmaildump {
                   2868:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2869:     my %returnhash=();
1.846     albertel 2870: 
                   2871:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2872:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2873:                                                          &escape($enddate).':';
                   2874: 	my @esc_senders=map { &escape($_)} @$senders;
                   2875: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2876: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2877:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2878:             if (($key) && ($value)) {
                   2879:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2880:             }
                   2881:         }
                   2882:     }
                   2883:     return %returnhash;
                   2884: }
1.662     raeburn  2885: # ---------------------------------------------------------- Domain roles
                   2886: 
                   2887: sub get_domain_roles {
                   2888:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2889:     if (undef($startdate) || $startdate eq '') {
                   2890:         $startdate = '.';
                   2891:     }
                   2892:     if (undef($enddate) || $enddate eq '') {
                   2893:         $enddate = '.';
                   2894:     }
1.922     raeburn  2895:     my $rolelist;
                   2896:     if (ref($roles) eq 'ARRAY') {
                   2897:         $rolelist = join(':',@{$roles});
                   2898:     }
1.662     raeburn  2899:     my %personnel = ();
1.841     albertel 2900: 
                   2901:     my %servers = &get_servers($dom,'library');
                   2902:     foreach my $tryserver (keys(%servers)) {
                   2903: 	%{$personnel{$tryserver}}=();
                   2904: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2905: 					    &escape($startdate).':'.
                   2906: 					    &escape($enddate).':'.
                   2907: 					    &escape($rolelist), $tryserver))) {
                   2908: 	    my ($key,$value) = split(/\=/,$line,2);
                   2909: 	    if (($key) && ($value)) {
                   2910: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2911: 	    }
                   2912: 	}
1.662     raeburn  2913:     }
                   2914:     return %personnel;
                   2915: }
1.658     raeburn  2916: 
1.149     www      2917: # ----------------------------------------------------------- Check out an item
                   2918: 
1.504     albertel 2919: sub get_first_access {
                   2920:     my ($type,$argsymb)=@_;
1.790     albertel 2921:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2922:     if ($argsymb) { $symb=$argsymb; }
                   2923:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2924:     if ($type eq 'course') {
                   2925: 	$res='course';
                   2926:     } elsif ($type eq 'map') {
1.588     albertel 2927: 	$res=&symbread($map);
                   2928:     } else {
                   2929: 	$res=$symb;
                   2930:     }
                   2931:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2932:     return $times{"$courseid\0$res"};
1.504     albertel 2933: }
                   2934: 
                   2935: sub set_first_access {
                   2936:     my ($type)=@_;
1.790     albertel 2937:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2938:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2939:     if ($type eq 'course') {
                   2940: 	$res='course';
                   2941:     } elsif ($type eq 'map') {
1.588     albertel 2942: 	$res=&symbread($map);
                   2943:     } else {
                   2944: 	$res=$symb;
                   2945:     }
                   2946:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2947:     if (!$firstaccess) {
1.588     albertel 2948: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2949:     }
                   2950:     return 'already_set';
1.504     albertel 2951: }
                   2952: 
1.149     www      2953: sub checkout {
                   2954:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2955:     my $now=time;
                   2956:     my $lonhost=$perlvar{'lonHostID'};
                   2957:     my $infostr=&escape(
1.234     www      2958:                  'CHECKOUTTOKEN&'.
1.149     www      2959:                  $tuname.'&'.
                   2960:                  $tudom.'&'.
                   2961:                  $tcrsid.'&'.
                   2962:                  $symb.'&'.
                   2963: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2964:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2965:     if ($token=~/^error\:/) { 
1.672     albertel 2966:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2967:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2968:                  "</font>");
                   2969:         return ''; 
                   2970:     }
                   2971: 
1.149     www      2972:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2973:     $token=~tr/a-z/A-Z/;
                   2974: 
1.153     www      2975:     my %infohash=('resource.0.outtoken' => $token,
                   2976:                   'resource.0.checkouttime' => $now,
                   2977:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2978: 
                   2979:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2980:        return '';
1.151     www      2981:     } else {
1.672     albertel 2982:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2983:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2984:                  "</font>");
1.149     www      2985:     }    
                   2986: 
                   2987:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2988:                          &escape('Checkout '.$infostr.' - '.
                   2989:                                                  $token)) ne 'ok') {
                   2990: 	return '';
1.151     www      2991:     } else {
1.672     albertel 2992:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2993:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2994:                  "</font>");
1.149     www      2995:     }
1.151     www      2996:     return $token;
1.149     www      2997: }
                   2998: 
                   2999: # ------------------------------------------------------------ Check in an item
                   3000: 
                   3001: sub checkin {
                   3002:     my $token=shift;
1.150     www      3003:     my $now=time;
                   3004:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3005:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3006:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3007:     $dtoken=~s/\W/\_/g;
1.234     www      3008:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3009:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3010: 
1.154     www      3011:     unless (($tuname) && ($tudom)) {
                   3012:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3013:         return '';
                   3014:     }
                   3015:     
                   3016:     unless (&allowed('mgr',$tcrsid)) {
                   3017:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3018:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3019:         return '';
                   3020:     }
                   3021: 
1.153     www      3022:     my %infohash=('resource.0.intoken' => $token,
                   3023:                   'resource.0.checkintime' => $now,
                   3024:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3025: 
                   3026:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3027:        return '';
                   3028:     }    
                   3029: 
                   3030:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3031:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3032: 	return '';
                   3033:     }
                   3034: 
                   3035:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3036: }
                   3037: 
                   3038: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3039: 
                   3040: sub expirespread {
                   3041:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3042:     my $cid=$env{'request.course.id'}; 
1.110     www      3043:     if ($cid) {
                   3044:        my $now=time;
                   3045:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3046:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3047:                             $env{'course.'.$cid.'.num'}.
1.110     www      3048: 	        	    ':nohist_expirationdates:'.
                   3049:                             &escape($key).'='.$now,
1.620     albertel 3050:                             $env{'course.'.$cid.'.home'})
1.110     www      3051:     }
                   3052:     return 'ok';
1.14      www      3053: }
                   3054: 
1.109     www      3055: # ----------------------------------------------------- Devalidate Spreadsheets
                   3056: 
                   3057: sub devalidate {
1.325     www      3058:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3059:     my $cid=$env{'request.course.id'}; 
1.109     www      3060:     if ($cid) {
1.391     matthew  3061:         # delete the stored spreadsheets for
                   3062:         # - the student level sheet of this user in course's homespace
                   3063:         # - the assessment level sheet for this resource 
                   3064:         #   for this user in user's homespace
1.553     albertel 3065: 	# - current conditional state info
1.325     www      3066: 	my $key=$uname.':'.$udom.':';
1.109     www      3067:         my $status=
1.299     matthew  3068: 	    &del('nohist_calculatedsheets',
1.391     matthew  3069: 		 [$key.'studentcalc:'],
1.620     albertel 3070: 		 $env{'course.'.$cid.'.domain'},
                   3071: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3072: 		.' '.
                   3073: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3074: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3075:         unless ($status eq 'ok ok') {
                   3076:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3077:                     $uname.' at '.$udom.' for '.
1.109     www      3078: 		    $symb.': '.$status);
1.133     albertel 3079:         }
1.553     albertel 3080: 	&delenv('user.state.'.$cid);
1.109     www      3081:     }
                   3082: }
                   3083: 
1.265     albertel 3084: sub get_scalar {
                   3085:     my ($string,$end) = @_;
                   3086:     my $value;
                   3087:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3088: 	$value = $1;
                   3089:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3090: 	$value = $1;
                   3091:     }
                   3092:     return &unescape($value);
                   3093: }
                   3094: 
                   3095: sub array2str {
                   3096:   my (@array) = @_;
                   3097:   my $result=&arrayref2str(\@array);
                   3098:   $result=~s/^__ARRAY_REF__//;
                   3099:   $result=~s/__END_ARRAY_REF__$//;
                   3100:   return $result;
                   3101: }
                   3102: 
1.204     albertel 3103: sub arrayref2str {
                   3104:   my ($arrayref) = @_;
1.265     albertel 3105:   my $result='__ARRAY_REF__';
1.204     albertel 3106:   foreach my $elem (@$arrayref) {
1.265     albertel 3107:     if(ref($elem) eq 'ARRAY') {
                   3108:       $result.=&arrayref2str($elem).'&';
                   3109:     } elsif(ref($elem) eq 'HASH') {
                   3110:       $result.=&hashref2str($elem).'&';
                   3111:     } elsif(ref($elem)) {
                   3112:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3113:     } else {
                   3114:       $result.=&escape($elem).'&';
                   3115:     }
                   3116:   }
                   3117:   $result=~s/\&$//;
1.265     albertel 3118:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3119:   return $result;
                   3120: }
                   3121: 
1.168     albertel 3122: sub hash2str {
1.204     albertel 3123:   my (%hash) = @_;
                   3124:   my $result=&hashref2str(\%hash);
1.265     albertel 3125:   $result=~s/^__HASH_REF__//;
                   3126:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3127:   return $result;
                   3128: }
                   3129: 
                   3130: sub hashref2str {
                   3131:   my ($hashref)=@_;
1.265     albertel 3132:   my $result='__HASH_REF__';
1.800     albertel 3133:   foreach my $key (sort(keys(%$hashref))) {
                   3134:     if (ref($key) eq 'ARRAY') {
                   3135:       $result.=&arrayref2str($key).'=';
                   3136:     } elsif (ref($key) eq 'HASH') {
                   3137:       $result.=&hashref2str($key).'=';
                   3138:     } elsif (ref($key)) {
1.265     albertel 3139:       $result.='=';
1.800     albertel 3140:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3141:     } else {
1.800     albertel 3142: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3143:     }
                   3144: 
1.800     albertel 3145:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3146:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3147:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3148:       $result.=&hashref2str($hashref->{$key}).'&';
                   3149:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3150:        $result.='&';
1.800     albertel 3151:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3152:     } else {
1.800     albertel 3153:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3154:     }
                   3155:   }
1.168     albertel 3156:   $result=~s/\&$//;
1.265     albertel 3157:   $result .= '__END_HASH_REF__';
1.168     albertel 3158:   return $result;
                   3159: }
                   3160: 
                   3161: sub str2hash {
1.265     albertel 3162:     my ($string)=@_;
                   3163:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3164:     return %$hash;
                   3165: }
                   3166: 
                   3167: sub str2hashref {
1.168     albertel 3168:   my ($string) = @_;
1.265     albertel 3169: 
                   3170:   my %hash;
                   3171: 
                   3172:   if($string !~ /^__HASH_REF__/) {
                   3173:       if (! ($string eq '' || !defined($string))) {
                   3174: 	  $hash{'error'}='Not hash reference';
                   3175:       }
                   3176:       return (\%hash, $string);
                   3177:   }
                   3178: 
                   3179:   $string =~ s/^__HASH_REF__//;
                   3180: 
                   3181:   while($string !~ /^__END_HASH_REF__/) {
                   3182:       #key
                   3183:       my $key='';
                   3184:       if($string =~ /^__HASH_REF__/) {
                   3185:           ($key, $string)=&str2hashref($string);
                   3186:           if(defined($key->{'error'})) {
                   3187:               $hash{'error'}='Bad data';
                   3188:               return (\%hash, $string);
                   3189:           }
                   3190:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3191:           ($key, $string)=&str2arrayref($string);
                   3192:           if($key->[0] eq 'Array reference error') {
                   3193:               $hash{'error'}='Bad data';
                   3194:               return (\%hash, $string);
                   3195:           }
                   3196:       } else {
                   3197:           $string =~ s/^(.*?)=//;
1.267     albertel 3198: 	  $key=&unescape($1);
1.265     albertel 3199:       }
                   3200:       $string =~ s/^=//;
                   3201: 
                   3202:       #value
                   3203:       my $value='';
                   3204:       if($string =~ /^__HASH_REF__/) {
                   3205:           ($value, $string)=&str2hashref($string);
                   3206:           if(defined($value->{'error'})) {
                   3207:               $hash{'error'}='Bad data';
                   3208:               return (\%hash, $string);
                   3209:           }
                   3210:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3211:           ($value, $string)=&str2arrayref($string);
                   3212:           if($value->[0] eq 'Array reference error') {
                   3213:               $hash{'error'}='Bad data';
                   3214:               return (\%hash, $string);
                   3215:           }
                   3216:       } else {
                   3217: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3218:       }
                   3219:       $string =~ s/^&//;
                   3220: 
                   3221:       $hash{$key}=$value;
1.204     albertel 3222:   }
1.265     albertel 3223: 
                   3224:   $string =~ s/^__END_HASH_REF__//;
                   3225: 
                   3226:   return (\%hash, $string);
1.204     albertel 3227: }
                   3228: 
                   3229: sub str2array {
1.265     albertel 3230:     my ($string)=@_;
                   3231:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3232:     return @$array;
                   3233: }
                   3234: 
                   3235: sub str2arrayref {
1.204     albertel 3236:   my ($string) = @_;
1.265     albertel 3237:   my @array;
                   3238: 
                   3239:   if($string !~ /^__ARRAY_REF__/) {
                   3240:       if (! ($string eq '' || !defined($string))) {
                   3241: 	  $array[0]='Array reference error';
                   3242:       }
                   3243:       return (\@array, $string);
                   3244:   }
                   3245: 
                   3246:   $string =~ s/^__ARRAY_REF__//;
                   3247: 
                   3248:   while($string !~ /^__END_ARRAY_REF__/) {
                   3249:       my $value='';
                   3250:       if($string =~ /^__HASH_REF__/) {
                   3251:           ($value, $string)=&str2hashref($string);
                   3252:           if(defined($value->{'error'})) {
                   3253:               $array[0] ='Array reference error';
                   3254:               return (\@array, $string);
                   3255:           }
                   3256:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3257:           ($value, $string)=&str2arrayref($string);
                   3258:           if($value->[0] eq 'Array reference error') {
                   3259:               $array[0] ='Array reference error';
                   3260:               return (\@array, $string);
                   3261:           }
                   3262:       } else {
                   3263: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3264:       }
                   3265:       $string =~ s/^&//;
                   3266: 
                   3267:       push(@array, $value);
1.191     harris41 3268:   }
1.265     albertel 3269: 
                   3270:   $string =~ s/^__END_ARRAY_REF__//;
                   3271: 
                   3272:   return (\@array, $string);
1.168     albertel 3273: }
                   3274: 
1.167     albertel 3275: # -------------------------------------------------------------------Temp Store
                   3276: 
1.168     albertel 3277: sub tmpreset {
                   3278:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3279:   if (!$symb) {
                   3280:     $symb=&symbread();
1.620     albertel 3281:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3282:   }
                   3283:   $symb=escape($symb);
                   3284: 
1.620     albertel 3285:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3286:   $namespace=~s/\//\_/g;
                   3287:   $namespace=~s/\W//g;
                   3288: 
1.620     albertel 3289:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3290:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3291:   if ($domain eq 'public' && $stuname eq 'public') {
                   3292:       $stuname=$ENV{'REMOTE_ADDR'};
                   3293:   }
1.168     albertel 3294:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3295:   my %hash;
                   3296:   if (tie(%hash,'GDBM_File',
                   3297: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3298: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3299:     foreach my $key (keys %hash) {
1.180     albertel 3300:       if ($key=~ /:$symb/) {
1.168     albertel 3301: 	delete($hash{$key});
                   3302:       }
                   3303:     }
                   3304:   }
                   3305: }
                   3306: 
1.167     albertel 3307: sub tmpstore {
1.168     albertel 3308:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3309: 
                   3310:   if (!$symb) {
                   3311:     $symb=&symbread();
1.620     albertel 3312:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3313:   }
                   3314:   $symb=escape($symb);
                   3315: 
                   3316:   if (!$namespace) {
                   3317:     # I don't think we would ever want to store this for a course.
                   3318:     # it seems this will only be used if we don't have a course.
1.620     albertel 3319:     #$namespace=$env{'request.course.id'};
1.168     albertel 3320:     #if (!$namespace) {
1.620     albertel 3321:       $namespace=$env{'request.state'};
1.168     albertel 3322:     #}
                   3323:   }
                   3324:   $namespace=~s/\//\_/g;
                   3325:   $namespace=~s/\W//g;
1.620     albertel 3326:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3327:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3328:   if ($domain eq 'public' && $stuname eq 'public') {
                   3329:       $stuname=$ENV{'REMOTE_ADDR'};
                   3330:   }
1.168     albertel 3331:   my $now=time;
                   3332:   my %hash;
                   3333:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3334:   if (tie(%hash,'GDBM_File',
                   3335: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3336: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3337:     $hash{"version:$symb"}++;
                   3338:     my $version=$hash{"version:$symb"};
                   3339:     my $allkeys=''; 
                   3340:     foreach my $key (keys(%$storehash)) {
                   3341:       $allkeys.=$key.':';
1.591     albertel 3342:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3343:     }
                   3344:     $hash{"$version:$symb:timestamp"}=$now;
                   3345:     $allkeys.='timestamp';
                   3346:     $hash{"$version:keys:$symb"}=$allkeys;
                   3347:     if (untie(%hash)) {
                   3348:       return 'ok';
                   3349:     } else {
                   3350:       return "error:$!";
                   3351:     }
                   3352:   } else {
                   3353:     return "error:$!";
                   3354:   }
                   3355: }
1.167     albertel 3356: 
1.168     albertel 3357: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3358: 
1.168     albertel 3359: sub tmprestore {
                   3360:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3361: 
1.168     albertel 3362:   if (!$symb) {
                   3363:     $symb=&symbread();
1.620     albertel 3364:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3365:   }
                   3366:   $symb=escape($symb);
                   3367: 
1.620     albertel 3368:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3369: 
1.620     albertel 3370:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3371:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3372:   if ($domain eq 'public' && $stuname eq 'public') {
                   3373:       $stuname=$ENV{'REMOTE_ADDR'};
                   3374:   }
1.168     albertel 3375:   my %returnhash;
                   3376:   $namespace=~s/\//\_/g;
                   3377:   $namespace=~s/\W//g;
                   3378:   my %hash;
                   3379:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3380:   if (tie(%hash,'GDBM_File',
                   3381: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3382: 	  &GDBM_READER(),0640)) {
1.168     albertel 3383:     my $version=$hash{"version:$symb"};
                   3384:     $returnhash{'version'}=$version;
                   3385:     my $scope;
                   3386:     for ($scope=1;$scope<=$version;$scope++) {
                   3387:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3388:       my @keys=split(/:/,$vkeys);
                   3389:       my $key;
                   3390:       $returnhash{"$scope:keys"}=$vkeys;
                   3391:       foreach $key (@keys) {
1.591     albertel 3392: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3393: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3394:       }
                   3395:     }
1.168     albertel 3396:     if (!(untie(%hash))) {
                   3397:       return "error:$!";
                   3398:     }
                   3399:   } else {
                   3400:     return "error:$!";
                   3401:   }
                   3402:   return %returnhash;
1.167     albertel 3403: }
                   3404: 
1.9       www      3405: # ----------------------------------------------------------------------- Store
                   3406: 
                   3407: sub store {
1.124     www      3408:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3409:     my $home='';
                   3410: 
1.168     albertel 3411:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3412: 
1.213     www      3413:     $symb=&symbclean($symb);
1.122     albertel 3414:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3415: 
1.620     albertel 3416:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3417:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3418: 
                   3419:     &devalidate($symb,$stuname,$domain);
1.109     www      3420: 
                   3421:     $symb=escape($symb);
1.187     www      3422:     if (!$namespace) { 
1.620     albertel 3423:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3424:           return ''; 
                   3425:        } 
                   3426:     }
1.620     albertel 3427:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3428: 
                   3429:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3430:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3431: 
1.12      www      3432:     my $namevalue='';
1.800     albertel 3433:     foreach my $key (keys(%$storehash)) {
                   3434:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3435:     }
1.12      www      3436:     $namevalue=~s/\&$//;
1.187     www      3437:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3438:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3439: }
                   3440: 
1.47      www      3441: # -------------------------------------------------------------- Critical Store
                   3442: 
                   3443: sub cstore {
1.124     www      3444:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3445:     my $home='';
                   3446: 
1.168     albertel 3447:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3448: 
1.213     www      3449:     $symb=&symbclean($symb);
1.122     albertel 3450:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3451: 
1.620     albertel 3452:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3453:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3454: 
                   3455:     &devalidate($symb,$stuname,$domain);
1.109     www      3456: 
                   3457:     $symb=escape($symb);
1.187     www      3458:     if (!$namespace) { 
1.620     albertel 3459:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3460:           return ''; 
                   3461:        } 
                   3462:     }
1.620     albertel 3463:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3464: 
                   3465:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3466:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3467: 
1.47      www      3468:     my $namevalue='';
1.800     albertel 3469:     foreach my $key (keys(%$storehash)) {
                   3470:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3471:     }
1.47      www      3472:     $namevalue=~s/\&$//;
1.187     www      3473:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3474:     return critical
                   3475:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3476: }
                   3477: 
1.9       www      3478: # --------------------------------------------------------------------- Restore
                   3479: 
                   3480: sub restore {
1.124     www      3481:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3482:     my $home='';
                   3483: 
1.168     albertel 3484:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3485: 
1.122     albertel 3486:     if (!$symb) {
                   3487:       unless ($symb=escape(&symbread())) { return ''; }
                   3488:     } else {
1.213     www      3489:       $symb=&escape(&symbclean($symb));
1.122     albertel 3490:     }
1.188     www      3491:     if (!$namespace) { 
1.620     albertel 3492:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3493:           return ''; 
                   3494:        } 
                   3495:     }
1.620     albertel 3496:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3497:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3498:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3499:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3500: 
1.12      www      3501:     my %returnhash=();
1.800     albertel 3502:     foreach my $line (split(/\&/,$answer)) {
                   3503: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3504:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3505:     }
1.75      www      3506:     my $version;
                   3507:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3508:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3509:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3510:        }
1.75      www      3511:     }
1.13      www      3512:     return %returnhash;
1.34      www      3513: }
                   3514: 
                   3515: # ---------------------------------------------------------- Course Description
                   3516: 
                   3517: sub coursedescription {
1.731     albertel 3518:     my ($courseid,$args)=@_;
1.34      www      3519:     $courseid=~s/^\///;
1.49      www      3520:     $courseid=~s/\_/\//g;
1.34      www      3521:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3522:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3523:     my $normalid=$cdomain.'_'.$cnum;
                   3524:     # need to always cache even if we get errors otherwise we keep 
                   3525:     # trying and trying and trying to get the course description.
                   3526:     my %envhash=();
                   3527:     my %returnhash=();
1.731     albertel 3528:     
                   3529:     my $expiretime=600;
                   3530:     if ($env{'request.course.id'} eq $normalid) {
                   3531: 	$expiretime=120;
                   3532:     }
                   3533: 
                   3534:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3535:     if (!$args->{'freshen_cache'}
                   3536: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3537: 	foreach my $key (keys(%env)) {
                   3538: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3539: 	    my ($setting) = $1;
                   3540: 	    $returnhash{$setting} = $env{$key};
                   3541: 	}
                   3542: 	return %returnhash;
                   3543:     }
                   3544: 
                   3545:     # get the data agin
                   3546:     if (!$args->{'one_time'}) {
                   3547: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3548:     }
1.811     albertel 3549: 
1.34      www      3550:     if ($chome ne 'no_host') {
1.302     albertel 3551:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3552:        if (!exists($returnhash{'con_lost'})) {
                   3553:            $returnhash{'home'}= $chome;
                   3554: 	   $returnhash{'domain'} = $cdomain;
                   3555: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3556:            if (!defined($returnhash{'type'})) {
                   3557:                $returnhash{'type'} = 'Course';
                   3558:            }
1.130     albertel 3559:            while (my ($name,$value) = each %returnhash) {
1.53      www      3560:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3561:            }
1.270     www      3562:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3563:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3564: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3565:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3566:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3567:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3568:        }
                   3569:     }
1.731     albertel 3570:     if (!$args->{'one_time'}) {
1.949     raeburn  3571: 	&appenv(\%envhash);
1.731     albertel 3572:     }
1.302     albertel 3573:     return %returnhash;
1.461     www      3574: }
                   3575: 
                   3576: # -------------------------------------------------See if a user is privileged
                   3577: 
                   3578: sub privileged {
                   3579:     my ($username,$domain)=@_;
                   3580:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3581: 			&homeserver($username,$domain));
                   3582:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3583:     my $now=time;
                   3584:     if ($rolesdump ne '') {
1.800     albertel 3585:         foreach my $entry (split(/&/,$rolesdump)) {
                   3586: 	    if ($entry!~/^rolesdef_/) {
                   3587: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3588: 		$area=~s/\_\w\w$//;
                   3589: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3590: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3591: 		    my $active=1;
                   3592: 		    if ($tend) {
                   3593: 			if ($tend<$now) { $active=0; }
                   3594: 		    }
                   3595: 		    if ($tstart) {
                   3596: 			if ($tstart>$now) { $active=0; }
                   3597: 		    }
                   3598: 		    if ($active) { return 1; }
                   3599: 		}
                   3600: 	    }
                   3601: 	}
                   3602:     }
                   3603:     return 0;
1.9       www      3604: }
1.1       albertel 3605: 
1.103     harris41 3606: # -------------------------------------------------------- Get user privileges
1.11      www      3607: 
                   3608: sub rolesinit {
                   3609:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3610:     my %userroles;
1.11      www      3611:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3612:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3613:     my %allroles=();
1.678     raeburn  3614:     my %allgroups=();   
1.11      www      3615:     my $now=time;
1.966     raeburn  3616:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3617:     my $group_privs;
1.11      www      3618: 
                   3619:     if ($rolesdump ne '') {
1.800     albertel 3620:         foreach my $entry (split(/&/,$rolesdump)) {
                   3621: 	  if ($entry!~/^rolesdef_/) {
                   3622:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3623: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3624:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3625: 	    if ($role=~/^cr/) { 
1.807     albertel 3626: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3627: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3628: 		    ($tend,$tstart)=split('_',$trest);
                   3629: 		} else {
                   3630: 		    $trole=$role;
                   3631: 		}
1.678     raeburn  3632:             } elsif ($role =~ m|^gr/|) {
                   3633:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3634:                 ($trole,$group_privs) = split(/\//,$trole);
                   3635:                 $group_privs = &unescape($group_privs);
1.587     albertel 3636: 	    } else {
                   3637: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3638: 	    }
1.743     albertel 3639: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3640: 					 $username);
                   3641: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3642:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3643:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3644:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3645: 		my $spec=$trole.'.'.$area;
                   3646: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3647: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3648:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3649:                 } elsif ($trole eq 'gr') {
                   3650:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3651: 		} else {
1.567     raeburn  3652:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3653: 		}
1.12      www      3654:             }
1.662     raeburn  3655:           }
1.191     harris41 3656:         }
1.743     albertel 3657:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3658:         $userroles{'user.adv'}    = $adv;
                   3659: 	$userroles{'user.author'} = $author;
1.620     albertel 3660:         $env{'user.adv'}=$adv;
1.11      www      3661:     }
1.743     albertel 3662:     return \%userroles;  
1.11      www      3663: }
                   3664: 
1.567     raeburn  3665: sub set_arearole {
                   3666:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3667: # log the associated role with the area
                   3668:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3669:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3670: }
                   3671: 
                   3672: sub custom_roleprivs {
                   3673:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3674:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3675:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3676:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3677:         my ($rdummy,$roledef)=
                   3678:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3679:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3680:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3681:             if (defined($syspriv)) {
                   3682:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3683:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3684:             }
                   3685:             if ($tdomain ne '') {
                   3686:                 if (defined($dompriv)) {
                   3687:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3688:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3689:                 }
                   3690:                 if (($trest ne '') && (defined($coursepriv))) {
                   3691:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3692:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3693:                 }
                   3694:             }
                   3695:         }
                   3696:     }
                   3697: }
                   3698: 
1.678     raeburn  3699: sub group_roleprivs {
                   3700:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3701:     my $access = 1;
                   3702:     my $now = time;
                   3703:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3704:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3705:     if ($access) {
1.811     albertel 3706:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3707:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3708:     }
                   3709: }
1.567     raeburn  3710: 
                   3711: sub standard_roleprivs {
                   3712:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3713:     if (defined($pr{$trole.':s'})) {
                   3714:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3715:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3716:     }
                   3717:     if ($tdomain ne '') {
                   3718:         if (defined($pr{$trole.':d'})) {
                   3719:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3720:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3721:         }
                   3722:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3723:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3724:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3725:         }
                   3726:     }
                   3727: }
                   3728: 
                   3729: sub set_userprivs {
1.678     raeburn  3730:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3731:     my $author=0;
                   3732:     my $adv=0;
1.678     raeburn  3733:     my %grouproles = ();
                   3734:     if (keys(%{$allgroups}) > 0) {
                   3735:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3736:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3737:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3738:                 $trole = $1;
                   3739:                 $area = $2;
1.681     raeburn  3740:                 $sec = $3;
                   3741:                 $extendedarea = $area.$sec;
                   3742:                 if (exists($$allgroups{$area})) {
                   3743:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3744:                         my $spec = $trole.'.'.$extendedarea;
                   3745:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3746:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3747:                     }
                   3748:                 }
                   3749:             }
                   3750:         }
                   3751:     }
1.800     albertel 3752:     foreach my $group (keys(%grouproles)) {
                   3753:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3754:     }
1.800     albertel 3755:     foreach my $role (keys(%{$allroles})) {
                   3756:         my %thesepriv;
1.941     raeburn  3757:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3758:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3759:             if ($item ne '') {
                   3760:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3761:                 if ($restrictions eq '') {
                   3762:                     $thesepriv{$privilege}='F';
                   3763:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3764:                     $thesepriv{$privilege}.=$restrictions;
                   3765:                 }
                   3766:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3767:             }
                   3768:         }
                   3769:         my $thesestr='';
1.800     albertel 3770:         foreach my $priv (keys(%thesepriv)) {
                   3771: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3772: 	}
                   3773:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3774:     }
                   3775:     return ($author,$adv);
                   3776: }
                   3777: 
1.12      www      3778: # --------------------------------------------------------------- get interface
                   3779: 
                   3780: sub get {
1.131     albertel 3781:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3782:    my $items='';
1.800     albertel 3783:    foreach my $item (@$storearr) {
                   3784:        $items.=&escape($item).'&';
1.191     harris41 3785:    }
1.12      www      3786:    $items=~s/\&$//;
1.620     albertel 3787:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3788:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3789:    my $uhome=&homeserver($uname,$udomain);
                   3790: 
1.133     albertel 3791:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3792:    my @pairs=split(/\&/,$rep);
1.273     albertel 3793:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3794:      return @pairs;
                   3795:    }
1.15      www      3796:    my %returnhash=();
1.42      www      3797:    my $i=0;
1.800     albertel 3798:    foreach my $item (@$storearr) {
                   3799:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3800:       $i++;
1.191     harris41 3801:    }
1.15      www      3802:    return %returnhash;
1.27      www      3803: }
                   3804: 
                   3805: # --------------------------------------------------------------- del interface
                   3806: 
                   3807: sub del {
1.133     albertel 3808:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3809:    my $items='';
1.800     albertel 3810:    foreach my $item (@$storearr) {
                   3811:        $items.=&escape($item).'&';
1.191     harris41 3812:    }
1.27      www      3813:    $items=~s/\&$//;
1.620     albertel 3814:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3815:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3816:    my $uhome=&homeserver($uname,$udomain);
                   3817: 
                   3818:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3819: }
                   3820: 
                   3821: # -------------------------------------------------------------- dump interface
                   3822: 
                   3823: sub dump {
1.755     albertel 3824:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3825:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3826:     if (!$uname) { $uname=$env{'user.name'}; }
                   3827:     my $uhome=&homeserver($uname,$udomain);
                   3828:     if ($regexp) {
                   3829: 	$regexp=&escape($regexp);
                   3830:     } else {
                   3831: 	$regexp='.';
                   3832:     }
                   3833:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3834:     my @pairs=split(/\&/,$rep);
                   3835:     my %returnhash=();
                   3836:     foreach my $item (@pairs) {
                   3837: 	my ($key,$value)=split(/=/,$item,2);
                   3838: 	$key = &unescape($key);
                   3839: 	next if ($key =~ /^error: 2 /);
                   3840: 	$returnhash{$key}=&thaw_unescape($value);
                   3841:     }
                   3842:     return %returnhash;
1.407     www      3843: }
                   3844: 
1.717     albertel 3845: # --------------------------------------------------------- dumpstore interface
                   3846: 
                   3847: sub dumpstore {
                   3848:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3850:    if (!$uname) { $uname=$env{'user.name'}; }
                   3851:    my $uhome=&homeserver($uname,$udomain);
                   3852:    if ($regexp) {
                   3853:        $regexp=&escape($regexp);
                   3854:    } else {
                   3855:        $regexp='.';
                   3856:    }
                   3857:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3858:    my @pairs=split(/\&/,$rep);
                   3859:    my %returnhash=();
                   3860:    foreach my $item (@pairs) {
                   3861:        my ($key,$value)=split(/=/,$item,2);
                   3862:        next if ($key =~ /^error: 2 /);
                   3863:        $returnhash{$key}=&thaw_unescape($value);
                   3864:    }
                   3865:    return %returnhash;
1.717     albertel 3866: }
                   3867: 
1.407     www      3868: # -------------------------------------------------------------- keys interface
                   3869: 
                   3870: sub getkeys {
                   3871:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3873:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3874:    my $uhome=&homeserver($uname,$udomain);
                   3875:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3876:    my @keyarray=();
1.800     albertel 3877:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3878:       next if ($key =~ /^error: 2 /);
1.800     albertel 3879:       push(@keyarray,&unescape($key));
1.407     www      3880:    }
                   3881:    return @keyarray;
1.318     matthew  3882: }
                   3883: 
1.319     matthew  3884: # --------------------------------------------------------------- currentdump
                   3885: sub currentdump {
1.328     matthew  3886:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3887:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3888:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3889:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3890:    my $uhome = &homeserver($sname,$sdom);
                   3891:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3892:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3893:    #
1.318     matthew  3894:    my %returnhash=();
1.319     matthew  3895:    #
                   3896:    if ($rep eq "unknown_cmd") { 
                   3897:        # an old lond will not know currentdump
                   3898:        # Do a dump and make it look like a currentdump
1.822     albertel 3899:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3900:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3901:        my %hash = @tmp;
                   3902:        @tmp=();
1.424     matthew  3903:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3904:    } else {
                   3905:        my @pairs=split(/\&/,$rep);
1.800     albertel 3906:        foreach my $pair (@pairs) {
                   3907:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3908:            my ($symb,$param) = split(/:/,$key);
                   3909:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3910:                                                         &thaw_unescape($value);
1.319     matthew  3911:        }
1.191     harris41 3912:    }
1.12      www      3913:    return %returnhash;
1.424     matthew  3914: }
                   3915: 
                   3916: sub convert_dump_to_currentdump{
                   3917:     my %hash = %{shift()};
                   3918:     my %returnhash;
                   3919:     # Code ripped from lond, essentially.  The only difference
                   3920:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3921:     # we might run in to problems with parameter names =~ /^v\./
                   3922:     while (my ($key,$value) = each(%hash)) {
                   3923:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3924: 	$symb  = &unescape($symb);
                   3925: 	$param = &unescape($param);
1.424     matthew  3926:         next if ($v eq 'version' || $symb eq 'keys');
                   3927:         next if (exists($returnhash{$symb}) &&
                   3928:                  exists($returnhash{$symb}->{$param}) &&
                   3929:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3930:         $returnhash{$symb}->{$param}=$value;
                   3931:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3932:     }
                   3933:     #
                   3934:     # Remove all of the keys in the hashes which keep track of
                   3935:     # the version of the parameter.
                   3936:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3937:         # use a foreach because we are going to delete from the hash.
                   3938:         foreach my $key (keys(%$param_hash)) {
                   3939:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3940:         }
                   3941:     }
                   3942:     return \%returnhash;
1.12      www      3943: }
                   3944: 
1.627     albertel 3945: # ------------------------------------------------------ critical inc interface
                   3946: 
                   3947: sub cinc {
                   3948:     return &inc(@_,'critical');
                   3949: }
                   3950: 
1.449     matthew  3951: # --------------------------------------------------------------- inc interface
                   3952: 
                   3953: sub inc {
1.627     albertel 3954:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3955:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3956:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3957:     my $uhome=&homeserver($uname,$udomain);
                   3958:     my $items='';
                   3959:     if (! ref($store)) {
                   3960:         # got a single value, so use that instead
                   3961:         $items = &escape($store).'=&';
                   3962:     } elsif (ref($store) eq 'SCALAR') {
                   3963:         $items = &escape($$store).'=&';        
                   3964:     } elsif (ref($store) eq 'ARRAY') {
                   3965:         $items = join('=&',map {&escape($_);} @{$store});
                   3966:     } elsif (ref($store) eq 'HASH') {
                   3967:         while (my($key,$value) = each(%{$store})) {
                   3968:             $items.= &escape($key).'='.&escape($value).'&';
                   3969:         }
                   3970:     }
                   3971:     $items=~s/\&$//;
1.627     albertel 3972:     if ($critical) {
                   3973: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3974:     } else {
                   3975: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3976:     }
1.449     matthew  3977: }
                   3978: 
1.12      www      3979: # --------------------------------------------------------------- put interface
                   3980: 
                   3981: sub put {
1.134     albertel 3982:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3983:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3984:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3985:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3986:    my $items='';
1.800     albertel 3987:    foreach my $item (keys(%$storehash)) {
                   3988:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3989:    }
1.12      www      3990:    $items=~s/\&$//;
1.134     albertel 3991:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3992: }
                   3993: 
1.631     albertel 3994: # ------------------------------------------------------------ newput interface
                   3995: 
                   3996: sub newput {
                   3997:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3999:    if (!$uname) { $uname=$env{'user.name'}; }
                   4000:    my $uhome=&homeserver($uname,$udomain);
                   4001:    my $items='';
                   4002:    foreach my $key (keys(%$storehash)) {
                   4003:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4004:    }
                   4005:    $items=~s/\&$//;
                   4006:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4007: }
                   4008: 
                   4009: # ---------------------------------------------------------  putstore interface
                   4010: 
1.524     raeburn  4011: sub putstore {
1.715     albertel 4012:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4014:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4015:    my $uhome=&homeserver($uname,$udomain);
                   4016:    my $items='';
1.715     albertel 4017:    foreach my $key (keys(%$storehash)) {
                   4018:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4019:    }
1.715     albertel 4020:    $items=~s/\&$//;
1.716     albertel 4021:    my $esc_symb=&escape($symb);
                   4022:    my $esc_v=&escape($version);
1.715     albertel 4023:    my $reply =
1.716     albertel 4024:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4025: 	      $uhome);
                   4026:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4027:        # gfall back to way things use to be done
1.715     albertel 4028:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4029: 			    $uname);
1.524     raeburn  4030:    }
1.715     albertel 4031:    return $reply;
                   4032: }
                   4033: 
                   4034: sub old_putstore {
1.716     albertel 4035:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4036:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4037:     if (!$uname) { $uname=$env{'user.name'}; }
                   4038:     my $uhome=&homeserver($uname,$udomain);
                   4039:     my %newstorehash;
1.800     albertel 4040:     foreach my $item (keys(%$storehash)) {
                   4041: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4042: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4043:     }
                   4044:     my $items='';
                   4045:     my %allitems = ();
1.800     albertel 4046:     foreach my $item (keys(%newstorehash)) {
                   4047: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4048: 	    my $key = $1.':keys:'.$2;
                   4049: 	    $allitems{$key} .= $3.':';
                   4050: 	}
1.800     albertel 4051: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4052:     }
1.800     albertel 4053:     foreach my $item (keys(%allitems)) {
                   4054: 	$allitems{$item} =~ s/\:$//;
                   4055: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4056:     }
                   4057:     $items=~s/\&$//;
                   4058:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4059: }
                   4060: 
1.47      www      4061: # ------------------------------------------------------ critical put interface
                   4062: 
                   4063: sub cput {
1.134     albertel 4064:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4066:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4067:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4068:    my $items='';
1.800     albertel 4069:    foreach my $item (keys(%$storehash)) {
                   4070:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4071:    }
1.47      www      4072:    $items=~s/\&$//;
1.134     albertel 4073:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4074: }
                   4075: 
                   4076: # -------------------------------------------------------------- eget interface
                   4077: 
                   4078: sub eget {
1.133     albertel 4079:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4080:    my $items='';
1.800     albertel 4081:    foreach my $item (@$storearr) {
                   4082:        $items.=&escape($item).'&';
1.191     harris41 4083:    }
1.12      www      4084:    $items=~s/\&$//;
1.620     albertel 4085:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4086:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4087:    my $uhome=&homeserver($uname,$udomain);
                   4088:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4089:    my @pairs=split(/\&/,$rep);
                   4090:    my %returnhash=();
1.42      www      4091:    my $i=0;
1.800     albertel 4092:    foreach my $item (@$storearr) {
                   4093:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4094:       $i++;
1.191     harris41 4095:    }
1.12      www      4096:    return %returnhash;
                   4097: }
                   4098: 
1.667     albertel 4099: # ------------------------------------------------------------ tmpput interface
                   4100: sub tmpput {
1.802     raeburn  4101:     my ($storehash,$server,$context)=@_;
1.667     albertel 4102:     my $items='';
1.800     albertel 4103:     foreach my $item (keys(%$storehash)) {
                   4104: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4105:     }
                   4106:     $items=~s/\&$//;
1.802     raeburn  4107:     if (defined($context)) {
                   4108:         $items .= ':'.&escape($context);
                   4109:     }
1.667     albertel 4110:     return &reply("tmpput:$items",$server);
                   4111: }
                   4112: 
                   4113: # ------------------------------------------------------------ tmpget interface
                   4114: sub tmpget {
1.688     albertel 4115:     my ($token,$server)=@_;
                   4116:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4117:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4118:     my %returnhash;
                   4119:     foreach my $item (split(/\&/,$rep)) {
                   4120: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4121:         next if ($key =~ /^error: 2 /);
1.667     albertel 4122: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4123:     }
                   4124:     return %returnhash;
                   4125: }
                   4126: 
1.688     albertel 4127: # ------------------------------------------------------------ tmpget interface
                   4128: sub tmpdel {
                   4129:     my ($token,$server)=@_;
                   4130:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4131:     return &reply("tmpdel:$token",$server);
                   4132: }
                   4133: 
1.765     albertel 4134: # -------------------------------------------------- portfolio access checking
                   4135: 
                   4136: sub portfolio_access {
1.766     albertel 4137:     my ($requrl) = @_;
1.765     albertel 4138:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4139:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4140:     if ($result) {
                   4141:         my %setters;
                   4142:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4143:             my ($startblock,$endblock) =
                   4144:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4145:             if ($startblock && $endblock) {
                   4146:                 return 'B';
                   4147:             }
                   4148:         } else {
                   4149:             my ($startblock,$endblock) =
                   4150:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4151:             if ($startblock && $endblock) {
                   4152:                 return 'B';
                   4153:             }
                   4154:         }
                   4155:     }
1.765     albertel 4156:     if ($result eq 'ok') {
1.766     albertel 4157:        return 'F';
1.765     albertel 4158:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4159:        return 'A';
1.765     albertel 4160:     }
1.766     albertel 4161:     return '';
1.765     albertel 4162: }
                   4163: 
                   4164: sub get_portfolio_access {
1.767     albertel 4165:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4166: 
                   4167:     if (!ref($access_hash)) {
                   4168: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4169: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4170: 						   $file_name);
                   4171: 	$access_hash = $access_controls{$file_name};
                   4172:     }
                   4173: 
1.765     albertel 4174:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4175:     my $now = time;
                   4176:     if (ref($access_hash) eq 'HASH') {
                   4177:         foreach my $key (keys(%{$access_hash})) {
                   4178:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4179:             if ($start > $now) {
                   4180:                 next;
                   4181:             }
                   4182:             if ($end && $end<$now) {
                   4183:                 next;
                   4184:             }
                   4185:             if ($scope eq 'public') {
                   4186:                 $public = $key;
                   4187:                 last;
                   4188:             } elsif ($scope eq 'guest') {
                   4189:                 $guest = $key;
                   4190:             } elsif ($scope eq 'domains') {
                   4191:                 push(@domains,$key);
                   4192:             } elsif ($scope eq 'users') {
                   4193:                 push(@users,$key);
                   4194:             } elsif ($scope eq 'course') {
                   4195:                 push(@courses,$key);
                   4196:             } elsif ($scope eq 'group') {
                   4197:                 push(@groups,$key);
                   4198:             }
                   4199:         }
                   4200:         if ($public) {
                   4201:             return 'ok';
                   4202:         }
                   4203:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4204:             if ($guest) {
                   4205:                 return $guest;
                   4206:             }
                   4207:         } else {
                   4208:             if (@domains > 0) {
                   4209:                 foreach my $domkey (@domains) {
                   4210:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4211:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4212:                             return 'ok';
                   4213:                         }
                   4214:                     }
                   4215:                 }
                   4216:             }
                   4217:             if (@users > 0) {
                   4218:                 foreach my $userkey (@users) {
1.865     raeburn  4219:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4220:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4221:                             if (ref($item) eq 'HASH') {
                   4222:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4223:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4224:                                     return 'ok';
                   4225:                                 }
                   4226:                             }
                   4227:                         }
                   4228:                     } 
1.765     albertel 4229:                 }
                   4230:             }
                   4231:             my %roleshash;
                   4232:             my @courses_and_groups = @courses;
                   4233:             push(@courses_and_groups,@groups); 
                   4234:             if (@courses_and_groups > 0) {
                   4235:                 my (%allgroups,%allroles); 
                   4236:                 my ($start,$end,$role,$sec,$group);
                   4237:                 foreach my $envkey (%env) {
1.811     albertel 4238:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4239:                         my $cid = $2.'_'.$3; 
                   4240:                         if ($1 eq 'gr') {
                   4241:                             $group = $4;
                   4242:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4243:                         } else {
                   4244:                             if ($4 eq '') {
                   4245:                                 $sec = 'none';
                   4246:                             } else {
                   4247:                                 $sec = $4;
                   4248:                             }
                   4249:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4250:                         }
1.811     albertel 4251:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4252:                         my $cid = $2.'_'.$3;
                   4253:                         if ($4 eq '') {
                   4254:                             $sec = 'none';
                   4255:                         } else {
                   4256:                             $sec = $4;
                   4257:                         }
                   4258:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4259:                     }
                   4260:                 }
                   4261:                 if (keys(%allroles) == 0) {
                   4262:                     return;
                   4263:                 }
                   4264:                 foreach my $key (@courses_and_groups) {
                   4265:                     my %content = %{$$access_hash{$key}};
                   4266:                     my $cnum = $content{'number'};
                   4267:                     my $cdom = $content{'domain'};
                   4268:                     my $cid = $cdom.'_'.$cnum;
                   4269:                     if (!exists($allroles{$cid})) {
                   4270:                         next;
                   4271:                     }    
                   4272:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4273:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4274:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4275:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4276:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4277:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4278:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4279:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4280:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4281:                                         if (grep/^all$/,@sections) {
                   4282:                                             return 'ok';
                   4283:                                         } else {
                   4284:                                             if (grep/^$sec$/,@sections) {
                   4285:                                                 return 'ok';
                   4286:                                             }
                   4287:                                         }
                   4288:                                     }
                   4289:                                 }
                   4290:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4291:                                     if (grep/^none$/,@groups) {
                   4292:                                         return 'ok';
                   4293:                                     }
                   4294:                                 } else {
                   4295:                                     if (grep/^all$/,@groups) {
                   4296:                                         return 'ok';
                   4297:                                     } 
                   4298:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4299:                                         if (grep/^$group$/,@groups) {
                   4300:                                             return 'ok';
                   4301:                                         }
                   4302:                                     }
                   4303:                                 } 
                   4304:                             }
                   4305:                         }
                   4306:                     }
                   4307:                 }
                   4308:             }
                   4309:             if ($guest) {
                   4310:                 return $guest;
                   4311:             }
                   4312:         }
                   4313:     }
                   4314:     return;
                   4315: }
                   4316: 
                   4317: sub course_group_datechecker {
                   4318:     my ($dates,$now,$status) = @_;
                   4319:     my ($start,$end) = split(/\./,$dates);
                   4320:     if (!$start && !$end) {
                   4321:         return 'ok';
                   4322:     }
                   4323:     if (grep/^active$/,@{$status}) {
                   4324:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4325:             return 'ok';
                   4326:         }
                   4327:     }
                   4328:     if (grep/^previous$/,@{$status}) {
                   4329:         if ($end > $now ) {
                   4330:             return 'ok';
                   4331:         }
                   4332:     }
                   4333:     if (grep/^future$/,@{$status}) {
                   4334:         if ($start > $now) {
                   4335:             return 'ok';
                   4336:         }
                   4337:     }
                   4338:     return; 
                   4339: }
                   4340: 
                   4341: sub parse_portfolio_url {
                   4342:     my ($url) = @_;
                   4343: 
                   4344:     my ($type,$udom,$unum,$group,$file_name);
                   4345:     
1.823     albertel 4346:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4347: 	$type = 1;
                   4348:         $udom = $1;
                   4349:         $unum = $2;
                   4350:         $file_name = $3;
1.823     albertel 4351:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4352: 	$type = 2;
                   4353:         $udom = $1;
                   4354:         $unum = $2;
                   4355:         $group = $3;
                   4356:         $file_name = $3.'/'.$4;
                   4357:     }
                   4358:     if (wantarray) {
                   4359: 	return ($type,$udom,$unum,$file_name,$group);
                   4360:     }
                   4361:     return $type;
                   4362: }
                   4363: 
                   4364: sub is_portfolio_url {
                   4365:     my ($url) = @_;
                   4366:     return scalar(&parse_portfolio_url($url));
                   4367: }
                   4368: 
1.798     raeburn  4369: sub is_portfolio_file {
                   4370:     my ($file) = @_;
1.820     raeburn  4371:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4372:         return 1;
                   4373:     }
                   4374:     return;
                   4375: }
                   4376: 
1.976     raeburn  4377: sub usertools_access {
1.976.2.1  raeburn  4378:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4379:     my $access;
                   4380:     my %tools = (
                   4381:                   aboutme   => 1,
                   4382:                   blog      => 1,
                   4383:                   portfolio => 1,
                   4384:                 );
                   4385:     return if (!defined($tools{$tool}));
                   4386: 
                   4387:     if ((!defined($udom)) || (!defined($uname))) {
                   4388:         $udom = $env{'user.domain'};
                   4389:         $uname = $env{'user.name'};
                   4390:     }
                   4391: 
1.976.2.1  raeburn  4392:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4393:         if ($action ne 'reload') {
                   4394:             return $env{'environment.availabletools.'.$tool};
                   4395:         }
1.976     raeburn  4396:     }
                   4397: 
                   4398:     my ($toolstatus,$inststatus);
                   4399: 
                   4400:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4401:         $toolstatus = $env{'environment.tools.'.$tool};
                   4402:         $inststatus = $env{'environment.inststatus'};
                   4403:     } else {
                   4404:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4405:         $toolstatus = $userenv{'tools.'.$tool};
                   4406:         $inststatus = $userenv{'inststatus'};
                   4407:     }
                   4408: 
                   4409:     if ($toolstatus ne '') {
                   4410:         if ($toolstatus) {
                   4411:             $access = 1;
                   4412:         } else {
                   4413:             $access = 0;
                   4414:         }
                   4415:         return $access;
                   4416:     }
                   4417: 
                   4418:     my $is_adv = &is_advanced_user($udom,$uname);
                   4419:     my %domdef = &get_domain_defaults($udom);
                   4420:     if (ref($domdef{$tool}) eq 'HASH') {
                   4421:         if ($is_adv) {
                   4422:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4423:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4424:                     $access = 1;
                   4425:                 } else {
                   4426:                     $access = 0;
                   4427:                 }
                   4428:                 return $access;
                   4429:             }
                   4430:         }
                   4431:         if ($inststatus ne '') {
                   4432:             my ($hasaccess,$hasnoaccess);
                   4433:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4434:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4435:                     if ($domdef{$tool}{$affiliation}) {
                   4436:                         $hasaccess = 1;
                   4437:                     } else {
                   4438:                         $hasnoaccess = 1;
                   4439:                     }
                   4440:                 }
                   4441:             }
                   4442:             if ($hasaccess || $hasnoaccess) {
                   4443:                 if ($hasaccess) {
                   4444:                     $access = 1;
                   4445:                 } elsif ($hasnoaccess) {
                   4446:                     $access = 0; 
                   4447:                 }
                   4448:                 return $access;
                   4449:             }
                   4450:         } else {
                   4451:             if ($domdef{$tool}{'default'} ne '') {
                   4452:                 if ($domdef{$tool}{'default'}) {
                   4453:                     $access = 1;
                   4454:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4455:                     $access = 0;
                   4456:                 }
                   4457:                 return $access;
                   4458:             }
                   4459:         }
                   4460:     } else {
                   4461:         $access = 1;
                   4462:         return $access;
                   4463:     }
                   4464: }
                   4465: 
                   4466: sub is_advanced_user {
                   4467:     my ($udom,$uname) = @_;
                   4468:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4469:     my %allroles;
                   4470:     my $is_adv;
                   4471:     foreach my $role (keys(%roleshash)) {
                   4472:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4473:         my $area = '/'.$tdomain.'/'.$trest;
                   4474:         if ($sec ne '') {
                   4475:             $area .= '/'.$sec;
                   4476:         }
                   4477:         if (($area ne '') && ($trole ne '')) {
                   4478:             my $spec=$trole.'.'.$area;
                   4479:             if ($trole =~ /^cr\//) {
                   4480:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4481:             } elsif ($trole ne 'gr') {
                   4482:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4483:             }
                   4484:         }
                   4485:     }
                   4486:     foreach my $role (keys(%allroles)) {
                   4487:         last if ($is_adv);
                   4488:         foreach my $item (split(/:/,$allroles{$role})) {
                   4489:             if ($item ne '') {
                   4490:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4491:                 if ($privilege eq 'adv') {
                   4492:                     $is_adv = 1;
                   4493:                     last;
                   4494:                 }
                   4495:             }
                   4496:         }
                   4497:     }
                   4498:     return $is_adv;
                   4499: }
1.798     raeburn  4500: 
1.341     www      4501: # ---------------------------------------------- Custom access rule evaluation
                   4502: 
                   4503: sub customaccess {
                   4504:     my ($priv,$uri)=@_;
1.807     albertel 4505:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4506:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4507:     $udom = &LONCAPA::clean_domain($udom);
                   4508:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4509:     my $access=0;
1.800     albertel 4510:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4511: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4512: 	if ($type eq 'user') {
                   4513: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4514: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4515: 		if ($tdom) {
                   4516: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4517: 		}
1.896     albertel 4518: 		if ($tuname) {
                   4519: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4520: 		}
                   4521: 		$access=($effect eq 'allow');
                   4522: 		last;
                   4523: 	    }
                   4524: 	} else {
                   4525: 	    if ($role) {
                   4526: 		if ($role ne $urole) { next; }
                   4527: 	    }
                   4528: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4529: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4530: 		if ($tdom) {
                   4531: 		    if ($tdom ne $udom) { next; }
                   4532: 		}
                   4533: 		if ($tcrs) {
                   4534: 		    if ($tcrs ne $ucrs) { next; }
                   4535: 		}
                   4536: 		if ($tsec) {
                   4537: 		    if ($tsec ne $usec) { next; }
                   4538: 		}
                   4539: 		$access=($effect eq 'allow');
                   4540: 		last;
                   4541: 	    }
                   4542: 	    if ($realm eq '' && $role eq '') {
                   4543: 		$access=($effect eq 'allow');
                   4544: 	    }
1.402     bowersj2 4545: 	}
1.341     www      4546:     }
                   4547:     return $access;
                   4548: }
                   4549: 
1.103     harris41 4550: # ------------------------------------------------- Check for a user privilege
1.12      www      4551: 
                   4552: sub allowed {
1.810     raeburn  4553:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4554:     my $ver_orguri=$uri;
1.439     www      4555:     $uri=&deversion($uri);
1.152     www      4556:     my $orguri=$uri;
1.52      www      4557:     $uri=&declutter($uri);
1.809     raeburn  4558: 
1.810     raeburn  4559:     if ($priv eq 'evb') {
                   4560: # Evade communication block restrictions for specified role in a course
                   4561:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4562:             return $1;
                   4563:         } else {
                   4564:             return;
                   4565:         }
                   4566:     }
                   4567: 
1.620     albertel 4568:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4569: # Free bre access to adm and meta resources
1.775     albertel 4570:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4571: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4572: 	&& ($priv eq 'bre')) {
1.14      www      4573: 	return 'F';
1.159     www      4574:     }
                   4575: 
1.545     banghart 4576: # Free bre access to user's own portfolio contents
1.714     raeburn  4577:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4578:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4579: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4580:         my %setters;
                   4581:         my ($startblock,$endblock) = 
                   4582:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4583:         if ($startblock && $endblock) {
                   4584:             return 'B';
                   4585:         } else {
                   4586:             return 'F';
                   4587:         }
1.545     banghart 4588:     }
                   4589: 
1.762     raeburn  4590: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4591:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4592:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4593:         if (exists($env{'request.course.id'})) {
                   4594:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4595:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4596:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4597:                 my $courseprivid=$env{'request.course.id'};
                   4598:                 $courseprivid=~s/\_/\//;
                   4599:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4600:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4601:                     return $1; 
1.762     raeburn  4602:                 } else {
                   4603:                     if ($env{'request.course.sec'}) {
                   4604:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4605:                     }
                   4606:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4607:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4608:                         return $2;
                   4609:                     }
1.714     raeburn  4610:                 }
                   4611:             }
                   4612:         }
                   4613:     }
                   4614: 
1.159     www      4615: # Free bre to public access
                   4616: 
                   4617:     if ($priv eq 'bre') {
1.238     www      4618:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4619: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4620:            return 'F'; 
                   4621:         }
1.238     www      4622:         if ($copyright eq 'priv') {
                   4623:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4624: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4625: 		return '';
                   4626:             }
                   4627:         }
                   4628:         if ($copyright eq 'domain') {
                   4629:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4630: 	    unless (($env{'user.domain'} eq $1) ||
                   4631:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4632: 		return '';
                   4633:             }
1.262     matthew  4634:         }
1.620     albertel 4635:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4636:             # Library role, so allow browsing of resources in this domain.
                   4637:             return 'F';
1.238     www      4638:         }
1.341     www      4639:         if ($copyright eq 'custom') {
                   4640: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4641:         }
1.14      www      4642:     }
1.264     matthew  4643:     # Domain coordinator is trying to create a course
1.620     albertel 4644:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4645:         # uri is the requested domain in this case.
                   4646:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4647:         # a role of dc for the domain in question.
1.620     albertel 4648:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4649:     }
1.29      www      4650: 
1.52      www      4651:     my $thisallowed='';
                   4652:     my $statecond=0;
                   4653:     my $courseprivid='';
                   4654: 
                   4655: # Course
                   4656: 
1.620     albertel 4657:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4658:        $thisallowed.=$1;
                   4659:     }
1.29      www      4660: 
1.52      www      4661: # Domain
                   4662: 
1.620     albertel 4663:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4664:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4665:        $thisallowed.=$1;
                   4666:     }
1.52      www      4667: 
                   4668: # Course: uri itself is a course
1.66      www      4669:     my $courseuri=$uri;
                   4670:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4671:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4672: 
1.620     albertel 4673:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4674:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4675:        $thisallowed.=$1;
                   4676:     }
1.29      www      4677: 
1.665     albertel 4678: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4679: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4680:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4681: 	$thisallowed='';
1.671     raeburn  4682:         my ($match)=&is_on_map($uri);
                   4683:         if ($match) {
                   4684:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4685:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4686:                 $thisallowed.=$1;
                   4687:             }
                   4688:         } else {
1.705     albertel 4689:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4690:             if ($refuri) {
                   4691:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4692:                     $thisallowed='F';
1.671     raeburn  4693:                 } else {
                   4694:                     $refuri=&declutter($refuri);
                   4695:                     my ($match) = &is_on_map($refuri);
                   4696:                     if ($match) {
                   4697:                         $thisallowed='F';
                   4698:                     }
1.669     raeburn  4699:                 }
1.671     raeburn  4700:             }
                   4701:         }
1.314     www      4702:     }
1.492     albertel 4703: 
1.766     albertel 4704:     if ($priv eq 'bre'
                   4705: 	&& $thisallowed ne 'F' 
                   4706: 	&& $thisallowed ne '2'
                   4707: 	&& &is_portfolio_url($uri)) {
                   4708: 	$thisallowed = &portfolio_access($uri);
                   4709:     }
                   4710:     
1.52      www      4711: # Full access at system, domain or course-wide level? Exit.
1.29      www      4712:     if ($thisallowed=~/F/) {
                   4713: 	return 'F';
                   4714:     }
                   4715: 
1.52      www      4716: # If this is generating or modifying users, exit with special codes
1.29      www      4717: 
1.643     www      4718:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4719: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4720: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4721: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4722: 	    unless ($auname) { return $thisallowed; }
                   4723: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4724: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4725: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4726: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4727: 	}
1.52      www      4728: 	return $thisallowed;
                   4729:     }
                   4730: #
1.103     harris41 4731: # Gathered so far: system, domain and course wide privileges
1.52      www      4732: #
                   4733: # Course: See if uri or referer is an individual resource that is part of 
                   4734: # the course
                   4735: 
1.620     albertel 4736:     if ($env{'request.course.id'}) {
1.232     www      4737: 
1.620     albertel 4738:        $courseprivid=$env{'request.course.id'};
                   4739:        if ($env{'request.course.sec'}) {
                   4740:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4741:        }
                   4742:        $courseprivid=~s/\_/\//;
                   4743:        my $checkreferer=1;
1.232     www      4744:        my ($match,$cond)=&is_on_map($uri);
                   4745:        if ($match) {
                   4746:            $statecond=$cond;
1.620     albertel 4747:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4748:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4749:                $thisallowed.=$1;
                   4750:                $checkreferer=0;
                   4751:            }
1.29      www      4752:        }
1.83      www      4753:        
1.148     www      4754:        if ($checkreferer) {
1.620     albertel 4755: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4756:             unless ($refuri) {
1.800     albertel 4757:                 foreach my $key (keys(%env)) {
                   4758: 		    if ($key=~/^httpref\..*\*/) {
                   4759: 			my $pattern=$key;
1.156     www      4760:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4761:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4762:                         $pattern=~s/\//\\\//g;
1.152     www      4763:                         if ($orguri=~/$pattern/) {
1.800     albertel 4764: 			    $refuri=$env{$key};
1.148     www      4765:                         }
                   4766:                     }
1.191     harris41 4767:                 }
1.148     www      4768:             }
1.232     www      4769: 
1.148     www      4770:          if ($refuri) { 
1.152     www      4771: 	  $refuri=&declutter($refuri);
1.232     www      4772:           my ($match,$cond)=&is_on_map($refuri);
                   4773:             if ($match) {
                   4774:               my $refstatecond=$cond;
1.620     albertel 4775:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4776:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4777:                   $thisallowed.=$1;
1.53      www      4778:                   $uri=$refuri;
                   4779:                   $statecond=$refstatecond;
1.52      www      4780:               }
                   4781:           }
1.148     www      4782:         }
1.29      www      4783:        }
1.52      www      4784:    }
1.29      www      4785: 
1.52      www      4786: #
1.103     harris41 4787: # Gathered now: all privileges that could apply, and condition number
1.52      www      4788: # 
                   4789: #
                   4790: # Full or no access?
                   4791: #
1.29      www      4792: 
1.52      www      4793:     if ($thisallowed=~/F/) {
                   4794: 	return 'F';
                   4795:     }
1.29      www      4796: 
1.52      www      4797:     unless ($thisallowed) {
                   4798:         return '';
                   4799:     }
1.29      www      4800: 
1.52      www      4801: # Restrictions exist, deal with them
                   4802: #
                   4803: #   C:according to course preferences
                   4804: #   R:according to resource settings
                   4805: #   L:unless locked
                   4806: #   X:according to user session state
                   4807: #
                   4808: 
                   4809: # Possibly locked functionality, check all courses
1.54      www      4810: # Locks might take effect only after 10 minutes cache expiration for other
                   4811: # courses, and 2 minutes for current course
1.52      www      4812: 
                   4813:     my $envkey;
                   4814:     if ($thisallowed=~/L/) {
1.620     albertel 4815:         foreach $envkey (keys %env) {
1.54      www      4816:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4817:                my $courseid=$2;
                   4818:                my $roleid=$1.'.'.$2;
1.92      www      4819:                $courseid=~s/^\///;
1.54      www      4820:                my $expiretime=600;
1.620     albertel 4821:                if ($env{'request.role'} eq $roleid) {
1.54      www      4822: 		  $expiretime=120;
                   4823:                }
                   4824: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4825:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4826:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4827: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4828:                }
1.620     albertel 4829:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4830:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4831: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4832:                        &log($env{'user.domain'},$env{'user.name'},
                   4833:                             $env{'user.home'},
1.57      www      4834:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4835:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4836:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4837: 		       return '';
                   4838:                    }
                   4839:                }
1.620     albertel 4840:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4841:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4842: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4843:                        &log($env{'user.domain'},$env{'user.name'},
                   4844:                             $env{'user.home'},
1.57      www      4845:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4846:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4847:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4848: 		       return '';
                   4849:                    }
                   4850:                }
                   4851: 	   }
1.29      www      4852:        }
1.52      www      4853:     }
                   4854:    
                   4855: #
                   4856: # Rest of the restrictions depend on selected course
                   4857: #
                   4858: 
1.620     albertel 4859:     unless ($env{'request.course.id'}) {
1.766     albertel 4860: 	if ($thisallowed eq 'A') {
                   4861: 	    return 'A';
1.814     raeburn  4862:         } elsif ($thisallowed eq 'B') {
                   4863:             return 'B';
1.766     albertel 4864: 	} else {
                   4865: 	    return '1';
                   4866: 	}
1.52      www      4867:     }
1.29      www      4868: 
1.52      www      4869: #
                   4870: # Now user is definitely in a course
                   4871: #
1.53      www      4872: 
                   4873: 
                   4874: # Course preferences
                   4875: 
                   4876:    if ($thisallowed=~/C/) {
1.620     albertel 4877:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4878:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4879:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4880: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4881: 	   if ($priv ne 'pch') { 
                   4882: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4883: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4884: 			$env{'request.course.id'});
                   4885: 	   }
1.237     www      4886:            return '';
                   4887:        }
                   4888: 
1.620     albertel 4889:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4890: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4891: 	   if ($priv ne 'pch') { 
                   4892: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4893: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4894: 			$env{'request.course.id'});
                   4895: 	   }
1.54      www      4896:            return '';
                   4897:        }
1.53      www      4898:    }
                   4899: 
                   4900: # Resource preferences
                   4901: 
                   4902:    if ($thisallowed=~/R/) {
1.620     albertel 4903:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4904:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4905: 	   if ($priv ne 'pch') { 
                   4906: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4907: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4908: 	   }
                   4909: 	   return '';
1.54      www      4910:        }
1.53      www      4911:    }
1.30      www      4912: 
1.246     www      4913: # Restricted by state or randomout?
1.30      www      4914: 
1.52      www      4915:    if ($thisallowed=~/X/) {
1.620     albertel 4916:       if ($env{'acc.randomout'}) {
1.579     albertel 4917: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4918:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4919:             return ''; 
                   4920:          }
1.247     www      4921:       }
                   4922:       if (&condval($statecond)) {
1.52      www      4923: 	 return '2';
                   4924:       } else {
                   4925:          return '';
                   4926:       }
                   4927:    }
1.30      www      4928: 
1.766     albertel 4929:     if ($thisallowed eq 'A') {
                   4930: 	return 'A';
1.814     raeburn  4931:     } elsif ($thisallowed eq 'B') {
                   4932:         return 'B';
1.766     albertel 4933:     }
1.52      www      4934:    return 'F';
1.232     www      4935: }
                   4936: 
1.710     albertel 4937: sub split_uri_for_cond {
                   4938:     my $uri=&deversion(&declutter(shift));
                   4939:     my @uriparts=split(/\//,$uri);
                   4940:     my $filename=pop(@uriparts);
                   4941:     my $pathname=join('/',@uriparts);
                   4942:     return ($pathname,$filename);
                   4943: }
1.232     www      4944: # --------------------------------------------------- Is a resource on the map?
                   4945: 
                   4946: sub is_on_map {
1.710     albertel 4947:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4948:     #Trying to find the conditional for the file
1.620     albertel 4949:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4950: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4951:     if ($match) {
1.289     bowersj2 4952: 	return (1,$1);
                   4953:     } else {
1.434     www      4954: 	return (0,0);
1.289     bowersj2 4955:     }
1.12      www      4956: }
                   4957: 
1.427     www      4958: # --------------------------------------------------------- Get symb from alias
                   4959: 
                   4960: sub get_symb_from_alias {
                   4961:     my $symb=shift;
                   4962:     my ($map,$resid,$url)=&decode_symb($symb);
                   4963: # Already is a symb
                   4964:     if ($url) { return $symb; }
                   4965: # Must be an alias
                   4966:     my $aliassymb='';
                   4967:     my %bighash;
1.620     albertel 4968:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4969:                             &GDBM_READER(),0640)) {
                   4970:         my $rid=$bighash{'mapalias_'.$symb};
                   4971: 	if ($rid) {
                   4972: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4973: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4974: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4975: 	}
                   4976:         untie %bighash;
                   4977:     }
                   4978:     return $aliassymb;
                   4979: }
                   4980: 
1.12      www      4981: # ----------------------------------------------------------------- Define Role
                   4982: 
                   4983: sub definerole {
                   4984:   if (allowed('mcr','/')) {
                   4985:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4986:     foreach my $role (split(':',$sysrole)) {
                   4987: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4988:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4989:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4990: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4991:                return "refused:s:$crole&$cqual"; 
                   4992:             }
                   4993:         }
1.191     harris41 4994:     }
1.800     albertel 4995:     foreach my $role (split(':',$domrole)) {
                   4996: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4997:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4998:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4999: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5000:                return "refused:d:$crole&$cqual"; 
                   5001:             }
                   5002:         }
1.191     harris41 5003:     }
1.800     albertel 5004:     foreach my $role (split(':',$courole)) {
                   5005: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5006:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5007:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5008: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5009:                return "refused:c:$crole&$cqual"; 
                   5010:             }
                   5011:         }
1.191     harris41 5012:     }
1.620     albertel 5013:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5014:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5015: 	        "rolesdef_$rolename=".
                   5016:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5017:     return reply($command,$env{'user.home'});
1.12      www      5018:   } else {
                   5019:     return 'refused';
                   5020:   }
1.105     harris41 5021: }
                   5022: 
                   5023: # ---------------- Make a metadata query against the network of library servers
                   5024: 
                   5025: sub metadata_query {
1.244     matthew  5026:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5027:     my %rhash;
1.845     albertel 5028:     my %libserv = &all_library();
1.244     matthew  5029:     my @server_list = (defined($server_array) ? @$server_array
                   5030:                                               : keys(%libserv) );
                   5031:     for my $server (@server_list) {
1.118     harris41 5032: 	unless ($custom or $customshow) {
                   5033: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5034: 	    $rhash{$server}=$reply;
                   5035: 	}
                   5036: 	else {
                   5037: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5038: 			     &escape($custom).':'.&escape($customshow),
                   5039: 			     $server);
                   5040: 	    $rhash{$server}=$reply;
                   5041: 	}
1.112     harris41 5042:     }
1.118     harris41 5043:     return \%rhash;
1.240     www      5044: }
                   5045: 
                   5046: # ----------------------------------------- Send log queries and wait for reply
                   5047: 
                   5048: sub log_query {
                   5049:     my ($uname,$udom,$query,%filters)=@_;
                   5050:     my $uhome=&homeserver($uname,$udom);
                   5051:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5052:     my $uhost=&hostname($uhome);
1.800     albertel 5053:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5054:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5055:                        $uhome);
1.479     albertel 5056:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5057:     return get_query_reply($queryid);
                   5058: }
                   5059: 
1.818     raeburn  5060: # -------------------------- Update MySQL table for portfolio file
                   5061: 
                   5062: sub update_portfolio_table {
1.821     raeburn  5063:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5064:     if ($group ne '') {
                   5065:         $file_name =~s /^\Q$group\E//;
                   5066:     }
1.818     raeburn  5067:     my $homeserver = &homeserver($uname,$udom);
                   5068:     my $queryid=
1.821     raeburn  5069:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5070:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5071:     my $reply = &get_query_reply($queryid);
                   5072:     return $reply;
                   5073: }
                   5074: 
1.899     raeburn  5075: # -------------------------- Update MySQL allusers table
                   5076: 
                   5077: sub update_allusers_table {
                   5078:     my ($uname,$udom,$names) = @_;
                   5079:     my $homeserver = &homeserver($uname,$udom);
                   5080:     my $queryid=
                   5081:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5082:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5083:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5084:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5085:                'generation='.&escape($names->{'generation'}).'%%'.
                   5086:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5087:                'id='.&escape($names->{'id'}),$homeserver);
                   5088:     my $reply = &get_query_reply($queryid);
                   5089:     return $reply;
                   5090: }
                   5091: 
1.508     raeburn  5092: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5093: 
                   5094: sub fetch_enrollment_query {
1.511     raeburn  5095:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5096:     my $homeserver;
1.547     raeburn  5097:     my $maxtries = 1;
1.508     raeburn  5098:     if ($context eq 'automated') {
                   5099:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5100:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5101:     } else {
                   5102:         $homeserver = &homeserver($cnum,$dom);
                   5103:     }
1.838     albertel 5104:     my $host=&hostname($homeserver);
1.506     raeburn  5105:     my $cmd = '';
1.800     albertel 5106:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5107:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5108:     }
                   5109:     $cmd =~ s/%%$//;
                   5110:     $cmd = &escape($cmd);
                   5111:     my $query = 'fetchenrollment';
1.620     albertel 5112:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5113:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5114:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5115:         return 'error: '.$queryid;
                   5116:     }
1.506     raeburn  5117:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5118:     my $tries = 1;
                   5119:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5120:         $reply = &get_query_reply($queryid);
                   5121:         $tries ++;
                   5122:     }
1.526     raeburn  5123:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5124:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5125:     } else {
1.901     albertel 5126:         my @responses = split(/:/,$reply);
1.515     raeburn  5127:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5128:             foreach my $line (@responses) {
                   5129:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5130:                 $$replyref{$key} = $value;
                   5131:             }
                   5132:         } else {
1.506     raeburn  5133:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5134:             foreach my $line (@responses) {
                   5135:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5136:                 $$replyref{$key} = $value;
                   5137:                 if ($value > 0) {
1.800     albertel 5138:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5139:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5140:                         my $destname = $pathname.'/'.$filename;
                   5141:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5142:                         if ($xml_classlist =~ /^error/) {
                   5143:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5144:                         } else {
1.506     raeburn  5145:                             if ( open(FILE,">$destname") ) {
                   5146:                                 print FILE &unescape($xml_classlist);
                   5147:                                 close(FILE);
1.526     raeburn  5148:                             } else {
                   5149:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5150:                             }
                   5151:                         }
                   5152:                     }
                   5153:                 }
                   5154:             }
                   5155:         }
                   5156:         return 'ok';
                   5157:     }
                   5158:     return 'error';
                   5159: }
                   5160: 
1.242     www      5161: sub get_query_reply {
                   5162:     my $queryid=shift;
1.240     www      5163:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5164:     my $reply='';
                   5165:     for (1..100) {
                   5166: 	sleep 2;
                   5167:         if (-e $replyfile.'.end') {
1.448     albertel 5168: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5169: 		$reply = join('',<$fh>);
                   5170: 		close($fh);
1.240     www      5171: 	   } else { return 'error: reply_file_error'; }
1.242     www      5172:            return &unescape($reply);
                   5173: 	}
1.240     www      5174:     }
1.242     www      5175:     return 'timeout:'.$queryid;
1.240     www      5176: }
                   5177: 
                   5178: sub courselog_query {
1.241     www      5179: #
                   5180: # possible filters:
                   5181: # url: url or symb
                   5182: # username
                   5183: # domain
                   5184: # action: view, submit, grade
                   5185: # start: timestamp
                   5186: # end: timestamp
                   5187: #
1.240     www      5188:     my (%filters)=@_;
1.620     albertel 5189:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5190:     if ($filters{'url'}) {
                   5191: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5192:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5193:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5194:     }
1.620     albertel 5195:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5196:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5197:     return &log_query($cname,$cdom,'courselog',%filters);
                   5198: }
                   5199: 
                   5200: sub userlog_query {
1.858     raeburn  5201: #
                   5202: # possible filters:
                   5203: # action: log check role
                   5204: # start: timestamp
                   5205: # end: timestamp
                   5206: #
1.240     www      5207:     my ($uname,$udom,%filters)=@_;
                   5208:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5209: }
                   5210: 
1.506     raeburn  5211: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5212: 
                   5213: sub auto_run {
1.508     raeburn  5214:     my ($cnum,$cdom) = @_;
1.876     raeburn  5215:     my $response = 0;
                   5216:     my $settings;
                   5217:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5218:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5219:         $settings = $domconfig{'autoenroll'};
                   5220:         if ($settings->{'run'} eq '1') {
                   5221:             $response = 1;
                   5222:         }
                   5223:     } else {
1.934     raeburn  5224:         my $homeserver;
                   5225:         if (&is_course($cdom,$cnum)) {
                   5226:             $homeserver = &homeserver($cnum,$cdom);
                   5227:         } else {
                   5228:             $homeserver = &domain($cdom,'primary');
                   5229:         }
                   5230:         if ($homeserver ne 'no_host') {
                   5231:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5232:         }
1.876     raeburn  5233:     }
1.506     raeburn  5234:     return $response;
                   5235: }
1.776     albertel 5236: 
1.506     raeburn  5237: sub auto_get_sections {
1.508     raeburn  5238:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5239:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5240:     my @secs = ();
1.511     raeburn  5241:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5242:     unless ($response eq 'refused') {
1.901     albertel 5243:         @secs = split(/:/,$response);
1.506     raeburn  5244:     }
                   5245:     return @secs;
                   5246: }
1.776     albertel 5247: 
1.506     raeburn  5248: sub auto_new_course {
1.508     raeburn  5249:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5250:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5251:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5252:     return $response;
                   5253: }
1.776     albertel 5254: 
1.506     raeburn  5255: sub auto_validate_courseID {
1.508     raeburn  5256:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5257:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5258:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5259:     return $response;
                   5260: }
1.776     albertel 5261: 
1.506     raeburn  5262: sub auto_create_password {
1.873     raeburn  5263:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5264:     my ($homeserver,$response);
1.506     raeburn  5265:     my $create_passwd = 0;
                   5266:     my $authchk = '';
1.873     raeburn  5267:     if ($udom =~ /^$match_domain$/) {
                   5268:         $homeserver = &domain($udom,'primary');
                   5269:     }
                   5270:     if ($homeserver eq '') {
                   5271:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5272:             $homeserver = &homeserver($cnum,$cdom);
                   5273:         }
                   5274:     }
                   5275:     if ($homeserver eq '') {
                   5276:         $authchk = 'nodomain';
1.506     raeburn  5277:     } else {
1.873     raeburn  5278:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5279:         if ($response eq 'refused') {
                   5280:             $authchk = 'refused';
                   5281:         } else {
1.901     albertel 5282:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5283:         }
1.506     raeburn  5284:     }
                   5285:     return ($authparam,$create_passwd,$authchk);
                   5286: }
                   5287: 
1.706     raeburn  5288: sub auto_photo_permission {
                   5289:     my ($cnum,$cdom,$students) = @_;
                   5290:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5291:     my ($outcome,$perm_reqd,$conditions) = 
                   5292: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5293:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5294: 	return (undef,undef);
                   5295:     }
1.706     raeburn  5296:     return ($outcome,$perm_reqd,$conditions);
                   5297: }
                   5298: 
                   5299: sub auto_checkphotos {
                   5300:     my ($uname,$udom,$pid) = @_;
                   5301:     my $homeserver = &homeserver($uname,$udom);
                   5302:     my ($result,$resulttype);
                   5303:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5304: 				   &escape($uname).':'.&escape($pid),
                   5305: 				   $homeserver));
1.709     albertel 5306:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5307: 	return (undef,undef);
                   5308:     }
1.706     raeburn  5309:     if ($outcome) {
                   5310:         ($result,$resulttype) = split(/:/,$outcome);
                   5311:     } 
                   5312:     return ($result,$resulttype);
                   5313: }
                   5314: 
                   5315: sub auto_photochoice {
                   5316:     my ($cnum,$cdom) = @_;
                   5317:     my $homeserver = &homeserver($cnum,$cdom);
                   5318:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5319: 						       &escape($cdom),
                   5320: 						       $homeserver)));
1.709     albertel 5321:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5322: 	return (undef,undef);
                   5323:     }
1.706     raeburn  5324:     return ($update,$comment);
                   5325: }
                   5326: 
                   5327: sub auto_photoupdate {
                   5328:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5329:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5330:     my $host=&hostname($homeserver);
1.706     raeburn  5331:     my $cmd = '';
                   5332:     my $maxtries = 1;
1.800     albertel 5333:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5334:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5335:     }
                   5336:     $cmd =~ s/%%$//;
                   5337:     $cmd = &escape($cmd);
                   5338:     my $query = 'institutionalphotos';
                   5339:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5340:     unless ($queryid=~/^\Q$host\E\_/) {
                   5341:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5342:         return 'error: '.$queryid;
                   5343:     }
                   5344:     my $reply = &get_query_reply($queryid);
                   5345:     my $tries = 1;
                   5346:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5347:         $reply = &get_query_reply($queryid);
                   5348:         $tries ++;
                   5349:     }
                   5350:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5351:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5352:     } else {
                   5353:         my @responses = split(/:/,$reply);
                   5354:         my $outcome = shift(@responses); 
                   5355:         foreach my $item (@responses) {
                   5356:             my ($key,$value) = split(/=/,$item);
                   5357:             $$photo{$key} = $value;
                   5358:         }
                   5359:         return $outcome;
                   5360:     }
                   5361:     return 'error';
                   5362: }
                   5363: 
1.521     raeburn  5364: sub auto_instcode_format {
1.793     albertel 5365:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5366: 	$cat_order) = @_;
1.521     raeburn  5367:     my $courses = '';
1.772     raeburn  5368:     my @homeservers;
1.521     raeburn  5369:     if ($caller eq 'global') {
1.841     albertel 5370: 	my %servers = &get_servers($codedom,'library');
                   5371: 	foreach my $tryserver (keys(%servers)) {
                   5372: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5373: 		push(@homeservers,$tryserver);
                   5374: 	    }
1.584     raeburn  5375:         }
1.521     raeburn  5376:     } else {
1.772     raeburn  5377:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5378:     }
1.793     albertel 5379:     foreach my $code (keys(%{$instcodes})) {
                   5380:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5381:     }
                   5382:     chop($courses);
1.772     raeburn  5383:     my $ok_response = 0;
                   5384:     my $response;
                   5385:     while (@homeservers > 0 && $ok_response == 0) {
                   5386:         my $server = shift(@homeservers); 
                   5387:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5388:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5389:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5390: 		split(/:/,$response);
1.772     raeburn  5391:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5392:             push(@{$codetitles},&str2array($codetitles_str));
                   5393:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5394:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5395:             $ok_response = 1;
                   5396:         }
                   5397:     }
                   5398:     if ($ok_response) {
1.521     raeburn  5399:         return 'ok';
1.772     raeburn  5400:     } else {
                   5401:         return $response;
1.521     raeburn  5402:     }
                   5403: }
                   5404: 
1.792     raeburn  5405: sub auto_instcode_defaults {
                   5406:     my ($domain,$returnhash,$code_order) = @_;
                   5407:     my @homeservers;
1.841     albertel 5408: 
                   5409:     my %servers = &get_servers($domain,'library');
                   5410:     foreach my $tryserver (keys(%servers)) {
                   5411: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5412: 	    push(@homeservers,$tryserver);
                   5413: 	}
1.792     raeburn  5414:     }
1.841     albertel 5415: 
1.792     raeburn  5416:     my $response;
1.841     albertel 5417:     foreach my $server (@homeservers) {
1.792     raeburn  5418:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5419:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5420: 	
                   5421: 	foreach my $pair (split(/\&/,$response)) {
                   5422: 	    my ($name,$value)=split(/\=/,$pair);
                   5423: 	    if ($name eq 'code_order') {
                   5424: 		@{$code_order} = split(/\&/,&unescape($value));
                   5425: 	    } else {
                   5426: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5427: 	    }
                   5428: 	}
                   5429: 	return 'ok';
1.792     raeburn  5430:     }
1.841     albertel 5431: 
                   5432:     return $response;
1.792     raeburn  5433: } 
                   5434: 
1.777     albertel 5435: sub auto_validate_class_sec {
1.918     raeburn  5436:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5437:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5438:     my $ownerlist;
                   5439:     if (ref($owners) eq 'ARRAY') {
                   5440:         $ownerlist = join(',',@{$owners});
                   5441:     } else {
                   5442:         $ownerlist = $owners;
                   5443:     }
1.773     raeburn  5444:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5445:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5446:     return $response;
                   5447: }
                   5448: 
1.679     raeburn  5449: # ------------------------------------------------------- Course Group routines
                   5450: 
                   5451: sub get_coursegroups {
1.809     raeburn  5452:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5453:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5454: }
                   5455: 
1.679     raeburn  5456: sub modify_coursegroup {
                   5457:     my ($cdom,$cnum,$groupsettings) = @_;
                   5458:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5459: }
                   5460: 
1.809     raeburn  5461: sub toggle_coursegroup_status {
                   5462:     my ($cdom,$cnum,$group,$action) = @_;
                   5463:     my ($from_namespace,$to_namespace);
                   5464:     if ($action eq 'delete') {
                   5465:         $from_namespace = 'coursegroups';
                   5466:         $to_namespace = 'deleted_groups';
                   5467:     } else {
                   5468:         $from_namespace = 'deleted_groups';
                   5469:         $to_namespace = 'coursegroups';
                   5470:     }
                   5471:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5472:     if (my $tmp = &error(%curr_group)) {
                   5473:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5474:         return ('read error',$tmp);
                   5475:     } else {
                   5476:         my %savedsettings = %curr_group; 
1.809     raeburn  5477:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5478:         my $deloutcome;
                   5479:         if ($result eq 'ok') {
1.809     raeburn  5480:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5481:         } else {
                   5482:             return ('write error',$result);
                   5483:         }
                   5484:         if ($deloutcome eq 'ok') {
                   5485:             return 'ok';
                   5486:         } else {
                   5487:             return ('delete error',$deloutcome);
                   5488:         }
                   5489:     }
                   5490: }
                   5491: 
1.679     raeburn  5492: sub modify_group_roles {
1.957     raeburn  5493:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5494:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5495:     my $role = 'gr/'.&escape($userprivs);
                   5496:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5497:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5498:     if ($result eq 'ok') {
                   5499:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5500:     }
1.679     raeburn  5501:     return $result;
                   5502: }
                   5503: 
                   5504: sub modify_coursegroup_membership {
                   5505:     my ($cdom,$cnum,$membership) = @_;
                   5506:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5507:     return $result;
                   5508: }
                   5509: 
1.682     raeburn  5510: sub get_active_groups {
                   5511:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5512:     my $now = time;
                   5513:     my %groups = ();
                   5514:     foreach my $key (keys(%env)) {
1.811     albertel 5515:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5516:             my ($start,$end) = split(/\./,$env{$key});
                   5517:             if (($end!=0) && ($end<$now)) { next; }
                   5518:             if (($start!=0) && ($start>$now)) { next; }
                   5519:             if ($1 eq $cdom && $2 eq $cnum) {
                   5520:                 $groups{$3} = $env{$key} ;
                   5521:             }
                   5522:         }
                   5523:     }
                   5524:     return %groups;
                   5525: }
                   5526: 
1.683     raeburn  5527: sub get_group_membership {
                   5528:     my ($cdom,$cnum,$group) = @_;
                   5529:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5530: }
                   5531: 
                   5532: sub get_users_groups {
                   5533:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5534:     my @usersgroups;
1.683     raeburn  5535:     my $cachetime=1800;
                   5536: 
                   5537:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5538:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5539:     if (defined($cached)) {
1.734     albertel 5540:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5541:     } else {  
                   5542:         $grouplist = '';
1.816     raeburn  5543:         my $courseurl = &courseid_to_courseurl($courseid);
                   5544:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5545:         my $access_end = $env{'course.'.$courseid.
                   5546:                               '.default_enrollment_end_date'};
                   5547:         my $now = time;
                   5548:         foreach my $key (keys(%roleshash)) {
                   5549:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5550:                 my $group = $1;
                   5551:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5552:                     my $start = $2;
                   5553:                     my $end = $1;
                   5554:                     if ($start == -1) { next; } # deleted from group
                   5555:                     if (($start!=0) && ($start>$now)) { next; }
                   5556:                     if (($end!=0) && ($end<$now)) {
                   5557:                         if ($access_end && $access_end < $now) {
                   5558:                             if ($access_end - $end < 86400) {
                   5559:                                 push(@usersgroups,$group);
1.733     raeburn  5560:                             }
                   5561:                         }
1.817     raeburn  5562:                         next;
1.733     raeburn  5563:                     }
1.817     raeburn  5564:                     push(@usersgroups,$group);
1.683     raeburn  5565:                 }
                   5566:             }
                   5567:         }
1.817     raeburn  5568:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5569:         $grouplist = join(':',@usersgroups);
                   5570:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5571:     }
1.733     raeburn  5572:     return @usersgroups;
1.683     raeburn  5573: }
                   5574: 
                   5575: sub devalidate_getgroups_cache {
                   5576:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5577:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5578: 
1.683     raeburn  5579:     my $hashid="$udom:$uname:$courseid";
                   5580:     &devalidate_cache_new('getgroups',$hashid);
                   5581: }
                   5582: 
1.12      www      5583: # ------------------------------------------------------------------ Plain Text
                   5584: 
                   5585: sub plaintext {
1.742     raeburn  5586:     my ($short,$type,$cid) = @_;
1.758     albertel 5587:     if ($short =~ /^cr/) {
                   5588: 	return (split('/',$short))[-1];
                   5589:     }
1.742     raeburn  5590:     if (!defined($cid)) {
                   5591:         $cid = $env{'request.course.id'};
                   5592:     }
                   5593:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5594:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5595:                                           '.plaintext'});
                   5596:     }
                   5597:     my %rolenames = (
                   5598:                       Course => 'std',
                   5599:                       Group => 'alt1',
                   5600:                     );
                   5601:     if (defined($type) && 
                   5602:          defined($rolenames{$type}) && 
                   5603:          defined($prp{$short}{$rolenames{$type}})) {
                   5604:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5605:     } else {
                   5606:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5607:     }
1.12      www      5608: }
                   5609: 
                   5610: # ----------------------------------------------------------------- Assign Role
                   5611: 
                   5612: sub assignrole {
1.957     raeburn  5613:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5614:         $context)=@_;
1.21      www      5615:     my $mrole;
                   5616:     if ($role =~ /^cr\//) {
1.393     www      5617:         my $cwosec=$url;
1.811     albertel 5618:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5619: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5620:            &logthis('Refused custom assignrole: '.
                   5621:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5622: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5623:            return 'refused'; 
                   5624:         }
1.21      www      5625:         $mrole='cr';
1.678     raeburn  5626:     } elsif ($role =~ /^gr\//) {
                   5627:         my $cwogrp=$url;
1.811     albertel 5628:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5629:         unless (&allowed('mdg',$cwogrp)) {
                   5630:             &logthis('Refused group assignrole: '.
                   5631:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5632:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5633:             return 'refused';
                   5634:         }
                   5635:         $mrole='gr';
1.21      www      5636:     } else {
1.82      www      5637:         my $cwosec=$url;
1.811     albertel 5638:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5639:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5640:             my $refused;
                   5641:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5642:                 if (!(&allowed('c'.$role,$url))) {
                   5643:                     $refused = 1;
                   5644:                 }
                   5645:             } else {
                   5646:                 $refused = 1;
                   5647:             }
1.947     raeburn  5648:             if ($refused) {
                   5649:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5650:                     $refused = '';
                   5651:                 } else {
                   5652:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5653:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5654: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5655:                     return 'refused';
                   5656:                 }
1.932     raeburn  5657:             }
1.104     www      5658:         }
1.21      www      5659:         $mrole=$role;
                   5660:     }
1.620     albertel 5661:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5662:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5663:     if ($end) { $command.='_'.$end; }
1.21      www      5664:     if ($start) {
                   5665: 	if ($end) { 
1.81      www      5666:            $command.='_'.$start; 
1.21      www      5667:         } else {
1.81      www      5668:            $command.='_0_'.$start;
1.21      www      5669:         }
                   5670:     }
1.739     raeburn  5671:     my $origstart = $start;
                   5672:     my $origend = $end;
1.957     raeburn  5673:     my $delflag;
1.357     www      5674: # actually delete
                   5675:     if ($deleteflag) {
1.373     www      5676: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5677: # modify command to delete the role
1.620     albertel 5678:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5679:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5680: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5681: # set start and finish to negative values for userrolelog
                   5682:            $start=-1;
                   5683:            $end=-1;
1.957     raeburn  5684:            $delflag = 1;
1.357     www      5685:         }
                   5686:     }
                   5687: # send command
1.349     www      5688:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5689: # log new user role if status is ok
1.349     www      5690:     if ($answer eq 'ok') {
1.663     raeburn  5691: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5692: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5693:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5694:         unless ($role =~ /^gr/) {
                   5695:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5696:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5697:         }
1.349     www      5698:     }
                   5699:     return $answer;
1.169     harris41 5700: }
                   5701: 
                   5702: # -------------------------------------------------- Modify user authentication
1.197     www      5703: # Overrides without validation
                   5704: 
1.169     harris41 5705: sub modifyuserauth {
                   5706:     my ($udom,$uname,$umode,$upass)=@_;
                   5707:     my $uhome=&homeserver($uname,$udom);
1.197     www      5708:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5709:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5710:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5711:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5712:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5713: 		     &escape($upass),$uhome);
1.620     albertel 5714:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5715:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5716:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5717:     &log($udom,,$uname,$uhome,
1.620     albertel 5718:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5719:                                      $env{'user.name'}.', '.$umode.
1.197     www      5720:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5721:     unless ($reply eq 'ok') {
1.197     www      5722:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5723: 	return 'error: '.$reply;
                   5724:     }   
1.170     harris41 5725:     return 'ok';
1.80      www      5726: }
                   5727: 
1.81      www      5728: # --------------------------------------------------------------- Modify a user
1.80      www      5729: 
1.81      www      5730: sub modifyuser {
1.206     matthew  5731:     my ($udom,    $uname, $uid,
                   5732:         $umode,   $upass, $first,
                   5733:         $middle,  $last,  $gene,
1.963     raeburn  5734:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5735:     $udom= &LONCAPA::clean_domain($udom);
                   5736:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5737:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5738:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5739: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5740:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5741:                                      ' desiredhome not specified'). 
1.620     albertel 5742:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5743:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5744:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5745: # ----------------------------------------------------------------- Create User
1.406     albertel 5746:     if (($uhome eq 'no_host') && 
                   5747: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5748:         my $unhome='';
1.844     albertel 5749:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5750:             $unhome = $desiredhome;
1.620     albertel 5751: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5752: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5753:         } else { # load balancing routine for determining $unhome
1.81      www      5754:             my $loadm=10000000;
1.841     albertel 5755: 	    my %servers = &get_servers($udom,'library');
                   5756: 	    foreach my $tryserver (keys(%servers)) {
                   5757: 		my $answer=reply('load',$tryserver);
                   5758: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5759: 		    $loadm=$answer;
                   5760: 		    $unhome=$tryserver;
                   5761: 		}
1.80      www      5762: 	    }
                   5763:         }
                   5764:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5765: 	    return 'error: unable to find a home server for '.$uname.
                   5766:                    ' in domain '.$udom;
1.80      www      5767:         }
                   5768:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5769:                          &escape($upass),$unhome);
                   5770: 	unless ($reply eq 'ok') {
                   5771:             return 'error: '.$reply;
                   5772:         }   
1.230     stredwic 5773:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5774:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5775: 	    return 'error: unable verify users home machine.';
1.80      www      5776:         }
1.209     matthew  5777:     }   # End of creation of new user
1.80      www      5778: # ---------------------------------------------------------------------- Add ID
                   5779:     if ($uid) {
                   5780:        $uid=~tr/A-Z/a-z/;
                   5781:        my %uidhash=&idrget($udom,$uname);
1.196     www      5782:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5783:          && (!$forceid)) {
1.80      www      5784: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5785: 	      return 'error: user id "'.$uid.'" does not match '.
                   5786:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5787:           }
                   5788:        } else {
                   5789: 	  &idput($udom,($uname => $uid));
                   5790:        }
                   5791:     }
                   5792: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5793:     my @tmp=&get('environment',
1.899     raeburn  5794: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5795:                     'permanentemail','inststatus'],
1.134     albertel 5796: 		   $udom,$uname);
1.313     matthew  5797:     my %names;
                   5798:     if ($tmp[0] =~ m/^error:.*/) { 
                   5799:         %names=(); 
                   5800:     } else {
                   5801:         %names = @tmp;
                   5802:     }
1.388     www      5803: #
                   5804: # Make sure to not trash student environment if instructor does not bother
                   5805: # to supply name and email information
                   5806: #
                   5807:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5808:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5809:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5810:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5811:     if ($email) {
                   5812:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5813:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5814:     }
1.899     raeburn  5815:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5816:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5817:     my $reply = &put('environment', \%names, $udom,$uname);
                   5818:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5819:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5820:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5821:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5822:                  $umode.', '.$first.', '.$middle.', '.
                   5823: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5824:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5825:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5826:     } else {
                   5827:         $logmsg .= ' during self creation';
                   5828:     }
                   5829:     &logthis($logmsg);
1.134     albertel 5830:     return 'ok';
1.80      www      5831: }
                   5832: 
1.81      www      5833: # -------------------------------------------------------------- Modify student
1.80      www      5834: 
1.81      www      5835: sub modifystudent {
                   5836:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5837:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5838:         $selfenroll,$context)=@_;
1.455     albertel 5839:     if (!$cid) {
1.620     albertel 5840: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5841: 	    return 'not_in_class';
                   5842: 	}
1.80      www      5843:     }
                   5844: # --------------------------------------------------------------- Make the user
1.81      www      5845:     my $reply=&modifyuser
1.209     matthew  5846: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5847:          $desiredhome,$email);
1.80      www      5848:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5849:     # This will cause &modify_student_enrollment to get the uid from the
                   5850:     # students environment
                   5851:     $uid = undef if (!$forceid);
1.455     albertel 5852:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5853: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5854:     return $reply;
                   5855: }
                   5856: 
                   5857: sub modify_student_enrollment {
1.957     raeburn  5858:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5859:     my ($cdom,$cnum,$chome);
                   5860:     if (!$cid) {
1.620     albertel 5861: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5862: 	    return 'not_in_class';
                   5863: 	}
1.620     albertel 5864: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5865: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5866:     } else {
                   5867: 	($cdom,$cnum)=split(/_/,$cid);
                   5868:     }
1.620     albertel 5869:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5870:     if (!$chome) {
1.457     raeburn  5871: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5872:     }
1.455     albertel 5873:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5874:     # Make sure the user exists
1.81      www      5875:     my $uhome=&homeserver($uname,$udom);
                   5876:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5877: 	return 'error: no such user';
                   5878:     }
1.297     matthew  5879:     # Get student data if we were not given enough information
                   5880:     if (!defined($first)  || $first  eq '' || 
                   5881:         !defined($last)   || $last   eq '' || 
                   5882:         !defined($uid)    || $uid    eq '' || 
                   5883:         !defined($middle) || $middle eq '' || 
                   5884:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5885:         # They did not supply us with enough data to enroll the student, so
                   5886:         # we need to pick up more information.
1.297     matthew  5887:         my %tmp = &get('environment',
1.294     matthew  5888:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5889:                        ,$udom,$uname);
                   5890: 
1.800     albertel 5891:         #foreach my $key (keys(%tmp)) {
                   5892:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5893:         #}
1.294     matthew  5894:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5895:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5896:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5897:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5898:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5899:     }
1.556     albertel 5900:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5901:     my $reply=cput('classlist',
                   5902: 		   {"$uname:$udom" => 
1.515     raeburn  5903: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5904: 		   $cdom,$cnum);
1.81      www      5905:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5906: 	return 'error: '.$reply;
1.652     albertel 5907:     } else {
                   5908: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5909:     }
1.297     matthew  5910:     # Add student role to user
1.83      www      5911:     my $uurl='/'.$cid;
1.81      www      5912:     $uurl=~s/\_/\//g;
                   5913:     if ($usec) {
                   5914: 	$uurl.='/'.$usec;
                   5915:     }
1.957     raeburn  5916:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5917: }
                   5918: 
1.556     albertel 5919: sub format_name {
                   5920:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5921:     my $name;
                   5922:     if ($first ne 'lastname') {
                   5923: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5924:     } else {
                   5925: 	if ($lastname=~/\S/) {
                   5926: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5927: 	    $name=~s/\s+,/,/;
                   5928: 	} else {
                   5929: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5930: 	}
                   5931:     }
                   5932:     $name=~s/^\s+//;
                   5933:     $name=~s/\s+$//;
                   5934:     $name=~s/\s+/ /g;
                   5935:     return $name;
                   5936: }
                   5937: 
1.84      www      5938: # ------------------------------------------------- Write to course preferences
                   5939: 
                   5940: sub writecoursepref {
                   5941:     my ($courseid,%prefs)=@_;
                   5942:     $courseid=~s/^\///;
                   5943:     $courseid=~s/\_/\//g;
                   5944:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5945:     my $chome=homeserver($cnum,$cdomain);
                   5946:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5947: 	return 'error: no such course';
                   5948:     }
                   5949:     my $cstring='';
1.800     albertel 5950:     foreach my $pref (keys(%prefs)) {
                   5951: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5952:     }
1.84      www      5953:     $cstring=~s/\&$//;
                   5954:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5955: }
                   5956: 
                   5957: # ---------------------------------------------------------- Make/modify course
                   5958: 
                   5959: sub createcourse {
1.741     raeburn  5960:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5961:         $course_owner,$crstype)=@_;
1.84      www      5962:     $url=&declutter($url);
                   5963:     my $cid='';
1.264     matthew  5964:     unless (&allowed('ccc',$udom)) {
1.84      www      5965:         return 'refused';
                   5966:     }
                   5967: # ------------------------------------------------------------------- Create ID
1.674     www      5968:    my $uname=int(1+rand(9)).
                   5969:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5970:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5971:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5972: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5973:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5974:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5975:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5976:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5977:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5978:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5979:            return 'error: unable to generate unique course-ID';
                   5980:        } 
                   5981:    }
1.264     matthew  5982: # ------------------------------------------------ Check supplied server name
1.620     albertel 5983:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5984:     if (! &is_library($course_server)) {
1.264     matthew  5985:         return 'error:bad server name '.$course_server;
                   5986:     }
1.84      www      5987: # ------------------------------------------------------------- Make the course
                   5988:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5989:                       $course_server);
1.84      www      5990:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5991:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5992:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5993: 	return 'error: no such course';
                   5994:     }
1.271     www      5995: # ----------------------------------------------------------------- Course made
1.516     raeburn  5996: # log existence
1.918     raeburn  5997:     my $newcourse = {
                   5998:                     $udom.'_'.$uname => {
1.921     raeburn  5999:                                      description => $description,
                   6000:                                      inst_code   => $inst_code,
                   6001:                                      owner       => $course_owner,
                   6002:                                      type        => $crstype,
1.918     raeburn  6003:                                                 },
                   6004:                     };
1.921     raeburn  6005:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6006: # set toplevel url
1.271     www      6007:     my $topurl=$url;
                   6008:     unless ($nonstandard) {
                   6009: # ------------------------------------------ For standard courses, make top url
                   6010:         my $mapurl=&clutter($url);
1.278     www      6011:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6012:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6013: <map>
                   6014: <resource id="1" type="start"></resource>
                   6015: <resource id="2" src="$mapurl"></resource>
                   6016: <resource id="3" type="finish"></resource>
                   6017: <link index="1" from="1" to="2"></link>
                   6018: <link index="2" from="2" to="3"></link>
                   6019: </map>
                   6020: ENDINITMAP
                   6021:         $topurl=&declutter(
1.638     albertel 6022:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6023:                           );
                   6024:     }
                   6025: # ----------------------------------------------------------- Write preferences
1.84      www      6026:     &writecoursepref($udom.'_'.$uname,
                   6027:                      ('description' => $description,
1.271     www      6028:                       'url'         => $topurl));
1.84      www      6029:     return '/'.$udom.'/'.$uname;
                   6030: }
                   6031: 
1.813     albertel 6032: sub is_course {
                   6033:     my ($cdom,$cnum) = @_;
                   6034:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6035: 				undef,'.');
1.813     albertel 6036:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6037:         return 1;
                   6038:     }
                   6039:     return 0;
                   6040: }
                   6041: 
1.21      www      6042: # ---------------------------------------------------------- Assign Custom Role
                   6043: 
                   6044: sub assigncustomrole {
1.957     raeburn  6045:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6046:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6047:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6048: }
                   6049: 
                   6050: # ----------------------------------------------------------------- Revoke Role
                   6051: 
                   6052: sub revokerole {
1.957     raeburn  6053:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6054:     my $now=time;
1.965     raeburn  6055:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6056: }
                   6057: 
                   6058: # ---------------------------------------------------------- Revoke Custom Role
                   6059: 
                   6060: sub revokecustomrole {
1.957     raeburn  6061:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6062:     my $now=time;
1.357     www      6063:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6064:            $deleteflag,$selfenroll,$context);
1.17      www      6065: }
                   6066: 
1.533     banghart 6067: # ------------------------------------------------------------ Disk usage
1.535     albertel 6068: sub diskusage {
1.955     raeburn  6069:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6070:     $directorypath =~ s/\/$//;
                   6071:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6072:                        .&escape($getpropath).':'.&escape($uname).':'
                   6073:                        .&escape($udom),homeserver($uname,$udom));
                   6074:     if ($listing eq 'unknown_cmd') {
                   6075:         if ($getpropath) {
                   6076:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6077:         }
                   6078:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6079:     }
1.514     albertel 6080:     return $listing;
1.512     banghart 6081: }
                   6082: 
1.566     banghart 6083: sub is_locked {
                   6084:     my ($file_name, $domain, $user) = @_;
                   6085:     my @check;
                   6086:     my $is_locked;
                   6087:     push @check, $file_name;
1.613     albertel 6088:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6089: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6090:     my ($tmp)=keys(%locked);
                   6091:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6092:     
1.566     banghart 6093:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6094:         $is_locked = 'false';
                   6095:         foreach my $entry (@{$locked{$file_name}}) {
                   6096:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6097:                $is_locked = 'true';
                   6098:                last;
1.745     raeburn  6099:            }
                   6100:        }
1.566     banghart 6101:     } else {
                   6102:         $is_locked = 'false';
                   6103:     }
                   6104: }
                   6105: 
1.759     albertel 6106: sub declutter_portfile {
                   6107:     my ($file) = @_;
1.833     albertel 6108:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6109:     return $file;
                   6110: }
                   6111: 
1.559     banghart 6112: # ------------------------------------------------------------- Mark as Read Only
                   6113: 
                   6114: sub mark_as_readonly {
                   6115:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6116:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6117:     my ($tmp)=keys(%current_permissions);
                   6118:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6119:     foreach my $file (@{$files}) {
1.759     albertel 6120: 	$file = &declutter_portfile($file);
1.561     banghart 6121:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6122:     }
1.613     albertel 6123:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6124:     return;
                   6125: }
                   6126: 
1.572     banghart 6127: # ------------------------------------------------------------Save Selected Files
                   6128: 
                   6129: sub save_selected_files {
                   6130:     my ($user, $path, @files) = @_;
                   6131:     my $filename = $user."savedfiles";
1.573     banghart 6132:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6133:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6134:     foreach my $file (@files) {
1.620     albertel 6135:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6136:     }
                   6137:     foreach my $file (@other_files) {
1.574     banghart 6138:         print (OUT $file."\n");
1.572     banghart 6139:     }
1.574     banghart 6140:     close (OUT);
1.572     banghart 6141:     return 'ok';
                   6142: }
                   6143: 
1.574     banghart 6144: sub clear_selected_files {
                   6145:     my ($user) = @_;
                   6146:     my $filename = $user."savedfiles";
                   6147:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6148:     print (OUT undef);
                   6149:     close (OUT);
                   6150:     return ("ok");    
                   6151: }
                   6152: 
1.572     banghart 6153: sub files_in_path {
                   6154:     my ($user, $path) = @_;
                   6155:     my $filename = $user."savedfiles";
                   6156:     my %return_files;
1.574     banghart 6157:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6158:     while (my $line_in = <IN>) {
1.574     banghart 6159:         chomp ($line_in);
                   6160:         my @paths_and_file = split (m!/!, $line_in);
                   6161:         my $file_part = pop (@paths_and_file);
                   6162:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6163:         $path_part.='/';
                   6164:         my $path_and_file = $path_part.$file_part;
                   6165:         if ($path_part eq $path) {
                   6166:             $return_files{$file_part}= 'selected';
                   6167:         }
                   6168:     }
1.574     banghart 6169:     close (IN);
                   6170:     return (\%return_files);
1.572     banghart 6171: }
                   6172: 
                   6173: # called in portfolio select mode, to show files selected NOT in current directory
                   6174: sub files_not_in_path {
                   6175:     my ($user, $path) = @_;
                   6176:     my $filename = $user."savedfiles";
                   6177:     my @return_files;
                   6178:     my $path_part;
1.800     albertel 6179:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6180:     while (my $line = <IN>) {
1.572     banghart 6181:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6182:         my @paths_and_file = split(m|/|, $line);
                   6183:         my $file_part = pop(@paths_and_file);
                   6184:         chomp($file_part);
                   6185:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6186:         $path_part .= '/';
                   6187:         my $path_and_file = $path_part.$file_part;
                   6188:         if ($path_part ne $path) {
1.800     albertel 6189:             push(@return_files, ($path_and_file));
1.572     banghart 6190:         }
                   6191:     }
1.800     albertel 6192:     close(OUT);
1.574     banghart 6193:     return (@return_files);
1.572     banghart 6194: }
                   6195: 
1.745     raeburn  6196: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6197: 
1.745     raeburn  6198: sub get_portfile_permissions {
                   6199:     my ($domain,$user) = @_;
1.613     albertel 6200:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6201:     my ($tmp)=keys(%current_permissions);
                   6202:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6203:     return \%current_permissions;
                   6204: }
                   6205: 
                   6206: #---------------------------------------------Get portfolio file access controls
                   6207: 
1.749     raeburn  6208: sub get_access_controls {
1.745     raeburn  6209:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6210:     my %access;
                   6211:     my $real_file = $file;
                   6212:     $file =~ s/\.meta$//;
1.745     raeburn  6213:     if (defined($file)) {
1.749     raeburn  6214:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6215:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6216:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6217:             }
                   6218:         }
1.745     raeburn  6219:     } else {
1.749     raeburn  6220:         foreach my $key (keys(%{$current_permissions})) {
                   6221:             if ($key =~ /\0accesscontrol$/) {
                   6222:                 if (defined($group)) {
                   6223:                     if ($key !~ m-^\Q$group\E/-) {
                   6224:                         next;
                   6225:                     }
                   6226:                 }
                   6227:                 my ($fullpath) = split(/\0/,$key);
                   6228:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6229:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6230:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6231:                     }
                   6232:                 }
                   6233:             }
                   6234:         }
                   6235:     }
                   6236:     return %access;
                   6237: }
                   6238: 
                   6239: sub modify_access_controls {
                   6240:     my ($file_name,$changes,$domain,$user)=@_;
                   6241:     my ($outcome,$deloutcome);
                   6242:     my %store_permissions;
                   6243:     my %new_values;
                   6244:     my %new_control;
                   6245:     my %translation;
                   6246:     my @deletions = ();
                   6247:     my $now = time;
                   6248:     if (exists($$changes{'activate'})) {
                   6249:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6250:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6251:             my $numnew = scalar(@newitems);
                   6252:             for (my $i=0; $i<$numnew; $i++) {
                   6253:                 my $newkey = $newitems[$i];
                   6254:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6255:                 if ($newkey =~ /^\d+:/) { 
                   6256:                     $newkey =~ s/^(\d+)/$newid/;
                   6257:                     $translation{$1} = $newid;
                   6258:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6259:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6260:                     $translation{$1} = $newid;
                   6261:                 }
1.749     raeburn  6262:                 $new_values{$file_name."\0".$newkey} = 
                   6263:                                           $$changes{'activate'}{$newitems[$i]};
                   6264:                 $new_control{$newkey} = $now;
                   6265:             }
                   6266:         }
                   6267:     }
                   6268:     my %todelete;
                   6269:     my %changed_items;
                   6270:     foreach my $action ('delete','update') {
                   6271:         if (exists($$changes{$action})) {
                   6272:             if (ref($$changes{$action}) eq 'HASH') {
                   6273:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6274:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6275:                     if ($action eq 'delete') { 
                   6276:                         $todelete{$itemnum} = 1;
                   6277:                     } else {
                   6278:                         $changed_items{$itemnum} = $key;
                   6279:                     }
                   6280:                 }
1.745     raeburn  6281:             }
                   6282:         }
1.749     raeburn  6283:     }
                   6284:     # get lock on access controls for file.
                   6285:     my $lockhash = {
                   6286:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6287:                                                        ':'.$env{'user.domain'},
                   6288:                    }; 
                   6289:     my $tries = 0;
                   6290:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6291:    
                   6292:     while (($gotlock ne 'ok') && $tries <3) {
                   6293:         $tries ++;
                   6294:         sleep 1;
                   6295:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6296:     }
                   6297:     if ($gotlock eq 'ok') {
                   6298:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6299:         my ($tmp)=keys(%curr_permissions);
                   6300:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6301:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6302:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6303:             if (ref($curr_controls) eq 'HASH') {
                   6304:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6305:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6306:                     if (defined($todelete{$itemnum})) {
                   6307:                         push(@deletions,$file_name."\0".$control_item);
                   6308:                     } else {
                   6309:                         if (defined($changed_items{$itemnum})) {
                   6310:                             $new_control{$changed_items{$itemnum}} = $now;
                   6311:                             push(@deletions,$file_name."\0".$control_item);
                   6312:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6313:                         } else {
                   6314:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6315:                         }
                   6316:                     }
1.745     raeburn  6317:                 }
                   6318:             }
                   6319:         }
1.970     raeburn  6320:         my ($group);
                   6321:         if (&is_course($domain,$user)) {
                   6322:             ($group,my $file) = split(/\//,$file_name,2);
                   6323:         }
1.749     raeburn  6324:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6325:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6326:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6327:         #  remove lock
                   6328:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6329:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6330:         my $sqlresult =
1.970     raeburn  6331:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6332:                                     $group);
1.749     raeburn  6333:     } else {
                   6334:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6335:     }
1.749     raeburn  6336:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6337: }
                   6338: 
1.827     raeburn  6339: sub make_public_indefinitely {
                   6340:     my ($requrl) = @_;
                   6341:     my $now = time;
                   6342:     my $action = 'activate';
                   6343:     my $aclnum = 0;
                   6344:     if (&is_portfolio_url($requrl)) {
                   6345:         my (undef,$udom,$unum,$file_name,$group) =
                   6346:             &parse_portfolio_url($requrl);
                   6347:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6348:         my %access_controls = &get_access_controls($current_perms,
                   6349:                                                    $group,$file_name);
                   6350:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6351:             my ($num,$scope,$end,$start) = 
                   6352:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6353:             if ($scope eq 'public') {
                   6354:                 if ($start <= $now && $end == 0) {
                   6355:                     $action = 'none';
                   6356:                 } else {
                   6357:                     $action = 'update';
                   6358:                     $aclnum = $num;
                   6359:                 }
                   6360:                 last;
                   6361:             }
                   6362:         }
                   6363:         if ($action eq 'none') {
                   6364:              return 'ok';
                   6365:         } else {
                   6366:             my %changes;
                   6367:             my $newend = 0;
                   6368:             my $newstart = $now;
                   6369:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6370:             $changes{$action}{$newkey} = {
                   6371:                 type => 'public',
                   6372:                 time => {
                   6373:                     start => $newstart,
                   6374:                     end   => $newend,
                   6375:                 },
                   6376:             };
                   6377:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6378:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6379:             return $outcome;
                   6380:         }
                   6381:     } else {
                   6382:         return 'invalid';
                   6383:     }
                   6384: }
                   6385: 
1.745     raeburn  6386: #------------------------------------------------------Get Marked as Read Only
                   6387: 
                   6388: sub get_marked_as_readonly {
                   6389:     my ($domain,$user,$what,$group) = @_;
                   6390:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6391:     my @readonly_files;
1.629     banghart 6392:     my $cmp1=$what;
                   6393:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6394:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6395:         if (defined($group)) {
                   6396:             if ($file_name !~ m-^\Q$group\E/-) {
                   6397:                 next;
                   6398:             }
                   6399:         }
1.561     banghart 6400:         if (ref($value) eq "ARRAY"){
                   6401:             foreach my $stored_what (@{$value}) {
1.629     banghart 6402:                 my $cmp2=$stored_what;
1.759     albertel 6403:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6404:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6405:                 }
1.629     banghart 6406:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6407:                     push(@readonly_files, $file_name);
1.745     raeburn  6408:                     last;
1.563     banghart 6409:                 } elsif (!defined($what)) {
                   6410:                     push(@readonly_files, $file_name);
1.745     raeburn  6411:                     last;
1.561     banghart 6412:                 }
                   6413:             }
1.745     raeburn  6414:         }
1.561     banghart 6415:     }
                   6416:     return @readonly_files;
                   6417: }
1.577     banghart 6418: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6419: 
1.577     banghart 6420: sub get_marked_as_readonly_hash {
1.745     raeburn  6421:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6422:     my %readonly_files;
1.745     raeburn  6423:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6424:         if (defined($group)) {
                   6425:             if ($file_name !~ m-^\Q$group\E/-) {
                   6426:                 next;
                   6427:             }
                   6428:         }
1.577     banghart 6429:         if (ref($value) eq "ARRAY"){
                   6430:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6431:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6432:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6433:                         if ($lock_descriptor eq 'graded') {
                   6434:                             $readonly_files{$file_name} = 'graded';
                   6435:                         } elsif ($lock_descriptor eq 'handback') {
                   6436:                             $readonly_files{$file_name} = 'handback';
                   6437:                         } else {
                   6438:                             if (!exists($readonly_files{$file_name})) {
                   6439:                                 $readonly_files{$file_name} = 'locked';
                   6440:                             }
                   6441:                         }
1.745     raeburn  6442:                     }
1.750     banghart 6443:                 } 
1.577     banghart 6444:             }
                   6445:         } 
                   6446:     }
                   6447:     return %readonly_files;
                   6448: }
1.559     banghart 6449: # ------------------------------------------------------------ Unmark as Read Only
                   6450: 
                   6451: sub unmark_as_readonly {
1.629     banghart 6452:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6453:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6454:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6455:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6456:     my $symb_crs = $what;
                   6457:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6458:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6459:     my ($tmp)=keys(%current_permissions);
                   6460:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6461:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6462:     foreach my $file (@readonly_files) {
1.759     albertel 6463: 	my $clean_file = &declutter_portfile($file);
                   6464: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6465: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6466:         my @new_locks;
                   6467:         my @del_keys;
                   6468:         if (ref($current_locks) eq "ARRAY"){
                   6469:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6470:                 my $compare=$locker;
1.749     raeburn  6471:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6472:                     $compare=join('',@{$locker});
1.746     raeburn  6473:                     if ($compare ne $symb_crs) {
                   6474:                         push(@new_locks, $locker);
                   6475:                     }
1.563     banghart 6476:                 }
                   6477:             }
1.650     albertel 6478:             if (scalar(@new_locks) > 0) {
1.563     banghart 6479:                 $current_permissions{$file} = \@new_locks;
                   6480:             } else {
                   6481:                 push(@del_keys, $file);
1.613     albertel 6482:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6483:                 delete($current_permissions{$file});
1.563     banghart 6484:             }
                   6485:         }
1.561     banghart 6486:     }
1.613     albertel 6487:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6488:     return;
                   6489: }
1.512     banghart 6490: 
1.17      www      6491: # ------------------------------------------------------------ Directory lister
                   6492: 
                   6493: sub dirlist {
1.955     raeburn  6494:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6495:     $uri=~s/^\///;
                   6496:     $uri=~s/\/$//;
1.253     stredwic 6497:     my ($udom, $uname);
1.955     raeburn  6498:     if ($getuserdir) {
1.253     stredwic 6499:         $udom = $userdomain;
                   6500:         $uname = $username;
1.955     raeburn  6501:     } else {
                   6502:         (undef,$udom,$uname)=split(/\//,$uri);
                   6503:         if(defined($userdomain)) {
                   6504:             $udom = $userdomain;
                   6505:         }
                   6506:         if(defined($username)) {
                   6507:             $uname = $username;
                   6508:         }
1.253     stredwic 6509:     }
1.955     raeburn  6510:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6511: 
1.955     raeburn  6512:     $dirRoot = $perlvar{'lonDocRoot'};
                   6513:     if (defined($getpropath)) {
                   6514:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6515:         $dirRoot =~ s/\/$//;
1.955     raeburn  6516:     } elsif (defined($getuserdir)) {
                   6517:         my $subdir=$uname.'__';
                   6518:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6519:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6520:                    ."/$udom/$subdir/$uname";
                   6521:     } elsif (defined($alternateRoot)) {
                   6522:         $dirRoot = $alternateRoot;
1.751     banghart 6523:     }
1.253     stredwic 6524: 
                   6525:     if($udom) {
                   6526:         if($uname) {
1.955     raeburn  6527:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6528:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6529:                               .':'.&escape($uname).':'.&escape($udom),
                   6530:                               &homeserver($uname,$udom));
                   6531:             if ($listing eq 'unknown_cmd') {
                   6532:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6533:                                   &homeserver($uname,$udom));
                   6534:             } else {
                   6535:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6536:             }
1.605     matthew  6537:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6538:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6539: 				  &homeserver($uname,$udom));
1.605     matthew  6540:                 @listing_results = split(/:/,$listing);
                   6541:             } else {
                   6542:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6543:             }
                   6544:             return @listing_results;
1.955     raeburn  6545:         } elsif(!$alternateRoot) {
1.800     albertel 6546:             my %allusers;
1.841     albertel 6547: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6548:  	    foreach my $tryserver (keys(%servers)) {
                   6549:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6550:                                   &escape($udom),$tryserver);
                   6551:                 if ($listing eq 'unknown_cmd') {
                   6552: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6553: 				      $udom, $tryserver);
                   6554:                 } else {
                   6555:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6556:                 }
1.841     albertel 6557: 		if ($listing eq 'unknown_cmd') {
                   6558: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6559: 				      $udom, $tryserver);
                   6560: 		    @listing_results = split(/:/,$listing);
                   6561: 		} else {
                   6562: 		    @listing_results =
                   6563: 			map { &unescape($_); } split(/:/,$listing);
                   6564: 		}
                   6565: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6566: 		    $listing_results[0] ne 'empty'       &&
                   6567: 		    $listing_results[0] ne 'con_lost') {
                   6568: 		    foreach my $line (@listing_results) {
                   6569: 			my ($entry) = split(/&/,$line,2);
                   6570: 			$allusers{$entry} = 1;
                   6571: 		    }
                   6572: 		}
1.253     stredwic 6573:             }
                   6574:             my $alluserstr='';
1.800     albertel 6575:             foreach my $user (sort(keys(%allusers))) {
                   6576:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6577:             }
                   6578:             $alluserstr=~s/:$//;
                   6579:             return split(/:/,$alluserstr);
                   6580:         } else {
1.800     albertel 6581:             return ('missing user name');
1.253     stredwic 6582:         }
1.955     raeburn  6583:     } elsif(!defined($getpropath)) {
1.841     albertel 6584:         my @all_domains = sort(&all_domains());
1.955     raeburn  6585:         foreach my $domain (@all_domains) {
                   6586:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6587:         }
                   6588:         return @all_domains;
                   6589:     } else {
1.800     albertel 6590:         return ('missing domain');
1.275     stredwic 6591:     }
                   6592: }
                   6593: 
                   6594: # --------------------------------------------- GetFileTimestamp
                   6595: # This function utilizes dirlist and returns the date stamp for
                   6596: # when it was last modified.  It will also return an error of -1
                   6597: # if an error occurs
                   6598: 
                   6599: sub GetFileTimestamp {
1.955     raeburn  6600:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6601:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6602:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6603:     my ($fileStat) = 
                   6604:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6605:                                  undef,$getuserdir);
1.275     stredwic 6606:     my @stats = split('&', $fileStat);
                   6607:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6608:         # @stats contains first the filename, then the stat output
                   6609:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6610:     } else {
                   6611:         return -1;
1.253     stredwic 6612:     }
1.26      www      6613: }
                   6614: 
1.712     albertel 6615: sub stat_file {
                   6616:     my ($uri) = @_;
1.787     albertel 6617:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6618: 
1.955     raeburn  6619:     my ($udom,$uname,$file);
1.712     albertel 6620:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6621: 	($udom,$uname,$file) =
1.811     albertel 6622: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6623: 	$file = 'userfiles/'.$file;
                   6624:     }
                   6625:     if ($uri =~ m-^/res/-) {
                   6626: 	($udom,$uname) = 
1.807     albertel 6627: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6628: 	$file = $uri;
                   6629:     }
                   6630: 
                   6631:     if (!$udom || !$uname || !$file) {
                   6632: 	# unable to handle the uri
                   6633: 	return ();
                   6634:     }
1.956     raeburn  6635:     my $getpropath;
                   6636:     if ($file =~ /^userfiles\//) {
                   6637:         $getpropath = 1;
                   6638:     }
1.955     raeburn  6639:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6640:     my @stats = split('&', $result);
1.721     banghart 6641:     
1.712     albertel 6642:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6643: 	shift(@stats); #filename is first
                   6644: 	return @stats;
                   6645:     }
                   6646:     return ();
                   6647: }
                   6648: 
1.26      www      6649: # -------------------------------------------------------- Value of a Condition
                   6650: 
1.713     albertel 6651: # gets the value of a specific preevaluated condition
                   6652: #    stored in the string  $env{user.state.<cid>}
                   6653: # or looks up a condition reference in the bighash and if if hasn't
                   6654: # already been evaluated recurses into docondval to get the value of
                   6655: # the condition, then memoizing it to 
                   6656: #   $env{user.state.<cid>.<condition>}
1.40      www      6657: sub directcondval {
                   6658:     my $number=shift;
1.620     albertel 6659:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6660: 	&Apache::lonuserstate::evalstate();
                   6661:     }
1.713     albertel 6662:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6663: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6664:     } elsif ($number =~ /^_/) {
                   6665: 	my $sub_condition;
                   6666: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6667: 		&GDBM_READER(),0640)) {
                   6668: 	    $sub_condition=$bighash{'conditions'.$number};
                   6669: 	    untie(%bighash);
                   6670: 	}
                   6671: 	my $value = &docondval($sub_condition);
1.949     raeburn  6672: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6673: 	return $value;
                   6674:     }
1.620     albertel 6675:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6676:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6677:     } else {
                   6678:        return 2;
                   6679:     }
                   6680: }
                   6681: 
1.713     albertel 6682: # get the collection of conditions for this resource
1.26      www      6683: sub condval {
                   6684:     my $condidx=shift;
1.54      www      6685:     my $allpathcond='';
1.713     albertel 6686:     foreach my $cond (split(/\|/,$condidx)) {
                   6687: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6688: 	    $allpathcond.=
                   6689: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6690: 	}
1.191     harris41 6691:     }
1.54      www      6692:     $allpathcond=~s/\|$//;
1.713     albertel 6693:     return &docondval($allpathcond);
                   6694: }
                   6695: 
                   6696: #evaluates an expression of conditions
                   6697: sub docondval {
                   6698:     my ($allpathcond) = @_;
                   6699:     my $result=0;
                   6700:     if ($env{'request.course.id'}
                   6701: 	&& defined($allpathcond)) {
                   6702: 	my $operand='|';
                   6703: 	my @stack;
                   6704: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6705: 	    if ($chunk eq '(') {
                   6706: 		push @stack,($operand,$result);
                   6707: 	    } elsif ($chunk eq ')') {
                   6708: 		my $before=pop @stack;
                   6709: 		if (pop @stack eq '&') {
                   6710: 		    $result=$result>$before?$before:$result;
                   6711: 		} else {
                   6712: 		    $result=$result>$before?$result:$before;
                   6713: 		}
                   6714: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6715: 		$operand=$chunk;
                   6716: 	    } else {
                   6717: 		my $new=directcondval($chunk);
                   6718: 		if ($operand eq '&') {
                   6719: 		    $result=$result>$new?$new:$result;
                   6720: 		} else {
                   6721: 		    $result=$result>$new?$result:$new;
                   6722: 		}
                   6723: 	    }
                   6724: 	}
1.26      www      6725:     }
                   6726:     return $result;
1.421     albertel 6727: }
                   6728: 
                   6729: # ---------------------------------------------------- Devalidate courseresdata
                   6730: 
                   6731: sub devalidatecourseresdata {
                   6732:     my ($coursenum,$coursedomain)=@_;
                   6733:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6734:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6735: }
                   6736: 
1.763     www      6737: 
1.200     www      6738: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6739: #
                   6740: #  Parameters:
                   6741: #      $coursenum    - Number of the course.
                   6742: #      $coursedomain - Domain at which the course was created.
                   6743: #  Returns:
                   6744: #     A hash of the course parameters along (I think) with timestamps
                   6745: #     and version info.
1.877     foxr     6746: 
1.624     albertel 6747: sub get_courseresdata {
                   6748:     my ($coursenum,$coursedomain)=@_;
1.200     www      6749:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6750:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6751:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6752:     my %dumpreply;
1.417     albertel 6753:     unless (defined($cached)) {
1.624     albertel 6754: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6755: 	$result=\%dumpreply;
1.251     albertel 6756: 	my ($tmp) = keys(%dumpreply);
                   6757: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6758: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6759: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6760: 	    return $tmp;
1.416     albertel 6761: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6762: 	    $result=undef;
1.599     albertel 6763: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6764: 	}
                   6765:     }
1.624     albertel 6766:     return $result;
                   6767: }
                   6768: 
1.633     albertel 6769: sub devalidateuserresdata {
                   6770:     my ($uname,$udom)=@_;
                   6771:     my $hashid="$udom:$uname";
                   6772:     &devalidate_cache_new('userres',$hashid);
                   6773: }
                   6774: 
1.624     albertel 6775: sub get_userresdata {
                   6776:     my ($uname,$udom)=@_;
                   6777:     #most student don\'t have any data set, check if there is some data
                   6778:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6779: 
                   6780:     my $hashid="$udom:$uname";
                   6781:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6782:     if (!defined($cached)) {
                   6783: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6784: 	$result=\%resourcedata;
                   6785: 	&do_cache_new('userres',$hashid,$result,600);
                   6786:     }
                   6787:     my ($tmp)=keys(%$result);
                   6788:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6789: 	return $result;
                   6790:     }
                   6791:     #error 2 occurs when the .db doesn't exist
                   6792:     if ($tmp!~/error: 2 /) {
1.672     albertel 6793: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6794: 		 " Trying to get resource data for ".
                   6795: 		 $uname." at ".$udom.": ".
                   6796: 		 $tmp."</font>");
                   6797:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6798: 	#&EXT_cache_set($udom,$uname);
                   6799: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6800: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6801:     }
                   6802:     return $tmp;
                   6803: }
1.879     foxr     6804: #----------------------------------------------- resdata - return resource data
                   6805: #  Purpose:
                   6806: #    Return resource data for either users or for a course.
                   6807: #  Parameters:
                   6808: #     $name      - Course/user name.
                   6809: #     $domain    - Name of the domain the user/course is registered on.
                   6810: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6811: #     @which     - Array of names of resources desired.
                   6812: #  Returns:
                   6813: #     The value of the first reasource in @which that is found in the
                   6814: #     resource hash.
                   6815: #  Exceptional Conditions:
                   6816: #     If the $type passed in is not valid (not the string 'course' or 
                   6817: #     'user', an undefined  reference is returned.
                   6818: #     If none of the resources are found, an undef is returned
1.624     albertel 6819: sub resdata {
                   6820:     my ($name,$domain,$type,@which)=@_;
                   6821:     my $result;
                   6822:     if ($type eq 'course') {
                   6823: 	$result=&get_courseresdata($name,$domain);
                   6824:     } elsif ($type eq 'user') {
                   6825: 	$result=&get_userresdata($name,$domain);
                   6826:     }
                   6827:     if (!ref($result)) { return $result; }    
1.251     albertel 6828:     foreach my $item (@which) {
1.927     albertel 6829: 	if (defined($result->{$item->[0]})) {
                   6830: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6831: 	}
1.250     albertel 6832:     }
1.291     albertel 6833:     return undef;
1.200     www      6834: }
                   6835: 
1.379     matthew  6836: #
                   6837: # EXT resource caching routines
                   6838: #
                   6839: 
                   6840: sub clear_EXT_cache_status {
1.383     albertel 6841:     &delenv('cache.EXT.');
1.379     matthew  6842: }
                   6843: 
                   6844: sub EXT_cache_status {
                   6845:     my ($target_domain,$target_user) = @_;
1.383     albertel 6846:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6847:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6848:         # We know already the user has no data
                   6849:         return 1;
                   6850:     } else {
                   6851:         return 0;
                   6852:     }
                   6853: }
                   6854: 
                   6855: sub EXT_cache_set {
                   6856:     my ($target_domain,$target_user) = @_;
1.383     albertel 6857:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6858:     #&appenv({$cachename => time});
1.379     matthew  6859: }
                   6860: 
1.28      www      6861: # --------------------------------------------------------- Value of a Variable
1.58      www      6862: sub EXT {
1.715     albertel 6863: 
1.395     albertel 6864:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6865:     unless ($varname) { return ''; }
1.218     albertel 6866:     #get real user name/domain, courseid and symb
                   6867:     my $courseid;
1.359     albertel 6868:     my $publicuser;
1.427     www      6869:     if ($symbparm) {
                   6870: 	$symbparm=&get_symb_from_alias($symbparm);
                   6871:     }
1.218     albertel 6872:     if (!($uname && $udom)) {
1.790     albertel 6873:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6874:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6875:     } else {
1.620     albertel 6876: 	$courseid=$env{'request.course.id'};
1.218     albertel 6877:     }
1.48      www      6878:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6879:     my $rest;
1.320     albertel 6880:     if (defined($therest[0])) {
1.48      www      6881:        $rest=join('.',@therest);
                   6882:     } else {
                   6883:        $rest='';
                   6884:     }
1.320     albertel 6885: 
1.57      www      6886:     my $qualifierrest=$qualifier;
                   6887:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6888:     my $spacequalifierrest=$space;
                   6889:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6890:     if ($realm eq 'user') {
1.48      www      6891: # --------------------------------------------------------------- user.resource
                   6892: 	if ($space eq 'resource') {
1.651     albertel 6893: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6894: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6895: 		 &&
1.744     albertel 6896: 		 ($symbparm eq &symbread()) ) {	
                   6897: 		# if we are in the middle of processing the resource the
                   6898: 		# get the value we are planning on committing
                   6899:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6900:                     return $Apache::lonhomework::results{$qualifierrest};
                   6901:                 } else {
                   6902:                     return $Apache::lonhomework::history{$qualifierrest};
                   6903:                 }
1.335     albertel 6904: 	    } else {
1.359     albertel 6905: 		my %restored;
1.620     albertel 6906: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6907: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6908: 		} else {
                   6909: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6910: 		}
1.335     albertel 6911: 		return $restored{$qualifierrest};
                   6912: 	    }
1.48      www      6913: # ----------------------------------------------------------------- user.access
                   6914:         } elsif ($space eq 'access') {
1.218     albertel 6915: 	    # FIXME - not supporting calls for a specific user
1.48      www      6916:             return &allowed($qualifier,$rest);
                   6917: # ------------------------------------------ user.preferences, user.environment
                   6918:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6919: 	    if (($uname eq $env{'user.name'}) &&
                   6920: 		($udom eq $env{'user.domain'})) {
                   6921: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6922: 	    } else {
1.359     albertel 6923: 		my %returnhash;
                   6924: 		if (!$publicuser) {
                   6925: 		    %returnhash=&userenvironment($udom,$uname,
                   6926: 						 $qualifierrest);
                   6927: 		}
1.218     albertel 6928: 		return $returnhash{$qualifierrest};
                   6929: 	    }
1.48      www      6930: # ----------------------------------------------------------------- user.course
                   6931:         } elsif ($space eq 'course') {
1.218     albertel 6932: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6933:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6934: # ------------------------------------------------------------------- user.role
                   6935:         } elsif ($space eq 'role') {
1.218     albertel 6936: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6937:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6938:             if ($qualifier eq 'value') {
                   6939: 		return $role;
                   6940:             } elsif ($qualifier eq 'extent') {
                   6941:                 return $where;
                   6942:             }
                   6943: # ----------------------------------------------------------------- user.domain
                   6944:         } elsif ($space eq 'domain') {
1.218     albertel 6945:             return $udom;
1.48      www      6946: # ------------------------------------------------------------------- user.name
                   6947:         } elsif ($space eq 'name') {
1.218     albertel 6948:             return $uname;
1.48      www      6949: # ---------------------------------------------------- Any other user namespace
1.29      www      6950:         } else {
1.359     albertel 6951: 	    my %reply;
                   6952: 	    if (!$publicuser) {
                   6953: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6954: 	    }
                   6955: 	    return $reply{$qualifierrest};
1.48      www      6956:         }
1.236     www      6957:     } elsif ($realm eq 'query') {
                   6958: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6959:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6960: 						[$spacequalifierrest]);
1.620     albertel 6961: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6962:    } elsif ($realm eq 'request') {
1.48      www      6963: # ------------------------------------------------------------- request.browser
                   6964:         if ($space eq 'browser') {
1.430     www      6965: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6966: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6967: 		    return 1;
                   6968: 		} else {
                   6969: 		    return 0;
                   6970: 		}
                   6971: 	    } else {
1.620     albertel 6972: 		return $env{'browser.'.$qualifier};
1.430     www      6973: 	    }
1.57      www      6974: # ------------------------------------------------------------ request.filename
                   6975:         } else {
1.620     albertel 6976:             return $env{'request.'.$spacequalifierrest};
1.29      www      6977:         }
1.28      www      6978:     } elsif ($realm eq 'course') {
1.48      www      6979: # ---------------------------------------------------------- course.description
1.620     albertel 6980:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6981:     } elsif ($realm eq 'resource') {
1.165     www      6982: 
1.620     albertel 6983: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6984: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6985: 	}
1.693     albertel 6986: 
                   6987: 	if ($space eq 'title') {
                   6988: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6989: 	    return &gettitle($symbparm);
                   6990: 	}
                   6991: 	
                   6992: 	if ($space eq 'map') {
                   6993: 	    my ($map) = &decode_symb($symbparm);
                   6994: 	    return &symbread($map);
                   6995: 	}
1.905     albertel 6996: 	if ($space eq 'filename') {
                   6997: 	    if ($symbparm) {
                   6998: 		return &clutter((&decode_symb($symbparm))[2]);
                   6999: 	    }
                   7000: 	    return &hreflocation('',$env{'request.filename'});
                   7001: 	}
1.693     albertel 7002: 
                   7003: 	my ($section, $group, @groups);
1.593     albertel 7004: 	my ($courselevelm,$courselevel);
1.539     albertel 7005: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7006: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7007: 
1.218     albertel 7008: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7009: 
1.60      www      7010: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7011: 	    my $symbp=$symbparm;
1.735     albertel 7012: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7013: 
                   7014: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7015: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7016: 
1.620     albertel 7017: 	    if (($env{'user.name'} eq $uname) &&
                   7018: 		($env{'user.domain'} eq $udom)) {
                   7019: 		$section=$env{'request.course.sec'};
1.733     raeburn  7020:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7021:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7022: 	    } else {
1.539     albertel 7023: 		if (! defined($usection)) {
1.551     albertel 7024: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7025: 		} else {
                   7026: 		    $section = $usection;
                   7027: 		}
1.733     raeburn  7028:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7029: 	    }
                   7030: 
                   7031: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7032: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7033: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7034: 
1.593     albertel 7035: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7036: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7037: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7038: 
1.60      www      7039: # ----------------------------------------------------------- first, check user
1.624     albertel 7040: 
                   7041: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7042: 				       ([$courselevelr,'resource'],
                   7043: 					[$courselevelm,'map'     ],
                   7044: 					[$courselevel, 'course'  ]));
1.931     albertel 7045: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7046: 
1.594     albertel 7047: # ------------------------------------------------ second, check some of course
1.684     raeburn  7048:             my $coursereply;
1.691     raeburn  7049:             if (@groups > 0) {
                   7050:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7051:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7052:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7053:             }
1.96      www      7054: 
1.684     raeburn  7055: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7056: 				  $env{'course.'.$courseid.'.domain'},
                   7057: 				  'course',
                   7058: 				  ([$seclevelr,   'resource'],
                   7059: 				   [$seclevelm,   'map'     ],
                   7060: 				   [$seclevel,    'course'  ],
                   7061: 				   [$courselevelr,'resource']));
                   7062: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7063: 
1.60      www      7064: # ------------------------------------------------------ third, check map parms
1.218     albertel 7065: 	    my %parmhash=();
                   7066: 	    my $thisparm='';
                   7067: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7068: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7069: 		    &GDBM_READER(),0640)) {
1.218     albertel 7070: 		$thisparm=$parmhash{$symbparm};
                   7071: 		untie(%parmhash);
                   7072: 	    }
1.927     albertel 7073: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7074: 	}
1.594     albertel 7075: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7076: 
1.218     albertel 7077: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7078: 	my $filename;
                   7079: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7080: 	if ($symbparm) {
1.409     www      7081: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7082: 	} else {
1.620     albertel 7083: 	    $filename=$env{'request.filename'};
1.282     albertel 7084: 	}
                   7085: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7086: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7087: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7088: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7089: 
1.927     albertel 7090: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7091: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7092: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7093: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7094: 				     $env{'course.'.$courseid.'.domain'},
                   7095: 				     'course',
1.927     albertel 7096: 				     ([$courselevelm,'map'   ],
                   7097: 				      [$courselevel, 'course']));
                   7098: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7099: 	}
1.145     www      7100: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7101: 	unless ($space eq '0') {
1.336     albertel 7102: 	    my @parts=split(/_/,$space);
                   7103: 	    my $id=pop(@parts);
                   7104: 	    my $part=join('_',@parts);
                   7105: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7106: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7107: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7108: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7109: 	}
1.395     albertel 7110: 	if ($recurse) { return undef; }
                   7111: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7112: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7113: # ---------------------------------------------------- Any other user namespace
                   7114:     } elsif ($realm eq 'environment') {
                   7115: # ----------------------------------------------------------------- environment
1.620     albertel 7116: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7117: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7118: 	} else {
1.770     albertel 7119: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7120: 		return '';
                   7121: 	    }
1.219     albertel 7122: 	    my %returnhash=&userenvironment($udom,$uname,
                   7123: 					    $spacequalifierrest);
                   7124: 	    return $returnhash{$spacequalifierrest};
                   7125: 	}
1.28      www      7126:     } elsif ($realm eq 'system') {
1.48      www      7127: # ----------------------------------------------------------------- system.time
                   7128: 	if ($space eq 'time') {
                   7129: 	    return time;
                   7130:         }
1.696     albertel 7131:     } elsif ($realm eq 'server') {
                   7132: # ----------------------------------------------------------------- system.time
                   7133: 	if ($space eq 'name') {
                   7134: 	    return $ENV{'SERVER_NAME'};
                   7135:         }
1.28      www      7136:     }
1.48      www      7137:     return '';
1.61      www      7138: }
                   7139: 
1.927     albertel 7140: sub get_reply {
                   7141:     my ($reply_value) = @_;
1.940     raeburn  7142:     if (ref($reply_value) eq 'ARRAY') {
                   7143:         if (wantarray) {
                   7144: 	    return @$reply_value;
                   7145:         }
                   7146:         return $reply_value->[0];
                   7147:     } else {
                   7148:         return $reply_value;
1.927     albertel 7149:     }
                   7150: }
                   7151: 
1.691     raeburn  7152: sub check_group_parms {
                   7153:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7154:     my @groupitems = ();
                   7155:     my $resultitem;
1.927     albertel 7156:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7157:     foreach my $group (@{$groups}) {
                   7158:         foreach my $level (@levels) {
1.927     albertel 7159:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7160:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7161:         }
                   7162:     }
                   7163:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7164:                             $env{'course.'.$courseid.'.domain'},
                   7165:                                      'course',@groupitems);
                   7166:     return $coursereply;
                   7167: }
                   7168: 
                   7169: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7170:     my ($courseid,@groups) = @_;
                   7171:     @groups = sort(@groups);
1.691     raeburn  7172:     return @groups;
                   7173: }
                   7174: 
1.395     albertel 7175: sub packages_tab_default {
                   7176:     my ($uri,$varname)=@_;
                   7177:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7178: 
                   7179:     my (@extension,@specifics,$do_default);
                   7180:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7181: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7182: 	if ($pack_type eq 'default') {
                   7183: 	    $do_default=1;
                   7184: 	} elsif ($pack_type eq 'extension') {
                   7185: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7186: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7187: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7188: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7189: 	}
                   7190:     }
                   7191:     # first look for a package that matches the requested part id
                   7192:     foreach my $package (@specifics) {
                   7193: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7194: 	next if ($pack_part ne $part);
                   7195: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7196: 	    return $packagetab{"$pack_type&$name&default"};
                   7197: 	}
                   7198:     }
                   7199:     # look for any possible matching non extension_ package
                   7200:     foreach my $package (@specifics) {
                   7201: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7202: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7203: 	    return $packagetab{"$pack_type&$name&default"};
                   7204: 	}
1.585     albertel 7205: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7206: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7207: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7208: 	}
                   7209:     }
1.738     albertel 7210:     # look for any posible extension_ match
                   7211:     foreach my $package (@extension) {
                   7212: 	my ($package,$pack_type)=@{$package};
                   7213: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7214: 	    return $packagetab{"$pack_type&$name&default"};
                   7215: 	}
                   7216: 	if (defined($packagetab{$package."&$name&default"})) {
                   7217: 	    return $packagetab{$package."&$name&default"};
                   7218: 	}
                   7219:     }
                   7220:     # look for a global default setting
                   7221:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7222: 	return $packagetab{"default&$name&default"};
                   7223:     }
1.395     albertel 7224:     return undef;
                   7225: }
                   7226: 
1.334     albertel 7227: sub add_prefix_and_part {
                   7228:     my ($prefix,$part)=@_;
                   7229:     my $keyroot;
                   7230:     if (defined($prefix) && $prefix !~ /^__/) {
                   7231: 	# prefix that has a part already
                   7232: 	$keyroot=$prefix;
                   7233:     } elsif (defined($prefix)) {
                   7234: 	# prefix that is missing a part
                   7235: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7236:     } else {
                   7237: 	# no prefix at all
                   7238: 	if (defined($part)) { $keyroot='_'.$part; }
                   7239:     }
                   7240:     return $keyroot;
                   7241: }
                   7242: 
1.71      www      7243: # ---------------------------------------------------------------- Get metadata
                   7244: 
1.599     albertel 7245: my %metaentry;
1.71      www      7246: sub metadata {
1.176     www      7247:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7248:     $uri=&declutter($uri);
1.288     albertel 7249:     # if it is a non metadata possible uri return quickly
1.529     albertel 7250:     if (($uri eq '') || 
                   7251: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7252: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7253:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7254: 	return undef;
                   7255:     }
                   7256:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7257: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7258: 	return undef;
1.288     albertel 7259:     }
1.73      www      7260:     my $filename=$uri;
                   7261:     $uri=~s/\.meta$//;
1.172     www      7262: #
                   7263: # Is the metadata already cached?
1.177     www      7264: # Look at timestamp of caching
1.172     www      7265: # Everything is cached by the main uri, libraries are never directly cached
                   7266: #
1.428     albertel 7267:     if (!defined($liburi)) {
1.599     albertel 7268: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7269: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7270:     }
                   7271:     {
1.172     www      7272: #
                   7273: # Is this a recursive call for a library?
                   7274: #
1.599     albertel 7275: #	if (! exists($metacache{$uri})) {
                   7276: #	    $metacache{$uri}={};
                   7277: #	}
1.924     albertel 7278: 	my $cachetime = 60*60;
1.171     www      7279:         if ($liburi) {
                   7280: 	    $liburi=&declutter($liburi);
                   7281:             $filename=$liburi;
1.401     bowersj2 7282:         } else {
1.599     albertel 7283: 	    &devalidate_cache_new('meta',$uri);
                   7284: 	    undef(%metaentry);
1.401     bowersj2 7285: 	}
1.140     www      7286:         my %metathesekeys=();
1.73      www      7287:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7288: 	my $metastring;
1.924     albertel 7289: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7290: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7291: 	    $metastring = 
1.929     albertel 7292: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7293: 					  ('grade_target' => 'meta'));
                   7294: 	    $cachetime = 1; # only want this cached in the child not long term
                   7295: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7296: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7297: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7298: 	    $metastring=&getfile($file);
1.489     albertel 7299: 	}
1.208     albertel 7300:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7301:         my $token;
1.140     www      7302:         undef %metathesekeys;
1.71      www      7303:         while ($token=$parser->get_token) {
1.339     albertel 7304: 	    if ($token->[0] eq 'S') {
                   7305: 		if (defined($token->[2]->{'package'})) {
1.172     www      7306: #
                   7307: # This is a package - get package info
                   7308: #
1.339     albertel 7309: 		    my $package=$token->[2]->{'package'};
                   7310: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7311: 		    if (defined($token->[2]->{'id'})) { 
                   7312: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7313: 		    }
1.599     albertel 7314: 		    if ($metaentry{':packages'}) {
                   7315: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7316: 		    } else {
1.599     albertel 7317: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7318: 		    }
1.736     albertel 7319: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7320: 			my $part=$keyroot;
                   7321: 			$part=~s/^\_//;
1.736     albertel 7322: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7323: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7324: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7325: 			    # ignore package.tab specified default values
                   7326:                             # here &package_tab_default() will fetch those
                   7327: 			    if ($subp eq 'default') { next; }
1.736     albertel 7328: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7329: 			    my $unikey;
                   7330: 			    if ($pack =~ /_0$/) {
                   7331: 				$unikey='parameter_0_'.$name;
                   7332: 				$part=0;
                   7333: 			    } else {
                   7334: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7335: 			    }
1.339     albertel 7336: 			    if ($subp eq 'display') {
                   7337: 				$value.=' [Part: '.$part.']';
                   7338: 			    }
1.599     albertel 7339: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7340: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7341: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7342: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7343: 			    }
1.599     albertel 7344: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7345: 				$metaentry{':'.$unikey}=
                   7346: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7347: 			    }
1.339     albertel 7348: 			}
                   7349: 		    }
                   7350: 		} else {
1.172     www      7351: #
                   7352: # This is not a package - some other kind of start tag
1.339     albertel 7353: #
                   7354: 		    my $entry=$token->[1];
                   7355: 		    my $unikey;
                   7356: 		    if ($entry eq 'import') {
                   7357: 			$unikey='';
                   7358: 		    } else {
                   7359: 			$unikey=$entry;
                   7360: 		    }
                   7361: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7362: 
                   7363: 		    if (defined($token->[2]->{'id'})) { 
                   7364: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7365: 		    }
1.175     www      7366: 
1.339     albertel 7367: 		    if ($entry eq 'import') {
1.175     www      7368: #
                   7369: # Importing a library here
1.339     albertel 7370: #
                   7371: 			if ($depthcount<20) {
                   7372: 			    my $location=$parser->get_text('/import');
                   7373: 			    my $dir=$filename;
                   7374: 			    $dir=~s|[^/]*$||;
                   7375: 			    $location=&filelocation($dir,$location);
1.736     albertel 7376: 			    my $metadata = 
                   7377: 				&metadata($uri,'keys', $location,$unikey,
                   7378: 					  $depthcount+1);
                   7379: 			    foreach my $meta (split(',',$metadata)) {
                   7380: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7381: 				$metathesekeys{$meta}=1;
1.339     albertel 7382: 			    }
                   7383: 			}
                   7384: 		    } else { 
                   7385: 			
                   7386: 			if (defined($token->[2]->{'name'})) { 
                   7387: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7388: 			}
                   7389: 			$metathesekeys{$unikey}=1;
1.736     albertel 7390: 			foreach my $param (@{$token->[3]}) {
                   7391: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7392: 				$token->[2]->{$param};
1.339     albertel 7393: 			}
                   7394: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7395: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7396: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7397: 		 # only ws inside the tag, and not in default, so use default
                   7398: 		 # as value
1.599     albertel 7399: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7400: 			} elsif ( $internaltext =~ /\S/ ) {
                   7401: 		  # something interesting inside the tag
                   7402: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7403: 			} else {
1.908     albertel 7404: 		  # no interesting values, don't set a default
1.339     albertel 7405: 			}
1.172     www      7406: # end of not-a-package not-a-library import
1.339     albertel 7407: 		    }
1.172     www      7408: # end of not-a-package start tag
1.339     albertel 7409: 		}
1.172     www      7410: # the next is the end of "start tag"
1.339     albertel 7411: 	    }
                   7412: 	}
1.483     albertel 7413: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7414: 	$extension = lc($extension);
                   7415: 	if ($extension eq 'htm') { $extension='html'; }
                   7416: 
1.737     albertel 7417: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7418: 	    #no specific packages #how's our extension
                   7419: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7420: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7421: 					 \%metathesekeys);
                   7422: 	}
1.883     albertel 7423: 
                   7424: 	if (!exists($metaentry{':packages'})
                   7425: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7426: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7427: 		#no specific packages well let's get default then
                   7428: 		if ($key!~/^default&/) { next; }
1.488     albertel 7429: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7430: 					     \%metathesekeys);
                   7431: 	    }
                   7432: 	}
1.338     www      7433: # are there custom rights to evaluate
1.599     albertel 7434: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7435: 
1.338     www      7436:     #
                   7437:     # Importing a rights file here
1.339     albertel 7438:     #
                   7439: 	    unless ($depthcount) {
1.599     albertel 7440: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7441: 		my $dir=$filename;
                   7442: 		$dir=~s|[^/]*$||;
                   7443: 		$location=&filelocation($dir,$location);
1.736     albertel 7444: 		my $rights_metadata =
                   7445: 		    &metadata($uri,'keys',$location,'_rights',
                   7446: 			      $depthcount+1);
                   7447: 		foreach my $rights (split(',',$rights_metadata)) {
                   7448: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7449: 		    $metathesekeys{$rights}=1;
1.339     albertel 7450: 		}
                   7451: 	    }
                   7452: 	}
1.737     albertel 7453: 	# uniqifiy package listing
                   7454: 	my %seen;
                   7455: 	my @uniq_packages =
                   7456: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7457: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7458: 
                   7459: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7460: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7461: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7462: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7463: # this is the end of "was not already recently cached
1.71      www      7464:     }
1.599     albertel 7465:     return $metaentry{':'.$what};
1.261     albertel 7466: }
                   7467: 
1.488     albertel 7468: sub metadata_create_package_def {
1.483     albertel 7469:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7470:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7471:     if ($subp eq 'default') { next; }
                   7472:     
1.599     albertel 7473:     if (defined($metaentry{':packages'})) {
                   7474: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7475:     } else {
1.599     albertel 7476: 	$metaentry{':packages'}=$package;
1.483     albertel 7477:     }
                   7478:     my $value=$packagetab{$key};
                   7479:     my $unikey;
                   7480:     $unikey='parameter_0_'.$name;
1.599     albertel 7481:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7482:     $$metathesekeys{$unikey}=1;
1.599     albertel 7483:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7484: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7485:     }
1.599     albertel 7486:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7487: 	$metaentry{':'.$unikey}=
                   7488: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7489:     }
                   7490: }
                   7491: 
1.261     albertel 7492: sub metadata_generate_part0 {
                   7493:     my ($metadata,$metacache,$uri) = @_;
                   7494:     my %allnames;
1.737     albertel 7495:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7496: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7497: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7498: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7499: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7500: 	    $allnames{$name}=$part;
                   7501: 	  }
                   7502: 	}
                   7503:     }
                   7504:     foreach my $name (keys(%allnames)) {
                   7505:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7506:       my $key=":parameter_0_$name";
1.261     albertel 7507:       $$metacache{"$key.part"}='0';
                   7508:       $$metacache{"$key.name"}=$name;
1.428     albertel 7509:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7510: 					   $allnames{$name}.'_'.$name.
                   7511: 					   '.type'};
1.428     albertel 7512:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7513: 			     '.display'};
1.644     www      7514:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7515:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7516:       $$metacache{"$key.display"}=$olddis;
                   7517:     }
1.71      www      7518: }
                   7519: 
1.764     albertel 7520: # ------------------------------------------------------ Devalidate title cache
                   7521: 
                   7522: sub devalidate_title_cache {
                   7523:     my ($url)=@_;
                   7524:     if (!$env{'request.course.id'}) { return; }
                   7525:     my $symb=&symbread($url);
                   7526:     if (!$symb) { return; }
                   7527:     my $key=$env{'request.course.id'}."\0".$symb;
                   7528:     &devalidate_cache_new('title',$key);
                   7529: }
                   7530: 
1.301     www      7531: # ------------------------------------------------- Get the title of a resource
                   7532: 
                   7533: sub gettitle {
                   7534:     my $urlsymb=shift;
                   7535:     my $symb=&symbread($urlsymb);
1.534     albertel 7536:     if ($symb) {
1.620     albertel 7537: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7538: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7539: 	if (defined($cached)) { 
                   7540: 	    return $result;
                   7541: 	}
1.534     albertel 7542: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7543: 	my $title='';
1.907     albertel 7544: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7545: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7546: 	} else {
                   7547: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7548: 		    &GDBM_READER(),0640)) {
                   7549: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7550: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7551: 		untie(%bighash);
                   7552: 	    }
1.534     albertel 7553: 	}
                   7554: 	$title=~s/\&colon\;/\:/gs;
                   7555: 	if ($title) {
1.599     albertel 7556: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7557: 	}
                   7558: 	$urlsymb=$url;
                   7559:     }
                   7560:     my $title=&metadata($urlsymb,'title');
                   7561:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7562:     return $title;
1.301     www      7563: }
1.613     albertel 7564: 
1.614     albertel 7565: sub get_slot {
                   7566:     my ($which,$cnum,$cdom)=@_;
                   7567:     if (!$cnum || !$cdom) {
1.790     albertel 7568: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7569: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7570: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7571:     }
1.703     albertel 7572:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7573:     my %slotinfo;
                   7574:     if (exists($remembered{$key})) {
                   7575: 	$slotinfo{$which} = $remembered{$key};
                   7576:     } else {
                   7577: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7578: 	&Apache::lonhomework::showhash(%slotinfo);
                   7579: 	my ($tmp)=keys(%slotinfo);
                   7580: 	if ($tmp=~/^error:/) { return (); }
                   7581: 	$remembered{$key} = $slotinfo{$which};
                   7582:     }
1.616     albertel 7583:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7584: 	return %{$slotinfo{$which}};
                   7585:     }
                   7586:     return $slotinfo{$which};
1.614     albertel 7587: }
1.31      www      7588: # ------------------------------------------------- Update symbolic store links
                   7589: 
                   7590: sub symblist {
                   7591:     my ($mapname,%newhash)=@_;
1.438     www      7592:     $mapname=&deversion(&declutter($mapname));
1.31      www      7593:     my %hash;
1.620     albertel 7594:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7595:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7596:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7597: 	    foreach my $url (keys %newhash) {
                   7598: 		next if ($url eq 'last_known'
                   7599: 			 && $env{'form.no_update_last_known'});
                   7600: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7601: 						    $newhash{$url}->[1],
                   7602: 						    $newhash{$url}->[0]);
1.191     harris41 7603:             }
1.31      www      7604:             if (untie(%hash)) {
                   7605: 		return 'ok';
                   7606:             }
                   7607:         }
                   7608:     }
                   7609:     return 'error';
1.212     www      7610: }
                   7611: 
                   7612: # --------------------------------------------------------------- Verify a symb
                   7613: 
                   7614: sub symbverify {
1.510     www      7615:     my ($symb,$thisurl)=@_;
                   7616:     my $thisfn=$thisurl;
1.439     www      7617:     $thisfn=&declutter($thisfn);
1.215     www      7618: # direct jump to resource in page or to a sequence - will construct own symbs
                   7619:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7620: # check URL part
1.409     www      7621:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7622: 
1.431     www      7623:     unless ($url eq $thisfn) { return 0; }
1.213     www      7624: 
1.216     www      7625:     $symb=&symbclean($symb);
1.510     www      7626:     $thisurl=&deversion($thisurl);
1.439     www      7627:     $thisfn=&deversion($thisfn);
1.213     www      7628: 
                   7629:     my %bighash;
                   7630:     my $okay=0;
1.431     www      7631: 
1.620     albertel 7632:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7633:                             &GDBM_READER(),0640)) {
1.510     www      7634:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7635:         unless ($ids) { 
1.510     www      7636:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7637:         }
                   7638:         if ($ids) {
                   7639: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7640: 	    foreach my $id (split(/\,/,$ids)) {
                   7641: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7642:                if (
                   7643:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7644:    eq $symb) { 
1.620     albertel 7645: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7646: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7647: 		       $okay=1; 
                   7648: 		   }
                   7649: 	       }
1.216     www      7650: 	   }
                   7651:         }
1.213     www      7652: 	untie(%bighash);
                   7653:     }
                   7654:     return $okay;
1.31      www      7655: }
                   7656: 
1.210     www      7657: # --------------------------------------------------------------- Clean-up symb
                   7658: 
                   7659: sub symbclean {
                   7660:     my $symb=shift;
1.568     albertel 7661:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7662: # remove version from map
                   7663:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7664: 
1.210     www      7665: # remove version from URL
                   7666:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7667: 
1.507     www      7668: # remove wrapper
                   7669: 
1.510     www      7670:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7671:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7672:     return $symb;
1.409     www      7673: }
                   7674: 
                   7675: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7676: 
                   7677: sub encode_symb {
                   7678:     my ($map,$resid,$url)=@_;
                   7679:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7680: }
1.409     www      7681: 
                   7682: sub decode_symb {
1.568     albertel 7683:     my $symb=shift;
                   7684:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7685:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7686:     return (&fixversion($map),$resid,&fixversion($url));
                   7687: }
                   7688: 
                   7689: sub fixversion {
                   7690:     my $fn=shift;
1.609     banghart 7691:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7692:     my %bighash;
                   7693:     my $uri=&clutter($fn);
1.620     albertel 7694:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7695: # is this cached?
1.599     albertel 7696:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7697:     if (defined($cached)) { return $result; }
                   7698: # unfortunately not cached, or expired
1.620     albertel 7699:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7700: 	    &GDBM_READER(),0640)) {
                   7701:  	if ($bighash{'version_'.$uri}) {
                   7702:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7703:  	    unless (($version eq 'mostrecent') || 
                   7704: 		    ($version==&getversion($uri))) {
1.440     www      7705:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7706:  	    }
                   7707:  	}
                   7708:  	untie %bighash;
1.413     www      7709:     }
1.599     albertel 7710:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7711: }
                   7712: 
                   7713: sub deversion {
                   7714:     my $url=shift;
                   7715:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7716:     return $url;
1.210     www      7717: }
                   7718: 
1.31      www      7719: # ------------------------------------------------------ Return symb list entry
                   7720: 
                   7721: sub symbread {
1.249     www      7722:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7723:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7724:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7725: # no filename provided? try from environment
1.44      www      7726:     unless ($thisfn) {
1.620     albertel 7727:         if ($env{'request.symb'}) {
                   7728: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7729: 	}
1.620     albertel 7730: 	$thisfn=$env{'request.filename'};
1.44      www      7731:     }
1.569     albertel 7732:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7733: # is that filename actually a symb? Verify, clean, and return
                   7734:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7735: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7736: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7737: 	}
1.242     www      7738:     }
1.44      www      7739:     $thisfn=declutter($thisfn);
1.31      www      7740:     my %hash;
1.37      www      7741:     my %bighash;
                   7742:     my $syval='';
1.620     albertel 7743:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7744:         my $targetfn = $thisfn;
1.609     banghart 7745:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7746:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7747:         }
1.687     albertel 7748: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7749: 	    $targetfn=$1;
                   7750: 	}
1.620     albertel 7751:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7752:                       &GDBM_READER(),0640)) {
1.481     raeburn  7753: 	    $syval=$hash{$targetfn};
1.37      www      7754:             untie(%hash);
                   7755:         }
                   7756: # ---------------------------------------------------------- There was an entry
                   7757:         if ($syval) {
1.601     albertel 7758: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7759: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7760: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7761: 		    #return $env{$cache_str}='';
1.601     albertel 7762: 		#}    
                   7763: 		#$syval.=$1;
                   7764: 	    #}
1.37      www      7765:         } else {
                   7766: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7767:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7768:                             &GDBM_READER(),0640)) {
1.37      www      7769: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7770:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7771:               unless ($ids) { 
                   7772:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7773:               }
                   7774:               unless ($ids) {
                   7775: # alias?
                   7776: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7777:               }
1.37      www      7778:               if ($ids) {
                   7779: # ------------------------------------------------------------------- Has ID(s)
                   7780:                  my @possibilities=split(/\,/,$ids);
1.39      www      7781:                  if ($#possibilities==0) {
                   7782: # ----------------------------------------------- There is only one possibility
1.37      www      7783: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7784: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7785: 						    $resid,$thisfn);
1.249     www      7786:                  } elsif (!$donotrecurse) {
1.39      www      7787: # ------------------------------------------ There is more than one possibility
                   7788:                      my $realpossible=0;
1.800     albertel 7789:                      foreach my $id (@possibilities) {
                   7790: 			 my $file=$bighash{'src_'.$id};
1.39      www      7791:                          if (&allowed('bre',$file)) {
1.800     albertel 7792:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7793:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7794: 				$realpossible++;
1.626     albertel 7795:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7796: 						    $resid,$thisfn);
1.39      www      7797:                             }
                   7798: 			 }
1.191     harris41 7799:                      }
1.39      www      7800: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7801:                  } else {
                   7802:                      $syval='';
1.37      www      7803:                  }
                   7804: 	      }
                   7805:               untie(%bighash)
1.481     raeburn  7806:            }
1.31      www      7807:         }
1.62      www      7808:         if ($syval) {
1.620     albertel 7809: 	    return $env{$cache_str}=$syval;
1.62      www      7810:         }
1.31      www      7811:     }
1.949     raeburn  7812:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7813:     return $env{$cache_str}='';
1.31      www      7814: }
                   7815: 
                   7816: # ---------------------------------------------------------- Return random seed
                   7817: 
1.32      www      7818: sub numval {
                   7819:     my $txt=shift;
                   7820:     $txt=~tr/A-J/0-9/;
                   7821:     $txt=~tr/a-j/0-9/;
                   7822:     $txt=~tr/K-T/0-9/;
                   7823:     $txt=~tr/k-t/0-9/;
                   7824:     $txt=~tr/U-Z/0-5/;
                   7825:     $txt=~tr/u-z/0-5/;
                   7826:     $txt=~s/\D//g;
1.564     albertel 7827:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7828:     return int($txt);
1.368     albertel 7829: }
                   7830: 
1.484     albertel 7831: sub numval2 {
                   7832:     my $txt=shift;
                   7833:     $txt=~tr/A-J/0-9/;
                   7834:     $txt=~tr/a-j/0-9/;
                   7835:     $txt=~tr/K-T/0-9/;
                   7836:     $txt=~tr/k-t/0-9/;
                   7837:     $txt=~tr/U-Z/0-5/;
                   7838:     $txt=~tr/u-z/0-5/;
                   7839:     $txt=~s/\D//g;
                   7840:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7841:     my $total;
                   7842:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7843:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7844:     return int($total);
                   7845: }
                   7846: 
1.575     albertel 7847: sub numval3 {
                   7848:     use integer;
                   7849:     my $txt=shift;
                   7850:     $txt=~tr/A-J/0-9/;
                   7851:     $txt=~tr/a-j/0-9/;
                   7852:     $txt=~tr/K-T/0-9/;
                   7853:     $txt=~tr/k-t/0-9/;
                   7854:     $txt=~tr/U-Z/0-5/;
                   7855:     $txt=~tr/u-z/0-5/;
                   7856:     $txt=~s/\D//g;
                   7857:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7858:     my $total;
                   7859:     foreach my $val (@txts) { $total+=$val; }
                   7860:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7861:     return $total;
                   7862: }
                   7863: 
1.675     albertel 7864: sub digest {
                   7865:     my ($data)=@_;
                   7866:     my $digest=&Digest::MD5::md5($data);
                   7867:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7868:     my ($e,$f);
                   7869:     {
                   7870:         use integer;
                   7871:         $e=($a+$b);
                   7872:         $f=($c+$d);
                   7873:         if ($_64bit) {
                   7874:             $e=(($e<<32)>>32);
                   7875:             $f=(($f<<32)>>32);
                   7876:         }
                   7877:     }
                   7878:     if (wantarray) {
                   7879: 	return ($e,$f);
                   7880:     } else {
                   7881: 	my $g;
                   7882: 	{
                   7883: 	    use integer;
                   7884: 	    $g=($e+$f);
                   7885: 	    if ($_64bit) {
                   7886: 		$g=(($g<<32)>>32);
                   7887: 	    }
                   7888: 	}
                   7889: 	return $g;
                   7890:     }
                   7891: }
                   7892: 
1.368     albertel 7893: sub latest_rnd_algorithm_id {
1.675     albertel 7894:     return '64bit5';
1.366     albertel 7895: }
1.32      www      7896: 
1.503     albertel 7897: sub get_rand_alg {
                   7898:     my ($courseid)=@_;
1.790     albertel 7899:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7900:     if ($courseid) {
1.620     albertel 7901: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7902:     }
                   7903:     return &latest_rnd_algorithm_id();
                   7904: }
                   7905: 
1.562     albertel 7906: sub validCODE {
                   7907:     my ($CODE)=@_;
                   7908:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7909:     return 0;
                   7910: }
                   7911: 
1.491     albertel 7912: sub getCODE {
1.620     albertel 7913:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7914:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7915: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7916: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7917: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7918:     }
                   7919:     return undef;
                   7920: }
                   7921: 
1.31      www      7922: sub rndseed {
1.155     albertel 7923:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7924:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7925:     if (!defined($symb)) {
1.366     albertel 7926: 	unless ($symb=$wsymb) { return time; }
                   7927:     }
                   7928:     if (!$courseid) { $courseid=$wcourseid; }
                   7929:     if (!$domain) { $domain=$wdomain; }
                   7930:     if (!$username) { $username=$wusername }
1.503     albertel 7931:     my $which=&get_rand_alg();
1.803     albertel 7932: 
1.491     albertel 7933:     if (defined(&getCODE())) {
1.675     albertel 7934: 	if ($which eq '64bit5') {
                   7935: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7936: 	} elsif ($which eq '64bit4') {
1.575     albertel 7937: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7938: 	} else {
                   7939: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7940: 	}
1.675     albertel 7941:     } elsif ($which eq '64bit5') {
                   7942: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7943:     } elsif ($which eq '64bit4') {
                   7944: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7945:     } elsif ($which eq '64bit3') {
                   7946: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7947:     } elsif ($which eq '64bit2') {
                   7948: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7949:     } elsif ($which eq '64bit') {
                   7950: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7951:     }
                   7952:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7953: }
                   7954: 
                   7955: sub rndseed_32bit {
                   7956:     my ($symb,$courseid,$domain,$username)=@_;
                   7957:     {
                   7958: 	use integer;
                   7959: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7960: 	my $symbseed=numval($symb) << 22;
                   7961: 	my $namechck=unpack("%32C*",$username) << 17;
                   7962: 	my $nameseed=numval($username) << 12;
                   7963: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7964: 	my $courseseed=unpack("%32C*",$courseid);
                   7965: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7966: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7967: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7968: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7969: 	return $num;
                   7970:     }
                   7971: }
                   7972: 
                   7973: sub rndseed_64bit {
                   7974:     my ($symb,$courseid,$domain,$username)=@_;
                   7975:     {
                   7976: 	use integer;
                   7977: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7978: 	my $symbseed=numval($symb) << 10;
                   7979: 	my $namechck=unpack("%32S*",$username);
                   7980: 	
                   7981: 	my $nameseed=numval($username) << 21;
                   7982: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7983: 	my $courseseed=unpack("%32S*",$courseid);
                   7984: 	
                   7985: 	my $num1=$symbchck+$symbseed+$namechck;
                   7986: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7987: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7988: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7989: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7990: 	return "$num1,$num2";
1.155     albertel 7991:     }
1.366     albertel 7992: }
                   7993: 
1.443     albertel 7994: sub rndseed_64bit2 {
                   7995:     my ($symb,$courseid,$domain,$username)=@_;
                   7996:     {
                   7997: 	use integer;
                   7998: 	# strings need to be an even # of cahracters long, it it is odd the
                   7999:         # last characters gets thrown away
                   8000: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8001: 	my $symbseed=numval($symb) << 10;
                   8002: 	my $namechck=unpack("%32S*",$username.' ');
                   8003: 	
                   8004: 	my $nameseed=numval($username) << 21;
1.501     albertel 8005: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8006: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8007: 	
                   8008: 	my $num1=$symbchck+$symbseed+$namechck;
                   8009: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8010: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8011: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8012: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8013: 	return "$num1,$num2";
                   8014:     }
                   8015: }
                   8016: 
                   8017: sub rndseed_64bit3 {
                   8018:     my ($symb,$courseid,$domain,$username)=@_;
                   8019:     {
                   8020: 	use integer;
                   8021: 	# strings need to be an even # of cahracters long, it it is odd the
                   8022:         # last characters gets thrown away
                   8023: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8024: 	my $symbseed=numval2($symb) << 10;
                   8025: 	my $namechck=unpack("%32S*",$username.' ');
                   8026: 	
                   8027: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8028: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8029: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8030: 	
                   8031: 	my $num1=$symbchck+$symbseed+$namechck;
                   8032: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8033: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8034: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8035: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8036: 	
1.503     albertel 8037: 	return "$num1:$num2";
1.443     albertel 8038:     }
                   8039: }
                   8040: 
1.575     albertel 8041: sub rndseed_64bit4 {
                   8042:     my ($symb,$courseid,$domain,$username)=@_;
                   8043:     {
                   8044: 	use integer;
                   8045: 	# strings need to be an even # of cahracters long, it it is odd the
                   8046:         # last characters gets thrown away
                   8047: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8048: 	my $symbseed=numval3($symb) << 10;
                   8049: 	my $namechck=unpack("%32S*",$username.' ');
                   8050: 	
                   8051: 	my $nameseed=numval3($username) << 21;
                   8052: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8053: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8054: 	
                   8055: 	my $num1=$symbchck+$symbseed+$namechck;
                   8056: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8057: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8058: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8059: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8060: 	
                   8061: 	return "$num1:$num2";
                   8062:     }
                   8063: }
                   8064: 
1.675     albertel 8065: sub rndseed_64bit5 {
                   8066:     my ($symb,$courseid,$domain,$username)=@_;
                   8067:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8068:     return "$num1:$num2";
                   8069: }
                   8070: 
1.366     albertel 8071: sub rndseed_CODE_64bit {
                   8072:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8073:     {
1.366     albertel 8074: 	use integer;
1.443     albertel 8075: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8076: 	my $symbseed=numval2($symb);
1.491     albertel 8077: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8078: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8079: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8080: 	my $num1=$symbseed+$CODEchck;
                   8081: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8082: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8083: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8084: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8085: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8086: 	return "$num1:$num2";
1.366     albertel 8087:     }
                   8088: }
                   8089: 
1.575     albertel 8090: sub rndseed_CODE_64bit4 {
                   8091:     my ($symb,$courseid,$domain,$username)=@_;
                   8092:     {
                   8093: 	use integer;
                   8094: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8095: 	my $symbseed=numval3($symb);
                   8096: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8097: 	my $CODEseed=numval3(&getCODE());
                   8098: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8099: 	my $num1=$symbseed+$CODEchck;
                   8100: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8101: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8102: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8103: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8104: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8105: 	return "$num1:$num2";
                   8106:     }
                   8107: }
                   8108: 
1.675     albertel 8109: sub rndseed_CODE_64bit5 {
                   8110:     my ($symb,$courseid,$domain,$username)=@_;
                   8111:     my $code = &getCODE();
                   8112:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8113:     return "$num1:$num2";
                   8114: }
                   8115: 
1.366     albertel 8116: sub setup_random_from_rndseed {
                   8117:     my ($rndseed)=@_;
1.503     albertel 8118:     if ($rndseed =~/([,:])/) {
                   8119: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8120: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8121:     } else {
                   8122: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8123:     }
1.36      albertel 8124: }
                   8125: 
1.474     albertel 8126: sub latest_receipt_algorithm_id {
1.835     albertel 8127:     return 'receipt3';
1.474     albertel 8128: }
                   8129: 
1.480     www      8130: sub recunique {
                   8131:     my $fucourseid=shift;
                   8132:     my $unique;
1.835     albertel 8133:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8134: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8135: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8136:     } else {
                   8137: 	$unique=$perlvar{'lonReceipt'};
                   8138:     }
                   8139:     return unpack("%32C*",$unique);
                   8140: }
                   8141: 
                   8142: sub recprefix {
                   8143:     my $fucourseid=shift;
                   8144:     my $prefix;
1.835     albertel 8145:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8146: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8147: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8148:     } else {
                   8149: 	$prefix=$perlvar{'lonHostID'};
                   8150:     }
                   8151:     return unpack("%32C*",$prefix);
                   8152: }
                   8153: 
1.76      www      8154: sub ireceipt {
1.474     albertel 8155:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8156: 
                   8157:     my $return =&recprefix($fucourseid).'-';
                   8158: 
                   8159:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8160: 	$env{'request.state'} eq 'construct') {
                   8161: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8162: 	return $return;
                   8163:     }
                   8164: 
1.76      www      8165:     my $cuname=unpack("%32C*",$funame);
                   8166:     my $cudom=unpack("%32C*",$fudom);
                   8167:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8168:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8169:     my $cunique=&recunique($fucourseid);
1.474     albertel 8170:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8171:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8172: 
1.790     albertel 8173: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8174: 			       
                   8175: 	$return.= ($cunique%$cuname+
                   8176: 		   $cunique%$cudom+
                   8177: 		   $cusymb%$cuname+
                   8178: 		   $cusymb%$cudom+
                   8179: 		   $cucourseid%$cuname+
                   8180: 		   $cucourseid%$cudom+
                   8181: 		   $cpart%$cuname+
                   8182: 		   $cpart%$cudom);
                   8183:     } else {
                   8184: 	$return.= ($cunique%$cuname+
                   8185: 		   $cunique%$cudom+
                   8186: 		   $cusymb%$cuname+
                   8187: 		   $cusymb%$cudom+
                   8188: 		   $cucourseid%$cuname+
                   8189: 		   $cucourseid%$cudom);
                   8190:     }
                   8191:     return $return;
1.76      www      8192: }
                   8193: 
                   8194: sub receipt {
1.474     albertel 8195:     my ($part)=@_;
1.790     albertel 8196:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8197:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8198: }
1.260     ng       8199: 
1.790     albertel 8200: sub whichuser {
                   8201:     my ($passedsymb)=@_;
                   8202:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8203:     if (defined($env{'form.grade_symb'})) {
                   8204: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8205: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8206: 	if (!$allowed &&
                   8207: 	    exists($env{'request.course.sec'}) &&
                   8208: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8209: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8210: 			      '/'.$env{'request.course.sec'});
                   8211: 	}
                   8212: 	if ($allowed) {
                   8213: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8214: 	    $courseid=$tmp_courseid;
                   8215: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8216: 	    ($name)=&get_env_multiple('form.grade_username');
                   8217: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8218: 	}
                   8219:     }
                   8220:     if (!$passedsymb) {
                   8221: 	$symb=&symbread();
                   8222:     } else {
                   8223: 	$symb=$passedsymb;
                   8224:     }
                   8225:     $courseid=$env{'request.course.id'};
                   8226:     $domain=$env{'user.domain'};
                   8227:     $name=$env{'user.name'};
                   8228:     if ($name eq 'public' && $domain eq 'public') {
                   8229: 	if (!defined($env{'form.username'})) {
                   8230: 	    $env{'form.username'}.=time.rand(10000000);
                   8231: 	}
                   8232: 	$name.=$env{'form.username'};
                   8233:     }
                   8234:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8235: 
                   8236: }
                   8237: 
1.36      albertel 8238: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8239: # returns either the contents of the file or 
                   8240: # -1 if the file doesn't exist
1.481     raeburn  8241: #
                   8242: # if the target is a file that was uploaded via DOCS, 
                   8243: # a check will be made to see if a current copy exists on the local server,
                   8244: # if it does this will be served, otherwise a copy will be retrieved from
                   8245: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8246: # the local server.   
1.472     albertel 8247: 
1.36      albertel 8248: sub getfile {
1.538     albertel 8249:     my ($file) = @_;
1.609     banghart 8250:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8251:     &repcopy($file);
                   8252:     return &readfile($file);
                   8253: }
                   8254: 
                   8255: sub repcopy_userfile {
                   8256:     my ($file)=@_;
1.609     banghart 8257:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8258:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8259:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8260: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8261:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8262:     if (-e "$file") {
1.828     www      8263: # we already have a local copy, check it out
1.538     albertel 8264: 	my @fileinfo = stat($file);
1.828     www      8265: 	my $rtncode;
                   8266: 	my $info;
1.538     albertel 8267: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8268: 	if ($lwpresp ne 'ok') {
1.828     www      8269: # there is no such file anymore, even though we had a local copy
1.482     albertel 8270: 	    if ($rtncode eq '404') {
1.538     albertel 8271: 		unlink($file);
1.482     albertel 8272: 	    }
                   8273: 	    return -1;
                   8274: 	}
                   8275: 	if ($info < $fileinfo[9]) {
1.828     www      8276: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8277: 	    return 'ok';
1.828     www      8278: 	} else {
                   8279: # the file is outdated, get rid of it
                   8280: 	    unlink($file);
1.482     albertel 8281: 	}
1.828     www      8282:     }
                   8283: # one way or the other, at this point, we don't have the file
                   8284: # construct the correct path for the file
                   8285:     my @parts = ($cdom,$cnum); 
                   8286:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8287: 	push @parts, split(/\//,$1);
                   8288:     }
                   8289:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8290:     foreach my $part (@parts) {
                   8291: 	$path .= '/'.$part;
                   8292: 	if (!-e $path) {
                   8293: 	    mkdir($path,0770);
1.482     albertel 8294: 	}
                   8295:     }
1.828     www      8296: # now the path exists for sure
                   8297: # get a user agent
                   8298:     my $ua=new LWP::UserAgent;
                   8299:     my $transferfile=$file.'.in.transfer';
                   8300: # FIXME: this should flock
                   8301:     if (-e $transferfile) { return 'ok'; }
                   8302:     my $request;
                   8303:     $uri=~s/^\///;
1.976.2.3  raeburn  8304:     my $homeserver = &homeserver($cnum,$cdom);
                   8305:     my $protocol = $protocol{$homeserver};
                   8306:     $protocol = 'http' if ($protocol ne 'https');
                   8307:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8308:     my $response=$ua->request($request,$transferfile);
                   8309: # did it work?
                   8310:     if ($response->is_error()) {
                   8311: 	unlink($transferfile);
                   8312: 	&logthis("Userfile repcopy failed for $uri");
                   8313: 	return -1;
                   8314:     }
                   8315: # worked, rename the transfer file
                   8316:     rename($transferfile,$file);
1.607     raeburn  8317:     return 'ok';
1.481     raeburn  8318: }
                   8319: 
1.517     albertel 8320: sub tokenwrapper {
                   8321:     my $uri=shift;
1.976.2.3  raeburn  8322:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8323:     $uri=~s|^/||;
1.620     albertel 8324:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8325:     my $token=$1;
1.552     albertel 8326:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8327:     if ($udom && $uname && $file) {
                   8328: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8329:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.976.2.3  raeburn  8330:         my $homeserver = &homeserver($uname,$udom);
                   8331:         my $protocol = $protocol{$homeserver};
                   8332:         $protocol = 'http' if ($protocol ne 'https');
                   8333:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8334:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8335:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8336:     } else {
                   8337:         return '/adm/notfound.html';
                   8338:     }
                   8339: }
                   8340: 
1.828     www      8341: # call with reqtype HEAD: get last modification time
                   8342: # call with reqtype GET: get the file contents
                   8343: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8344: #
1.481     raeburn  8345: sub getuploaded {
                   8346:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8347:     $uri=~s/^\///;
1.976.2.3  raeburn  8348:     my $homeserver = &homeserver($cnum,$cdom);
                   8349:     my $protocol = $protocol{$homeserver};
                   8350:     $protocol = 'http' if ($protocol ne 'https');
                   8351:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8352:     my $ua=new LWP::UserAgent;
                   8353:     my $request=new HTTP::Request($reqtype,$uri);
                   8354:     my $response=$ua->request($request);
                   8355:     $$rtncode = $response->code;
1.482     albertel 8356:     if (! $response->is_success()) {
                   8357: 	return 'failed';
                   8358:     }      
                   8359:     if ($reqtype eq 'HEAD') {
1.486     www      8360: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8361:     } elsif ($reqtype eq 'GET') {
                   8362: 	$$info = $response->content;
1.472     albertel 8363:     }
1.482     albertel 8364:     return 'ok';
1.36      albertel 8365: }
                   8366: 
1.481     raeburn  8367: sub readfile {
                   8368:     my $file = shift;
                   8369:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8370:     my $fh;
                   8371:     open($fh,"<$file");
                   8372:     my $a='';
1.800     albertel 8373:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8374:     return $a;
                   8375: }
                   8376: 
1.36      albertel 8377: sub filelocation {
1.590     banghart 8378:     my ($dir,$file) = @_;
                   8379:     my $location;
                   8380:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8381: 
                   8382:     if ($file =~ m-^/adm/-) {
                   8383: 	$file=~s-^/adm/wrapper/-/-;
                   8384: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8385:     }
1.882     albertel 8386: 
1.590     banghart 8387:     if ($file=~m:^/~:) { # is a contruction space reference
                   8388:         $location = $file;
                   8389:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8390:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8391: 	# is a correct contruction space reference
                   8392:         $location = $file;
1.956     raeburn  8393:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8394:         $location = $file;
1.609     banghart 8395:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8396:         my ($udom,$uname,$filename)=
1.811     albertel 8397:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8398:         my $home=&homeserver($uname,$udom);
                   8399:         my $is_me=0;
                   8400:         my @ids=&current_machine_ids();
                   8401:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8402:         if ($is_me) {
1.955     raeburn  8403:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8404:         } else {
                   8405:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8406:   	      $udom.'/'.$uname.'/'.$filename;
                   8407:         }
1.882     albertel 8408:     } elsif ($file =~ m-^/adm/-) {
                   8409: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8410:     } else {
                   8411:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8412:         $file=~s:^/res/:/:;
                   8413:         if ( !( $file =~ m:^/:) ) {
                   8414:             $location = $dir. '/'.$file;
                   8415:         } else {
                   8416:             $location = '/home/httpd/html/res'.$file;
                   8417:         }
1.59      albertel 8418:     }
1.590     banghart 8419:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8420:     while ($location=~m{/\.\./}) {
                   8421: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8422: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8423: 	} else {
                   8424: 	    $location=~ s{/\.\./}{/}g;
                   8425: 	}
                   8426:     } #remove dir/..
1.590     banghart 8427:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8428:     return $location;
1.46      www      8429: }
1.36      albertel 8430: 
1.46      www      8431: sub hreflocation {
                   8432:     my ($dir,$file)=@_;
1.976.2.3  raeburn  8433:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8434: 	$file=filelocation($dir,$file);
1.700     albertel 8435:     } elsif ($file=~m-^/adm/-) {
                   8436: 	$file=~s-^/adm/wrapper/-/-;
                   8437: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8438:     }
                   8439:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8440: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8441:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8442: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8443:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8444: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8445: 	    -/uploaded/$1/$2/-x;
1.46      www      8446:     }
1.913     albertel 8447:     if ($file=~ m{^/userfiles/}) {
                   8448: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8449:     }
1.462     albertel 8450:     return $file;
1.465     albertel 8451: }
                   8452: 
                   8453: sub current_machine_domains {
1.853     albertel 8454:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8455: }
                   8456: 
                   8457: sub machine_domains {
                   8458:     my ($hostname) = @_;
1.465     albertel 8459:     my @domains;
1.838     albertel 8460:     my %hostname = &all_hostnames();
1.465     albertel 8461:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8462: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8463: 	if ($hostname eq $name) {
1.844     albertel 8464: 	    push(@domains,&host_domain($id));
1.465     albertel 8465: 	}
                   8466:     }
                   8467:     return @domains;
                   8468: }
                   8469: 
                   8470: sub current_machine_ids {
1.853     albertel 8471:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8472: }
                   8473: 
                   8474: sub machine_ids {
                   8475:     my ($hostname) = @_;
                   8476:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8477:     my @ids;
1.888     albertel 8478:     my %name_to_host = &all_names();
1.889     albertel 8479:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8480: 	return @{ $name_to_host{$hostname} };
                   8481:     }
                   8482:     return;
1.31      www      8483: }
                   8484: 
1.824     raeburn  8485: sub additional_machine_domains {
                   8486:     my @domains;
                   8487:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8488:     while( my $line = <$fh>) {
                   8489:         $line =~ s/\s//g;
                   8490:         push(@domains,$line);
                   8491:     }
                   8492:     return @domains;
                   8493: }
                   8494: 
                   8495: sub default_login_domain {
                   8496:     my $domain = $perlvar{'lonDefDomain'};
                   8497:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8498:     foreach my $posdom (&current_machine_domains(),
                   8499:                         &additional_machine_domains()) {
                   8500:         if (lc($posdom) eq lc($testdomain)) {
                   8501:             $domain=$posdom;
                   8502:             last;
                   8503:         }
                   8504:     }
                   8505:     return $domain;
                   8506: }
                   8507: 
1.31      www      8508: # ------------------------------------------------------------- Declutters URLs
                   8509: 
                   8510: sub declutter {
                   8511:     my $thisfn=shift;
1.569     albertel 8512:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8513:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8514:     $thisfn=~s/^\///;
1.697     albertel 8515:     $thisfn=~s|^adm/wrapper/||;
                   8516:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8517:     $thisfn=~s/^res\///;
1.235     www      8518:     $thisfn=~s/\?.+$//;
1.268     www      8519:     return $thisfn;
                   8520: }
                   8521: 
                   8522: # ------------------------------------------------------------- Clutter up URLs
                   8523: 
                   8524: sub clutter {
                   8525:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8526:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8527: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8528:        $thisfn='/res'.$thisfn; 
                   8529:     }
1.694     albertel 8530:     if ($thisfn !~m|/adm|) {
1.695     albertel 8531: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8532: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8533: 	} else {
                   8534: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8535: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8536: 	    if ($embstyle eq 'ssi'
                   8537: 		|| ($embstyle eq 'hdn')
                   8538: 		|| ($embstyle eq 'rat')
                   8539: 		|| ($embstyle eq 'prv')
                   8540: 		|| ($embstyle eq 'ign')) {
                   8541: 		#do nothing with these
                   8542: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8543: 		|| ($embstyle eq 'emb')
                   8544: 		|| ($embstyle eq 'wrp')) {
                   8545: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8546: 	    } elsif ($embstyle eq 'unk'
                   8547: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8548: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8549: 	    } else {
1.718     www      8550: #		&logthis("Got a blank emb style");
1.695     albertel 8551: 	    }
1.694     albertel 8552: 	}
                   8553:     }
1.31      www      8554:     return $thisfn;
1.12      www      8555: }
                   8556: 
1.787     albertel 8557: sub clutter_with_no_wrapper {
                   8558:     my $uri = &clutter(shift);
                   8559:     if ($uri =~ m-^/adm/-) {
                   8560: 	$uri =~ s-^/adm/wrapper/-/-;
                   8561: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8562:     }
                   8563:     return $uri;
                   8564: }
                   8565: 
1.557     albertel 8566: sub freeze_escape {
                   8567:     my ($value)=@_;
                   8568:     if (ref($value)) {
                   8569: 	$value=&nfreeze($value);
                   8570: 	return '__FROZEN__'.&escape($value);
                   8571:     }
                   8572:     return &escape($value);
                   8573: }
                   8574: 
1.11      www      8575: 
1.557     albertel 8576: sub thaw_unescape {
                   8577:     my ($value)=@_;
                   8578:     if ($value =~ /^__FROZEN__/) {
                   8579: 	substr($value,0,10,undef);
                   8580: 	$value=&unescape($value);
                   8581: 	return &thaw($value);
                   8582:     }
                   8583:     return &unescape($value);
                   8584: }
                   8585: 
1.436     albertel 8586: sub correct_line_ends {
                   8587:     my ($result)=@_;
                   8588:     $$result =~s/\r\n/\n/mg;
                   8589:     $$result =~s/\r/\n/mg;
1.415     albertel 8590: }
1.1       albertel 8591: # ================================================================ Main Program
                   8592: 
1.184     www      8593: sub goodbye {
1.204     albertel 8594:    &logthis("Starting Shut down");
1.443     albertel 8595: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8596:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8597: #converted
1.599     albertel 8598: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8599:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8600: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8601: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8602: #1.1 only
1.870     albertel 8603: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8604: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8605: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8606: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8607:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8608:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8609:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8610:    &flushcourselogs();
                   8611:    &logthis("Shutting down");
                   8612: }
                   8613: 
1.852     albertel 8614: sub get_dns {
1.869     albertel 8615:     my ($url,$func,$ignore_cache) = @_;
                   8616:     if (!$ignore_cache) {
                   8617: 	my ($content,$cached)=
                   8618: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8619: 	if ($cached) {
                   8620: 	    &$func($content);
                   8621: 	    return;
                   8622: 	}
                   8623:     }
                   8624: 
                   8625:     my %alldns;
1.852     albertel 8626:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8627:     foreach my $dns (<$config>) {
                   8628: 	next if ($dns !~ /^\^(\S*)/x);
1.976.2.2  raeburn  8629:         my $line = $1;
                   8630:         my ($host,$protocol) = split(/:/,$line);
                   8631:         if ($protocol ne 'https') {
                   8632:             $protocol = 'http';
                   8633:         }
                   8634: 	$alldns{$host} = $protocol;
1.869     albertel 8635:     }
                   8636:     while (%alldns) {
                   8637: 	my ($dns) = keys(%alldns);
1.852     albertel 8638: 	my $ua=new LWP::UserAgent;
1.976.2.2  raeburn  8639: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8640: 	my $response=$ua->request($request);
1.976.2.2  raeburn  8641:         delete($alldns{$dns});
1.852     albertel 8642: 	next if ($response->is_error());
                   8643: 	my @content = split("\n",$response->content);
1.869     albertel 8644: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8645: 	&$func(\@content);
1.869     albertel 8646: 	return;
1.852     albertel 8647:     }
                   8648:     close($config);
1.871     albertel 8649:     my $which = (split('/',$url))[3];
                   8650:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8651:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8652:     my @content = <$config>;
                   8653:     &$func(\@content);
                   8654:     return;
1.852     albertel 8655: }
1.327     albertel 8656: # ------------------------------------------------------------ Read domain file
                   8657: {
1.852     albertel 8658:     my $loaded;
1.846     albertel 8659:     my %domain;
                   8660: 
1.852     albertel 8661:     sub parse_domain_tab {
                   8662: 	my ($lines) = @_;
                   8663: 	foreach my $line (@$lines) {
                   8664: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8665: 
1.846     albertel 8666: 	    chomp($line);
1.852     albertel 8667: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8668: 	    my %this_domain;
                   8669: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8670: 			       'lang_def', 'city', 'longi', 'lati',
                   8671: 			       'primary') {
                   8672: 		$this_domain{$field} = shift(@elements);
                   8673: 	    }
                   8674: 	    $domain{$name} = \%this_domain;
1.852     albertel 8675: 	}
                   8676:     }
1.864     albertel 8677: 
                   8678:     sub reset_domain_info {
                   8679: 	undef($loaded);
                   8680: 	undef(%domain);
                   8681:     }
                   8682: 
1.852     albertel 8683:     sub load_domain_tab {
1.869     albertel 8684: 	my ($ignore_cache) = @_;
                   8685: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8686: 	my $fh;
                   8687: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8688: 	    my @lines = <$fh>;
                   8689: 	    &parse_domain_tab(\@lines);
1.448     albertel 8690: 	}
1.852     albertel 8691: 	close($fh);
                   8692: 	$loaded = 1;
1.327     albertel 8693:     }
1.846     albertel 8694: 
                   8695:     sub domain {
1.852     albertel 8696: 	&load_domain_tab() if (!$loaded);
                   8697: 
1.846     albertel 8698: 	my ($name,$what) = @_;
                   8699: 	return if ( !exists($domain{$name}) );
                   8700: 
                   8701: 	if (!$what) {
                   8702: 	    return $domain{$name}{'description'};
                   8703: 	}
                   8704: 	return $domain{$name}{$what};
                   8705:     }
1.974     raeburn  8706: 
                   8707:     sub domain_info {
                   8708:         &load_domain_tab() if (!$loaded);
                   8709:         return %domain;
                   8710:     }
                   8711: 
1.327     albertel 8712: }
                   8713: 
                   8714: 
1.1       albertel 8715: # ------------------------------------------------------------- Read hosts file
                   8716: {
1.838     albertel 8717:     my %hostname;
1.844     albertel 8718:     my %hostdom;
1.845     albertel 8719:     my %libserv;
1.852     albertel 8720:     my $loaded;
1.888     albertel 8721:     my %name_to_host;
1.852     albertel 8722: 
                   8723:     sub parse_hosts_tab {
                   8724: 	my ($file) = @_;
                   8725: 	foreach my $configline (@$file) {
                   8726: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8727: 	    next if ($configline =~ /^\^/);
                   8728: 	    chomp($configline);
1.968     raeburn  8729: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8730: 	    $name=~s/\s//g;
                   8731: 	    if ($id && $domain && $role && $name) {
                   8732: 		$hostname{$id}=$name;
1.888     albertel 8733: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8734: 		$hostdom{$id}=$domain;
                   8735: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8736:                 if (defined($protocol)) {
                   8737:                     if ($protocol eq 'https') {
                   8738:                         $protocol{$id} = $protocol;
                   8739:                     } else {
                   8740:                         $protocol{$id} = 'http'; 
                   8741:                     }
1.968     raeburn  8742:                 } else {
1.969     raeburn  8743:                     $protocol{$id} = 'http';
1.968     raeburn  8744:                 }
1.852     albertel 8745: 	    }
                   8746: 	}
                   8747:     }
1.864     albertel 8748:     
                   8749:     sub reset_hosts_info {
1.897     albertel 8750: 	&purge_remembered();
1.864     albertel 8751: 	&reset_domain_info();
                   8752: 	&reset_hosts_ip_info();
1.892     albertel 8753: 	undef(%name_to_host);
1.864     albertel 8754: 	undef(%hostname);
                   8755: 	undef(%hostdom);
                   8756: 	undef(%libserv);
                   8757: 	undef($loaded);
                   8758:     }
1.1       albertel 8759: 
1.852     albertel 8760:     sub load_hosts_tab {
1.869     albertel 8761: 	my ($ignore_cache) = @_;
                   8762: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8763: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8764: 	my @config = <$config>;
                   8765: 	&parse_hosts_tab(\@config);
                   8766: 	close($config);
                   8767: 	$loaded=1;
1.1       albertel 8768:     }
1.852     albertel 8769: 
1.838     albertel 8770:     sub hostname {
1.852     albertel 8771: 	&load_hosts_tab() if (!$loaded);
                   8772: 
1.838     albertel 8773: 	my ($lonid) = @_;
                   8774: 	return $hostname{$lonid};
                   8775:     }
1.845     albertel 8776: 
1.838     albertel 8777:     sub all_hostnames {
1.852     albertel 8778: 	&load_hosts_tab() if (!$loaded);
                   8779: 
1.838     albertel 8780: 	return %hostname;
                   8781:     }
1.845     albertel 8782: 
1.888     albertel 8783:     sub all_names {
                   8784: 	&load_hosts_tab() if (!$loaded);
                   8785: 
                   8786: 	return %name_to_host;
                   8787:     }
                   8788: 
1.974     raeburn  8789:     sub all_host_domain {
                   8790:         &load_hosts_tab() if (!$loaded);
                   8791:         return %hostdom;
                   8792:     }
                   8793: 
1.845     albertel 8794:     sub is_library {
1.852     albertel 8795: 	&load_hosts_tab() if (!$loaded);
                   8796: 
1.845     albertel 8797: 	return exists($libserv{$_[0]});
                   8798:     }
                   8799: 
                   8800:     sub all_library {
1.852     albertel 8801: 	&load_hosts_tab() if (!$loaded);
                   8802: 
1.845     albertel 8803: 	return %libserv;
                   8804:     }
                   8805: 
1.841     albertel 8806:     sub get_servers {
1.852     albertel 8807: 	&load_hosts_tab() if (!$loaded);
                   8808: 
1.841     albertel 8809: 	my ($domain,$type) = @_;
                   8810: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8811: 	                                          : %hostname;
                   8812: 	my %result;
1.842     albertel 8813: 	if (ref($domain) eq 'ARRAY') {
                   8814: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8815: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8816: 		    $result{$host} = $hostname;
                   8817: 		}
                   8818: 	    }
                   8819: 	} else {
                   8820: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8821: 		if ($hostdom{$host} eq $domain) {
                   8822: 		    $result{$host} = $hostname;
                   8823: 		}
1.841     albertel 8824: 	    }
                   8825: 	}
                   8826: 	return %result;
                   8827:     }
1.845     albertel 8828: 
1.844     albertel 8829:     sub host_domain {
1.852     albertel 8830: 	&load_hosts_tab() if (!$loaded);
                   8831: 
1.844     albertel 8832: 	my ($lonid) = @_;
                   8833: 	return $hostdom{$lonid};
                   8834:     }
                   8835: 
1.841     albertel 8836:     sub all_domains {
1.852     albertel 8837: 	&load_hosts_tab() if (!$loaded);
                   8838: 
1.841     albertel 8839: 	my %seen;
                   8840: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8841: 	return @uniq;
                   8842:     }
1.1       albertel 8843: }
                   8844: 
1.847     albertel 8845: { 
                   8846:     my %iphost;
1.856     albertel 8847:     my %name_to_ip;
                   8848:     my %lonid_to_ip;
1.869     albertel 8849: 
1.847     albertel 8850:     sub get_hosts_from_ip {
                   8851: 	my ($ip) = @_;
                   8852: 	my %iphosts = &get_iphost();
                   8853: 	if (ref($iphosts{$ip})) {
                   8854: 	    return @{$iphosts{$ip}};
                   8855: 	}
                   8856: 	return;
1.839     albertel 8857:     }
1.864     albertel 8858:     
                   8859:     sub reset_hosts_ip_info {
                   8860: 	undef(%iphost);
                   8861: 	undef(%name_to_ip);
                   8862: 	undef(%lonid_to_ip);
                   8863:     }
1.856     albertel 8864: 
                   8865:     sub get_host_ip {
                   8866: 	my ($lonid) = @_;
                   8867: 	if (exists($lonid_to_ip{$lonid})) {
                   8868: 	    return $lonid_to_ip{$lonid};
                   8869: 	}
                   8870: 	my $name=&hostname($lonid);
                   8871:    	my $ip = gethostbyname($name);
                   8872: 	return if (!$ip || length($ip) ne 4);
                   8873: 	$ip=inet_ntoa($ip);
                   8874: 	$name_to_ip{$name}   = $ip;
                   8875: 	$lonid_to_ip{$lonid} = $ip;
                   8876: 	return $ip;
                   8877:     }
1.847     albertel 8878:     
                   8879:     sub get_iphost {
1.869     albertel 8880: 	my ($ignore_cache) = @_;
1.894     albertel 8881: 
1.869     albertel 8882: 	if (!$ignore_cache) {
                   8883: 	    if (%iphost) {
                   8884: 		return %iphost;
                   8885: 	    }
                   8886: 	    my ($ip_info,$cached)=
                   8887: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8888: 	    if ($cached) {
                   8889: 		%iphost      = %{$ip_info->[0]};
                   8890: 		%name_to_ip  = %{$ip_info->[1]};
                   8891: 		%lonid_to_ip = %{$ip_info->[2]};
                   8892: 		return %iphost;
                   8893: 	    }
                   8894: 	}
1.894     albertel 8895: 
                   8896: 	# get yesterday's info for fallback
                   8897: 	my %old_name_to_ip;
                   8898: 	my ($ip_info,$cached)=
                   8899: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8900: 	if ($cached) {
                   8901: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8902: 	}
                   8903: 
1.888     albertel 8904: 	my %name_to_host = &all_names();
                   8905: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8906: 	    my $ip;
                   8907: 	    if (!exists($name_to_ip{$name})) {
                   8908: 		$ip = gethostbyname($name);
                   8909: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8910: 		    if (defined($old_name_to_ip{$name})) {
                   8911: 			$ip = $old_name_to_ip{$name};
                   8912: 			&logthis("Can't find $name defaulting to old $ip");
                   8913: 		    } else {
                   8914: 			&logthis("Name $name no IP found");
                   8915: 			next;
                   8916: 		    }
                   8917: 		} else {
                   8918: 		    $ip=inet_ntoa($ip);
1.847     albertel 8919: 		}
                   8920: 		$name_to_ip{$name} = $ip;
                   8921: 	    } else {
                   8922: 		$ip = $name_to_ip{$name};
1.653     albertel 8923: 	    }
1.888     albertel 8924: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8925: 		$lonid_to_ip{$id} = $ip;
                   8926: 	    }
                   8927: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8928: 	}
1.869     albertel 8929: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8930: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8931: 				      48*60*60);
1.869     albertel 8932: 
1.847     albertel 8933: 	return %iphost;
1.598     albertel 8934:     }
                   8935: }
                   8936: 
1.862     albertel 8937: BEGIN {
                   8938: 
                   8939: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8940:     unless ($readit) {
                   8941: {
                   8942:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8943:     %perlvar = (%perlvar,%{$configvars});
                   8944: }
                   8945: 
                   8946: 
1.1       albertel 8947: # ------------------------------------------------------ Read spare server file
                   8948: {
1.448     albertel 8949:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8950: 
                   8951:     while (my $configline=<$config>) {
                   8952:        chomp($configline);
1.284     matthew  8953:        if ($configline) {
1.784     albertel 8954: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8955: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8956: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8957:        }
                   8958:     }
1.448     albertel 8959:     close($config);
1.1       albertel 8960: }
1.11      www      8961: # ------------------------------------------------------------ Read permissions
                   8962: {
1.448     albertel 8963:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8964: 
                   8965:     while (my $configline=<$config>) {
1.448     albertel 8966: 	chomp($configline);
                   8967: 	if ($configline) {
                   8968: 	    my ($role,$perm)=split(/ /,$configline);
                   8969: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8970: 	}
1.11      www      8971:     }
1.448     albertel 8972:     close($config);
1.11      www      8973: }
                   8974: 
                   8975: # -------------------------------------------- Read plain texts for permissions
                   8976: {
1.448     albertel 8977:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8978: 
                   8979:     while (my $configline=<$config>) {
1.448     albertel 8980: 	chomp($configline);
                   8981: 	if ($configline) {
1.742     raeburn  8982: 	    my ($short,@plain)=split(/:/,$configline);
                   8983:             %{$prp{$short}} = ();
                   8984: 	    if (@plain > 0) {
                   8985:                 $prp{$short}{'std'} = $plain[0];
                   8986:                 for (my $i=1; $i<@plain; $i++) {
                   8987:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8988:                 }
                   8989:             }
1.448     albertel 8990: 	}
1.135     www      8991:     }
1.448     albertel 8992:     close($config);
1.135     www      8993: }
                   8994: 
                   8995: # ---------------------------------------------------------- Read package table
                   8996: {
1.448     albertel 8997:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8998: 
                   8999:     while (my $configline=<$config>) {
1.483     albertel 9000: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9001: 	chomp($configline);
                   9002: 	my ($short,$plain)=split(/:/,$configline);
                   9003: 	my ($pack,$name)=split(/\&/,$short);
                   9004: 	if ($plain ne '') {
                   9005: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9006: 	    $packagetab{$short}=$plain; 
                   9007: 	}
1.11      www      9008:     }
1.448     albertel 9009:     close($config);
1.329     matthew  9010: }
                   9011: 
                   9012: # ------------- set up temporary directory
                   9013: {
                   9014:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9015: 
1.11      www      9016: }
                   9017: 
1.794     albertel 9018: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9019: 				'compress_threshold'=> 20_000,
                   9020:  			        });
1.185     www      9021: 
1.281     www      9022: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9023: $dumpcount=0;
1.958     www      9024: $locknum=0;
1.22      www      9025: 
1.163     harris41 9026: &logtouch();
1.672     albertel 9027: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9028: $readit=1;
1.564     albertel 9029:     {
                   9030: 	use integer;
                   9031: 	my $test=(2**32)+1;
1.568     albertel 9032: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9033: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9034:     }
1.195     www      9035: }
1.1       albertel 9036: }
1.179     www      9037: 
1.1       albertel 9038: 1;
1.191     harris41 9039: __END__
                   9040: 
1.243     albertel 9041: =pod
                   9042: 
1.191     harris41 9043: =head1 NAME
                   9044: 
1.243     albertel 9045: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9046: 
                   9047: =head1 SYNOPSIS
                   9048: 
1.243     albertel 9049: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9050: 
                   9051:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9052: 
1.243     albertel 9053: Common parameters:
                   9054: 
                   9055: =over 4
                   9056: 
                   9057: =item *
                   9058: 
                   9059: $uname : an internal username (if $cname expecting a course Id specifically)
                   9060: 
                   9061: =item *
                   9062: 
                   9063: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9064: 
                   9065: =item *
                   9066: 
                   9067: $symb : a resource instance identifier
                   9068: 
                   9069: =item *
                   9070: 
                   9071: $namespace : the name of a .db file that contains the data needed or
                   9072: being set.
                   9073: 
                   9074: =back
                   9075: 
1.394     bowersj2 9076: =head1 OVERVIEW
1.191     harris41 9077: 
1.394     bowersj2 9078: lonnet provides subroutines which interact with the
                   9079: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9080: about classes, users, and resources.
1.243     albertel 9081: 
                   9082: For many of these objects you can also use this to store data about
                   9083: them or modify them in various ways.
1.191     harris41 9084: 
1.394     bowersj2 9085: =head2 Symbs
1.191     harris41 9086: 
1.394     bowersj2 9087: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9088: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9089: map, the resource number of the resource in the map, and the URL of
                   9090: the resource itself. The latter is somewhat redundant, but might help
                   9091: if maps change.
                   9092: 
                   9093: An example is
                   9094: 
                   9095:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9096: 
                   9097: The respective map entry is
                   9098: 
                   9099:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9100:   title="Problem 2">
                   9101:  </resource>
                   9102: 
                   9103: Symbs are used by the random number generator, as well as to store and
                   9104: restore data specific to a certain instance of for example a problem.
                   9105: 
                   9106: =head2 Storing And Retrieving Data
                   9107: 
                   9108: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9109: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9110: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9111: is is the non-critical message twin of cstore. These functions are for
                   9112: handlers to store a perl hash to a user's permanent data space in an
                   9113: easy manner, and to retrieve it again on another call. It is expected
                   9114: that a handler would use this once at the beginning to retrieve data,
                   9115: and then again once at the end to send only the new data back.
                   9116: 
                   9117: The data is stored in the user's data directory on the user's
                   9118: homeserver under the ID of the course.
                   9119: 
                   9120: The hash that is returned by restore will have all of the previous
                   9121: value for all of the elements of the hash.
                   9122: 
                   9123: Example:
                   9124: 
                   9125:  #creating a hash
                   9126:  my %hash;
                   9127:  $hash{'foo'}='bar';
                   9128: 
                   9129:  #storing it
                   9130:  &Apache::lonnet::cstore(\%hash);
                   9131: 
                   9132:  #changing a value
                   9133:  $hash{'foo'}='notbar';
                   9134: 
                   9135:  #adding a new value
                   9136:  $hash{'bar'}='foo';
                   9137:  &Apache::lonnet::cstore(\%hash);
                   9138: 
                   9139:  #retrieving the hash
                   9140:  my %history=&Apache::lonnet::restore();
                   9141: 
                   9142:  #print the hash
                   9143:  foreach my $key (sort(keys(%history))) {
                   9144:    print("\%history{$key} = $history{$key}");
                   9145:  }
                   9146: 
                   9147: Will print out:
1.191     harris41 9148: 
1.394     bowersj2 9149:  %history{1:foo} = bar
                   9150:  %history{1:keys} = foo:timestamp
                   9151:  %history{1:timestamp} = 990455579
                   9152:  %history{2:bar} = foo
                   9153:  %history{2:foo} = notbar
                   9154:  %history{2:keys} = foo:bar:timestamp
                   9155:  %history{2:timestamp} = 990455580
                   9156:  %history{bar} = foo
                   9157:  %history{foo} = notbar
                   9158:  %history{timestamp} = 990455580
                   9159:  %history{version} = 2
                   9160: 
                   9161: Note that the special hash entries C<keys>, C<version> and
                   9162: C<timestamp> were added to the hash. C<version> will be equal to the
                   9163: total number of versions of the data that have been stored. The
                   9164: C<timestamp> attribute will be the UNIX time the hash was
                   9165: stored. C<keys> is available in every historical section to list which
                   9166: keys were added or changed at a specific historical revision of a
                   9167: hash.
                   9168: 
                   9169: B<Warning>: do not store the hash that restore returns directly. This
                   9170: will cause a mess since it will restore the historical keys as if the
                   9171: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9172: 
1.394     bowersj2 9173: Calling convention:
1.191     harris41 9174: 
1.394     bowersj2 9175:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9176:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9177: 
1.394     bowersj2 9178: For more detailed information, see lonnet specific documentation.
1.191     harris41 9179: 
1.394     bowersj2 9180: =head1 RETURN MESSAGES
1.191     harris41 9181: 
1.394     bowersj2 9182: =over 4
1.191     harris41 9183: 
1.394     bowersj2 9184: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9185: 
1.394     bowersj2 9186: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9187: when the connection is brought back up
1.191     harris41 9188: 
1.394     bowersj2 9189: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9190: for later delivery
1.191     harris41 9191: 
1.967     bisitz   9192: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9193: 
1.394     bowersj2 9194: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9195: that was requested
1.191     harris41 9196: 
1.243     albertel 9197: =back
1.191     harris41 9198: 
1.243     albertel 9199: =head1 PUBLIC SUBROUTINES
1.191     harris41 9200: 
1.243     albertel 9201: =head2 Session Environment Functions
1.191     harris41 9202: 
1.243     albertel 9203: =over 4
1.191     harris41 9204: 
1.394     bowersj2 9205: =item * 
                   9206: X<appenv()>
1.949     raeburn  9207: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9208: the user envirnoment file, and will be restored for each access this
1.620     albertel 9209: user makes during this session, also modifies the %env for the current
1.949     raeburn  9210: process. Optional rolesarrayref - if defined contains a reference to an array
                   9211: of roles which are exempt from the restriction on modifying user.role entries 
                   9212: in the user's environment.db and in %env.    
1.191     harris41 9213: 
                   9214: =item *
1.394     bowersj2 9215: X<delenv()>
                   9216: B<delenv($regexp)>: removes all items from the session
                   9217: environment file that matches the regular expression in $regexp. The
1.620     albertel 9218: values are also delted from the current processes %env.
1.191     harris41 9219: 
1.795     albertel 9220: =item * get_env_multiple($name) 
                   9221: 
                   9222: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9223: values may be defined and end up as an array ref.
                   9224: 
                   9225: returns an array of values
                   9226: 
1.243     albertel 9227: =back
                   9228: 
                   9229: =head2 User Information
1.191     harris41 9230: 
1.243     albertel 9231: =over 4
1.191     harris41 9232: 
                   9233: =item *
1.394     bowersj2 9234: X<queryauthenticate()>
                   9235: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9236: authentication scheme
                   9237: 
                   9238: =item *
1.394     bowersj2 9239: X<authenticate()>
                   9240: B<authenticate($uname,$upass,$udom)>: try to
                   9241: authenticate user from domain's lib servers (first use the current
                   9242: one). C<$upass> should be the users password.
1.191     harris41 9243: 
                   9244: =item *
1.394     bowersj2 9245: X<homeserver()>
                   9246: B<homeserver($uname,$udom)>: find the server which has
                   9247: the user's directory and files (there must be only one), this caches
                   9248: the answer, and also caches if there is a borken connection.
1.191     harris41 9249: 
                   9250: =item *
1.394     bowersj2 9251: X<idget()>
                   9252: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9253: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9254: username, and only 1 username per ID in a specific domain) (returns
                   9255: hash: id=>name,id=>name)
1.191     harris41 9256: 
                   9257: =item *
1.394     bowersj2 9258: X<idrget()>
                   9259: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9260: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9261: 
                   9262: =item *
1.394     bowersj2 9263: X<idput()>
                   9264: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9265: 
                   9266: =item *
1.394     bowersj2 9267: X<rolesinit()>
                   9268: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9269: 
                   9270: =item *
1.551     albertel 9271: X<getsection()>
                   9272: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9273: course $cname, return section name/number or '' for "not in course"
                   9274: and '-1' for "no section"
                   9275: 
                   9276: =item *
1.394     bowersj2 9277: X<userenvironment()>
                   9278: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9279: passed in @what from the requested user's environment, returns a hash
                   9280: 
1.858     raeburn  9281: =item * 
                   9282: X<userlog_query()>
1.859     albertel 9283: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9284: activity.log file. %filters defines filters applied when parsing the
                   9285: log file. These can be start or end timestamps, or the type of action
                   9286: - log to look for Login or Logout events, check for Checkin or
                   9287: Checkout, role for role selection. The response is in the form
                   9288: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9289: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9290: 
1.243     albertel 9291: =back
                   9292: 
                   9293: =head2 User Roles
                   9294: 
                   9295: =over 4
                   9296: 
                   9297: =item *
                   9298: 
1.810     raeburn  9299: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9300:  F: full access
                   9301:  U,I,K: authentication modes (cxx only)
                   9302:  '': forbidden
                   9303:  1: user needs to choose course
                   9304:  2: browse allowed
1.766     albertel 9305:  A: passphrase authentication needed
1.243     albertel 9306: 
                   9307: =item *
                   9308: 
                   9309: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9310: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9311: and course level
                   9312: 
                   9313: =item *
                   9314: 
                   9315: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9316: explanation of a user role term
                   9317: 
1.832     raeburn  9318: =item *
                   9319: 
1.935     raeburn  9320: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9321: All arguments are optional. Returns a hash of a roles, either for
                   9322: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9323: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9324: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9325: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9326: For each key, value is set to colon-separated start and end times for
                   9327: the role.  If no username and domain are specified, will default to
1.934     raeburn  9328: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9329: of role statuses (active, future or previous), roles 
                   9330: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9331: to restrict the list of roles reported. If no array ref is 
                   9332: provided for types, will default to return only active roles.
1.834     albertel 9333: 
1.243     albertel 9334: =back
                   9335: 
                   9336: =head2 User Modification
                   9337: 
                   9338: =over 4
                   9339: 
                   9340: =item *
                   9341: 
1.957     raeburn  9342: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9343: user for the level given by URL.  Optional start and end dates (leave empty
                   9344: string or zero for "no date")
1.191     harris41 9345: 
                   9346: =item *
                   9347: 
1.243     albertel 9348: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9349: change a users, password, possible return values are: ok,
                   9350: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9351: refused
1.191     harris41 9352: 
                   9353: =item *
                   9354: 
1.243     albertel 9355: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9356: 
                   9357: =item *
                   9358: 
1.963     raeburn  9359: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9360:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9361: modify user
1.191     harris41 9362: 
                   9363: =item *
                   9364: 
1.286     matthew  9365: modifystudent
                   9366: 
1.957     raeburn  9367: modify a student's enrollment and identification information.
1.286     matthew  9368: The course id is resolved based on the current users environment.  
                   9369: This means the envoking user must be a course coordinator or otherwise
                   9370: associated with a course.
                   9371: 
1.297     matthew  9372: This call is essentially a wrapper for lonnet::modifyuser and
                   9373: lonnet::modify_student_enrollment
1.286     matthew  9374: 
                   9375: Inputs: 
                   9376: 
                   9377: =over 4
                   9378: 
1.957     raeburn  9379: =item B<$udom> Student's loncapa domain
1.286     matthew  9380: 
1.957     raeburn  9381: =item B<$uname> Student's loncapa login name
1.286     matthew  9382: 
1.964     bisitz   9383: =item B<$uid> Student/Employee ID
1.286     matthew  9384: 
1.957     raeburn  9385: =item B<$umode> Student's authentication mode
1.286     matthew  9386: 
1.957     raeburn  9387: =item B<$upass> Student's password
1.286     matthew  9388: 
1.957     raeburn  9389: =item B<$first> Student's first name
1.286     matthew  9390: 
1.957     raeburn  9391: =item B<$middle> Student's middle name
1.286     matthew  9392: 
1.957     raeburn  9393: =item B<$last> Student's last name
1.286     matthew  9394: 
1.957     raeburn  9395: =item B<$gene> Student's generation
1.286     matthew  9396: 
1.957     raeburn  9397: =item B<$usec> Student's section in course
1.286     matthew  9398: 
                   9399: =item B<$end> Unix time of the roles expiration
                   9400: 
                   9401: =item B<$start> Unix time of the roles start date
                   9402: 
                   9403: =item B<$forceid> If defined, allow $uid to be changed
                   9404: 
                   9405: =item B<$desiredhome> server to use as home server for student
                   9406: 
1.957     raeburn  9407: =item B<$email> Student's permanent e-mail address
                   9408: 
                   9409: =item B<$type> Type of enrollment (auto or manual)
                   9410: 
1.963     raeburn  9411: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9412: 
                   9413: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9414: 
1.963     raeburn  9415: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9416: 
1.963     raeburn  9417: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9418: 
1.963     raeburn  9419: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9420: 
1.286     matthew  9421: =back
1.297     matthew  9422: 
                   9423: =item *
                   9424: 
                   9425: modify_student_enrollment
                   9426: 
                   9427: Change a students enrollment status in a class.  The environment variable
                   9428: 'role.request.course' must be defined for this function to proceed.
                   9429: 
                   9430: Inputs:
                   9431: 
                   9432: =over 4
                   9433: 
                   9434: =item $udom, students domain
                   9435: 
                   9436: =item $uname, students name
                   9437: 
                   9438: =item $uid, students user id
                   9439: 
                   9440: =item $first, students first name
                   9441: 
                   9442: =item $middle
                   9443: 
                   9444: =item $last
                   9445: 
                   9446: =item $gene
                   9447: 
                   9448: =item $usec
                   9449: 
                   9450: =item $end
                   9451: 
                   9452: =item $start
                   9453: 
1.957     raeburn  9454: =item $type
                   9455: 
                   9456: =item $locktype
                   9457: 
                   9458: =item $cid
                   9459: 
                   9460: =item $selfenroll
                   9461: 
                   9462: =item $context
                   9463: 
1.297     matthew  9464: =back
                   9465: 
1.191     harris41 9466: 
                   9467: =item *
                   9468: 
1.243     albertel 9469: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9470: custom role; give a custom role to a user for the level given by URL.  Specify
                   9471: name and domain of role author, and role name
1.191     harris41 9472: 
                   9473: =item *
                   9474: 
1.243     albertel 9475: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9476: 
                   9477: =item *
                   9478: 
1.243     albertel 9479: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9480: 
                   9481: =back
                   9482: 
                   9483: =head2 Course Infomation
                   9484: 
                   9485: =over 4
1.191     harris41 9486: 
                   9487: =item *
                   9488: 
1.631     albertel 9489: coursedescription($courseid) : returns a hash of information about the
                   9490: specified course id, including all environment settings for the
                   9491: course, the description of the course will be in the hash under the
                   9492: key 'description'
1.191     harris41 9493: 
                   9494: =item *
                   9495: 
1.624     albertel 9496: resdata($name,$domain,$type,@which) : request for current parameter
                   9497: setting for a specific $type, where $type is either 'course' or 'user',
                   9498: @what should be a list of parameters to ask about. This routine caches
                   9499: answers for 5 minutes.
1.243     albertel 9500: 
1.877     foxr     9501: =item *
                   9502: 
                   9503: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9504: data base, returning a hash that is keyed by the resource name and has
                   9505: values that are the resource value.  I believe that the timestamps and
                   9506: versions are also returned.
                   9507: 
                   9508: 
1.243     albertel 9509: =back
                   9510: 
                   9511: =head2 Course Modification
                   9512: 
                   9513: =over 4
1.191     harris41 9514: 
                   9515: =item *
                   9516: 
1.243     albertel 9517: writecoursepref($courseid,%prefs) : write preferences (environment
                   9518: database) for a course
1.191     harris41 9519: 
                   9520: =item *
                   9521: 
1.243     albertel 9522: createcourse($udom,$description,$url) : make/modify course
                   9523: 
                   9524: =back
                   9525: 
                   9526: =head2 Resource Subroutines
                   9527: 
                   9528: =over 4
1.191     harris41 9529: 
                   9530: =item *
                   9531: 
1.243     albertel 9532: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9533: 
                   9534: =item *
                   9535: 
1.243     albertel 9536: repcopy($filename) : subscribes to the requested file, and attempts to
                   9537: replicate from the owning library server, Might return
1.607     raeburn  9538: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9539: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9540: resource. Expects the local filesystem pathname
                   9541: (/home/httpd/html/res/....)
                   9542: 
                   9543: =back
                   9544: 
                   9545: =head2 Resource Information
                   9546: 
                   9547: =over 4
1.191     harris41 9548: 
                   9549: =item *
                   9550: 
1.243     albertel 9551: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9552: a vairety of different possible values, $varname should be a request
                   9553: string, and the other parameters can be used to specify who and what
                   9554: one is asking about.
                   9555: 
                   9556: Possible values for $varname are environment.lastname (or other item
                   9557: from the envirnment hash), user.name (or someother aspect about the
                   9558: user), resource.0.maxtries (or some other part and parameter of a
                   9559: resource)
1.204     albertel 9560: 
                   9561: =item *
                   9562: 
1.243     albertel 9563: directcondval($number) : get current value of a condition; reads from a state
                   9564: string
1.204     albertel 9565: 
                   9566: =item *
                   9567: 
1.243     albertel 9568: condval($condidx) : value of condition index based on state
1.204     albertel 9569: 
                   9570: =item *
                   9571: 
1.243     albertel 9572: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9573: resource's metadata, $what should be either a specific key, or either
                   9574: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9575: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9576: 
                   9577: this function automatically caches all requests
1.191     harris41 9578: 
                   9579: =item *
                   9580: 
1.243     albertel 9581: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9582: network of library servers; returns file handle of where SQL and regex results
                   9583: will be stored for query
1.191     harris41 9584: 
                   9585: =item *
                   9586: 
1.243     albertel 9587: symbread($filename) : return symbolic list entry (filename argument optional);
                   9588: returns the data handle
1.191     harris41 9589: 
                   9590: =item *
                   9591: 
1.243     albertel 9592: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9593: a possible symb for the URL in $thisfn, and if is an encryypted
                   9594: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9595: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9596: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9597: 
1.191     harris41 9598: 
                   9599: =item *
                   9600: 
1.243     albertel 9601: symbclean($symb) : removes versions numbers from a symb, returns the
                   9602: cleaned symb
1.191     harris41 9603: 
                   9604: =item *
                   9605: 
1.243     albertel 9606: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9607: course map, user must be in a course for it to work.
1.191     harris41 9608: 
                   9609: =item *
                   9610: 
1.243     albertel 9611: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9612: 
                   9613: =item *
                   9614: 
1.243     albertel 9615: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9616: a random seed, all arguments are optional, if they aren't sent it uses the
                   9617: environment to derive them. Note: if symb isn't sent and it can't get one
                   9618: from &symbread it will use the current time as its return value
1.191     harris41 9619: 
                   9620: =item *
                   9621: 
1.243     albertel 9622: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9623: unfakeable, receipt
1.191     harris41 9624: 
                   9625: =item *
                   9626: 
1.620     albertel 9627: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9628: 
                   9629: =item *
                   9630: 
1.243     albertel 9631: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9632: 
                   9633: =item *
                   9634: 
1.243     albertel 9635: 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 9636: 
                   9637: =item *
                   9638: 
1.243     albertel 9639: 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 9640: 
                   9641: =item *
                   9642: 
1.243     albertel 9643: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9644: 
                   9645: =item *
                   9646: 
1.243     albertel 9647: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9648: forcing spreadsheet to reevaluate the resource scores next time.
                   9649: 
                   9650: =back
                   9651: 
                   9652: =head2 Storing/Retreiving Data
                   9653: 
                   9654: =over 4
1.191     harris41 9655: 
                   9656: =item *
                   9657: 
1.243     albertel 9658: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9659: for this url; hashref needs to be given and should be a \%hashname; the
                   9660: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9661: be derived from the env
1.191     harris41 9662: 
                   9663: =item *
                   9664: 
1.243     albertel 9665: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9666: uses critical subroutine
1.191     harris41 9667: 
                   9668: =item *
                   9669: 
1.243     albertel 9670: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9671: all args are optional
1.191     harris41 9672: 
                   9673: =item *
                   9674: 
1.717     albertel 9675: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9676: dumps the complete (or key matching regexp) namespace into a hash
                   9677: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9678: normally &store()ed into
                   9679: 
                   9680: $range should be either an integer '100' (give me the first 100
                   9681:                                            matching records)
                   9682:               or be  two integers sperated by a - with no spaces
                   9683:                  '30-50' (give me the 30th through the 50th matching
                   9684:                           records)
                   9685: 
                   9686: 
                   9687: =item *
                   9688: 
                   9689: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9690: replaces a &store() version of data with a replacement set of data
                   9691: for a particular resource in a namespace passed in the $storehash hash 
                   9692: reference
                   9693: 
                   9694: =item *
                   9695: 
1.243     albertel 9696: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9697: works very similar to store/cstore, but all data is stored in a
                   9698: temporary location and can be reset using tmpreset, $storehash should
                   9699: be a hash reference, returns nothing on success
1.191     harris41 9700: 
                   9701: =item *
                   9702: 
1.243     albertel 9703: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9704: similar to restore, but all data is stored in a temporary location and
                   9705: can be reset using tmpreset. Returns a hash of values on success,
                   9706: error string otherwise.
1.191     harris41 9707: 
                   9708: =item *
                   9709: 
1.243     albertel 9710: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9711: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9712: 
                   9713: =item *
                   9714: 
1.243     albertel 9715: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9716: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9717: 
                   9718: =item *
                   9719: 
1.243     albertel 9720: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9721: namesp ($udom and $uname are optional)
1.191     harris41 9722: 
                   9723: =item *
                   9724: 
1.702     albertel 9725: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9726: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9727: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9728: 
1.702     albertel 9729: $range should be either an integer '100' (give me the first 100
                   9730:                                            matching records)
                   9731:               or be  two integers sperated by a - with no spaces
                   9732:                  '30-50' (give me the 30th through the 50th matching
                   9733:                           records)
1.449     matthew  9734: =item *
                   9735: 
                   9736: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9737: $store can be a scalar, an array reference, or if the amount to be 
                   9738: incremented is > 1, a hash reference.
                   9739: 
                   9740: ($udom and $uname are optional)
1.191     harris41 9741: 
                   9742: =item *
                   9743: 
1.243     albertel 9744: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9745: ($udom and $uname are optional)
1.191     harris41 9746: 
                   9747: =item *
                   9748: 
1.243     albertel 9749: cput($namespace,$storehash,$udom,$uname) : critical put
                   9750: ($udom and $uname are optional)
1.191     harris41 9751: 
                   9752: =item *
                   9753: 
1.748     albertel 9754: newput($namespace,$storehash,$udom,$uname) :
                   9755: 
                   9756: Attempts to store the items in the $storehash, but only if they don't
                   9757: currently exist, if this succeeds you can be certain that you have 
                   9758: successfully created a new key value pair in the $namespace db.
                   9759: 
                   9760: 
                   9761: Args:
                   9762:  $namespace: name of database to store values to
                   9763:  $storehash: hashref to store to the db
                   9764:  $udom: (optional) domain of user containing the db
                   9765:  $uname: (optional) name of user caontaining the db
                   9766: 
                   9767: Returns:
                   9768:  'ok' -> succeeded in storing all keys of $storehash
                   9769:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9770:                         least <key> already existed in the db (other
                   9771:                         requested keys may also already exist)
1.967     bisitz   9772:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9773:  'con_lost' -> unable to contact request server
                   9774:  'refused' -> action was not allowed by remote machine
                   9775: 
                   9776: 
                   9777: =item *
                   9778: 
1.243     albertel 9779: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9780: reference filled in from namesp (encrypts the return communication)
                   9781: ($udom and $uname are optional)
1.191     harris41 9782: 
                   9783: =item *
                   9784: 
1.243     albertel 9785: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9786: critical subroutine
                   9787: 
1.806     raeburn  9788: =item *
                   9789: 
1.860     raeburn  9790: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9791: array reference filled in from namespace found in domain level on either
                   9792: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9793: 
                   9794: =item *
                   9795: 
1.860     raeburn  9796: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9797: domain level either on specified domain server ($uhome) or primary domain 
                   9798: server ($udom and $uhome are optional)
1.806     raeburn  9799: 
1.943     raeburn  9800: =item * 
                   9801: 
                   9802: get_domain_defaults($target_domain) : returns hash with defaults for
                   9803: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9804: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9805: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9806: Values are retrieved from cache (if current), or from domain's configuration.db
                   9807: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9808: or lonTabs/domain.tab. 
                   9809: 
                   9810: %domdefaults = &get_auth_defaults($target_domain);
                   9811: 
1.243     albertel 9812: =back
                   9813: 
                   9814: =head2 Network Status Functions
                   9815: 
                   9816: =over 4
1.191     harris41 9817: 
                   9818: =item *
                   9819: 
                   9820: dirlist($uri) : return directory list based on URI
                   9821: 
                   9822: =item *
                   9823: 
1.243     albertel 9824: spareserver() : find server with least workload from spare.tab
                   9825: 
                   9826: =back
                   9827: 
                   9828: =head2 Apache Request
                   9829: 
                   9830: =over 4
1.191     harris41 9831: 
                   9832: =item *
                   9833: 
1.243     albertel 9834: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9835: localhost, posts hash
                   9836: 
                   9837: =back
                   9838: 
                   9839: =head2 Data to String to Data
                   9840: 
                   9841: =over 4
1.191     harris41 9842: 
                   9843: =item *
                   9844: 
1.243     albertel 9845: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9846: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9847: 
                   9848: =item *
                   9849: 
1.243     albertel 9850: hashref2str($hashref) : convert a hashref into a string complete with
                   9851: escaping and '=' and '&' separators, supports elements that are
                   9852: arrayrefs and hashrefs
1.191     harris41 9853: 
                   9854: =item *
                   9855: 
1.243     albertel 9856: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9857: with escaping and '&' separators, supports elements that are arrayrefs
                   9858: and hashrefs
1.191     harris41 9859: 
                   9860: =item *
                   9861: 
1.243     albertel 9862: str2hash($string) : convert string to hash using unescaping and
                   9863: splitting on '=' and '&', supports elements that are arrayrefs and
                   9864: hashrefs
1.191     harris41 9865: 
                   9866: =item *
                   9867: 
1.243     albertel 9868: str2array($string) : convert string to hash using unescaping and
                   9869: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9870: 
                   9871: =back
                   9872: 
                   9873: =head2 Logging Routines
                   9874: 
                   9875: =over 4
                   9876: 
                   9877: These routines allow one to make log messages in the lonnet.log and
                   9878: lonnet.perm logfiles.
1.191     harris41 9879: 
                   9880: =item *
                   9881: 
1.243     albertel 9882: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9883: 
                   9884: =item *
                   9885: 
1.243     albertel 9886: logthis() : append message to the normal lonnet.log file, it gets
                   9887: preiodically rolled over and deleted.
1.191     harris41 9888: 
                   9889: =item *
                   9890: 
1.243     albertel 9891: logperm() : append a permanent message to lonnet.perm.log, this log
                   9892: file never gets deleted by any automated portion of the system, only
                   9893: messages of critical importance should go in here.
                   9894: 
                   9895: =back
                   9896: 
                   9897: =head2 General File Helper Routines
                   9898: 
                   9899: =over 4
1.191     harris41 9900: 
                   9901: =item *
                   9902: 
1.481     raeburn  9903: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9904: (a) files in /uploaded
                   9905:   (i) If a local copy of the file exists - 
                   9906:       compares modification date of local copy with last-modified date for 
                   9907:       definitive version stored on home server for course. If local copy is 
                   9908:       stale, requests a new version from the home server and stores it. 
                   9909:       If the original has been removed from the home server, then local copy 
                   9910:       is unlinked.
                   9911:   (ii) If local copy does not exist -
                   9912:       requests the file from the home server and stores it. 
                   9913:   
                   9914:   If $caller is 'uploadrep':  
                   9915:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9916:     for request for files originally uploaded via DOCS. 
                   9917:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9918:   
                   9919:   Otherwise:
                   9920:      This indicates a call from the content generation phase of the request.
                   9921:      -  returns the entire contents of the file or -1.
                   9922:      
                   9923: (b) files in /res
                   9924:    - returns the entire contents of a file or -1; 
                   9925:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9926: 
1.712     albertel 9927: 
                   9928: =item *
                   9929: 
                   9930: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9931:                   reference
                   9932: 
                   9933: returns either a stat() list of data about the file or an empty list
                   9934: if the file doesn't exist or couldn't find out about it (connection
                   9935: problems or user unknown)
                   9936: 
1.191     harris41 9937: =item *
                   9938: 
1.243     albertel 9939: filelocation($dir,$file) : returns file system location of a file
                   9940: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9941: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9942: and a file of ../bob will become /a/bob)
1.191     harris41 9943: 
                   9944: =item *
                   9945: 
                   9946: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9947: filelocation except for hrefs
                   9948: 
                   9949: =item *
                   9950: 
                   9951: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9952: 
1.243     albertel 9953: =back
                   9954: 
1.608     albertel 9955: =head2 Usererfile file routines (/uploaded*)
                   9956: 
                   9957: =over 4
                   9958: 
                   9959: =item *
                   9960: 
                   9961: userfileupload(): main rotine for putting a file in a user or course's
                   9962:                   filespace, arguments are,
                   9963: 
1.620     albertel 9964:  formname - required - this is the name of the element in $env where the
1.608     albertel 9965:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9966:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9967:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9968:  coursedoc - if true, store the file in the course of the active role
                   9969:              of the current user
                   9970:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9971:          if undefined, it will be placed in "unknown"
                   9972: 
                   9973:  (This routine calls clean_filename() to remove any dangerous
                   9974:  characters from the filename, and then calls finuserfileupload() to
                   9975:  complete the transaction)
                   9976: 
                   9977:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9978:  and /adm/notfound.html if unsuccessful
                   9979: 
                   9980: =item *
                   9981: 
                   9982: clean_filename(): routine for cleaing a filename up for storage in
                   9983:                  userfile space, argument is:
                   9984: 
                   9985:  filename - proposed filename
                   9986: 
                   9987: returns: the new clean filename
                   9988: 
                   9989: =item *
                   9990: 
                   9991: finishuserfileupload(): routine that creaes and sends the file to
                   9992: userspace, probably shouldn't be called directly
                   9993: 
                   9994:   docuname: username or courseid of destination for the file
                   9995:   docudom: domain of user/course of destination for the file
                   9996:   formname: same as for userfileupload()
                   9997:   fname: filename (inculding subdirectories) for the file
                   9998: 
                   9999:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10000:  and /adm/notfound.html if unsuccessful
                   10001: 
                   10002: =item *
                   10003: 
                   10004: renameuserfile(): renames an existing userfile to a new name
                   10005: 
                   10006:   Args:
                   10007:    docuname: username or courseid of destination for the file
                   10008:    docudom: domain of user/course of destination for the file
                   10009:    old: current file name (including any subdirs under userfiles)
                   10010:    new: desired file name (including any subdirs under userfiles)
                   10011: 
                   10012: =item *
                   10013: 
                   10014: mkdiruserfile(): creates a directory is a userfiles dir
                   10015: 
                   10016:   Args:
                   10017:    docuname: username or courseid of destination for the file
                   10018:    docudom: domain of user/course of destination for the file
                   10019:    dir: dir to create (including any subdirs under userfiles)
                   10020: 
                   10021: =item *
                   10022: 
                   10023: removeuserfile(): removes a file that exists in userfiles
                   10024: 
                   10025:   Args:
                   10026:    docuname: username or courseid of destination for the file
                   10027:    docudom: domain of user/course of destination for the file
                   10028:    fname: filname to delete (including any subdirs under userfiles)
                   10029: 
                   10030: =item *
                   10031: 
                   10032: removeuploadedurl(): convience function for removeuserfile()
                   10033: 
                   10034:   Args:
                   10035:    url:  a full /uploaded/... url to delete
                   10036: 
1.747     albertel 10037: =item * 
                   10038: 
                   10039: get_portfile_permissions():
                   10040:   Args:
                   10041:     domain: domain of user or course contain the portfolio files
                   10042:     user: name of user or num of course contain the portfolio files
                   10043:   Returns:
                   10044:     hashref of a dump of the proper file_permissions.db
                   10045:    
                   10046: 
                   10047: =item * 
                   10048: 
                   10049: get_access_controls():
                   10050: 
                   10051: Args:
                   10052:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10053:   group: (optional) the group you want the files associated with
                   10054:   file: (optional) the file you want access info on
                   10055: 
                   10056: Returns:
1.749     raeburn  10057:     a hash (keys are file names) of hashes containing
                   10058:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10059:         values are XML containing access control settings (see below) 
1.747     albertel 10060: 
                   10061: Internal notes:
                   10062: 
1.749     raeburn  10063:  access controls are stored in file_permissions.db as key=value pairs.
                   10064:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10065:         where scope -> public,guest,course,group,domains or users.
                   10066:               end -> UNIX time for end of access (0 -> no end date)
                   10067:               start -> UNIX time for start of access
                   10068: 
                   10069:     value -> XML description of access control
                   10070:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10071:             <start></start>
                   10072:             <end></end>
                   10073: 
                   10074:             <password></password>  for scope type = guest
                   10075: 
                   10076:             <domain></domain>     for scope type = course or group
                   10077:             <number></number>
                   10078:             <roles id="">
                   10079:              <role></role>
                   10080:              <access></access>
                   10081:              <section></section>
                   10082:              <group></group>
                   10083:             </roles>
                   10084: 
                   10085:             <dom></dom>         for scope type = domains
                   10086: 
                   10087:             <users>             for scope type = users
                   10088:              <user>
                   10089:               <uname></uname>
                   10090:               <udom></udom>
                   10091:              </user>
                   10092:             </users>
                   10093:            </scope> 
                   10094:               
                   10095:  Access data is also aggregated for each file in an additional key=value pair:
                   10096:  key -> path to file/file_name\0accesscontrol 
                   10097:  value -> reference to hash
                   10098:           hash contains key = value pairs
                   10099:           where key = uniqueID:scope_end_start
                   10100:                 value = UNIX time record was last updated
                   10101: 
                   10102:           Used to improve speed of look-ups of access controls for each file.  
                   10103:  
                   10104:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10105: 
                   10106: modify_access_controls():
                   10107: 
                   10108: Modifies access controls for a portfolio file
                   10109: Args
                   10110: 1. file name
                   10111: 2. reference to hash of required changes,
                   10112: 3. domain
                   10113: 4. username
                   10114:   where domain,username are the domain of the portfolio owner 
                   10115:   (either a user or a course) 
                   10116: 
                   10117: Returns:
                   10118: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10119: 2. result of deletions ('ok' or 'error', with error message).
                   10120: 3. reference to hash of any new or updated access controls.
                   10121: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10122:    key = integer (inbound ID)
                   10123:    value = uniqueID  
1.747     albertel 10124: 
1.608     albertel 10125: =back
                   10126: 
1.243     albertel 10127: =head2 HTTP Helper Routines
                   10128: 
                   10129: =over 4
                   10130: 
1.191     harris41 10131: =item *
                   10132: 
                   10133: escape() : unpack non-word characters into CGI-compatible hex codes
                   10134: 
                   10135: =item *
                   10136: 
                   10137: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10138: 
1.243     albertel 10139: =back
                   10140: 
                   10141: =head1 PRIVATE SUBROUTINES
                   10142: 
                   10143: =head2 Underlying communication routines (Shouldn't call)
                   10144: 
                   10145: =over 4
                   10146: 
                   10147: =item *
                   10148: 
                   10149: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10150: 
                   10151: =item *
                   10152: 
                   10153: reply() : uses subreply to send a message to remote machine, logs all failures
                   10154: 
                   10155: =item *
                   10156: 
                   10157: critical() : passes a critical message to another server; if cannot
                   10158: get through then place message in connection buffer directory and
                   10159: returns con_delayed, if incapable of saving message, returns
                   10160: con_failed
                   10161: 
                   10162: =item *
                   10163: 
                   10164: reconlonc() : tries to reconnect lonc client processes.
                   10165: 
                   10166: =back
                   10167: 
                   10168: =head2 Resource Access Logging
                   10169: 
                   10170: =over 4
                   10171: 
                   10172: =item *
                   10173: 
                   10174: flushcourselogs() : flush (save) buffer logs and access logs
                   10175: 
                   10176: =item *
                   10177: 
                   10178: courselog($what) : save message for course in hash
                   10179: 
                   10180: =item *
                   10181: 
                   10182: courseacclog($what) : save message for course using &courselog().  Perform
                   10183: special processing for specific resource types (problems, exams, quizzes, etc).
                   10184: 
1.191     harris41 10185: =item *
                   10186: 
                   10187: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10188: as a PerlChildExitHandler
1.243     albertel 10189: 
                   10190: =back
                   10191: 
                   10192: =head2 Other
                   10193: 
                   10194: =over 4
                   10195: 
                   10196: =item *
                   10197: 
                   10198: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10199: 
                   10200: =back
                   10201: 
                   10202: =cut
1.877     foxr     10203: 

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