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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.973   ! bisitz      4: # $Id: lonnet.pm,v 1.972 2008/11/25 18:20:11 jms 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)) {
                    524: 	    if ($key=~/^$delthis/) { 
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.943     raeburn  1225: # ------------------------- Get Authentication and Language Defaults for Domain
                   1226: 
                   1227: sub get_domain_defaults {
                   1228:     my ($domain) = @_;
                   1229:     my $cachetime = 60*60*24;
                   1230:     my ($defauthtype,$defautharg,$deflang);
                   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 =
                   1239:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   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:     }
                   1249:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1250:                                   $cachetime);
                   1251:     return %domdefaults;
                   1252: }
                   1253: 
1.344     www      1254: # --------------------------------------------------- Assign a key to a student
                   1255: 
                   1256: sub assign_access_key {
1.364     www      1257: #
                   1258: # a valid key looks like uname:udom#comments
                   1259: # comments are being appended
                   1260: #
1.498     www      1261:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1262:     $kdom=
1.620     albertel 1263:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1264:     $knum=
1.620     albertel 1265:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1266:     $cdom=
1.620     albertel 1267:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1268:     $cnum=
1.620     albertel 1269:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1270:     $udom=$env{'user.name'} unless (defined($udom));
                   1271:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1272:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1273:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1274:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1275:                                                   # assigned to this person
                   1276:                                                   # - this should not happen,
1.345     www      1277:                                                   # unless something went wrong
                   1278:                                                   # the first time around
                   1279: # ready to assign
1.364     www      1280:         $logentry=$1.'; '.$logentry;
1.496     www      1281:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1282:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1283: # key now belongs to user
1.346     www      1284: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1285:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1286:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1287:                 return 'ok';
                   1288:             } else {
                   1289:                 return 
                   1290:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1291: 	    }
                   1292:         } else {
                   1293:             return 'error: Could not assign key, try again later.';
                   1294:         }
1.364     www      1295:     } elsif (!$existing{$ckey}) {
1.345     www      1296: # the key does not exist
                   1297: 	return 'error: The key does not exist';
                   1298:     } else {
                   1299: # the key is somebody else's
                   1300: 	return 'error: The key is already in use';
                   1301:     }
1.344     www      1302: }
                   1303: 
1.364     www      1304: # ------------------------------------------ put an additional comment on a key
                   1305: 
                   1306: sub comment_access_key {
                   1307: #
                   1308: # a valid key looks like uname:udom#comments
                   1309: # comments are being appended
                   1310: #
                   1311:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1312:     $cdom=
1.620     albertel 1313:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1314:     $cnum=
1.620     albertel 1315:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1316:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1317:     if ($existing{$ckey}) {
                   1318:         $existing{$ckey}.='; '.$logentry;
                   1319: # ready to assign
1.367     www      1320:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1321:                                                  $cdom,$cnum) eq 'ok') {
                   1322: 	    return 'ok';
                   1323:         } else {
                   1324: 	    return 'error: Count not store comment.';
                   1325:         }
                   1326:     } else {
                   1327: # the key does not exist
                   1328: 	return 'error: The key does not exist';
                   1329:     }
                   1330: }
                   1331: 
1.344     www      1332: # ------------------------------------------------------ Generate a set of keys
                   1333: 
                   1334: sub generate_access_keys {
1.364     www      1335:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1336:     $cdom=
1.620     albertel 1337:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1338:     $cnum=
1.620     albertel 1339:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1340:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1341:     unless (($cdom) && ($cnum)) { return 0; }
                   1342:     if ($number>10000) { return 0; }
                   1343:     sleep(2); # make sure don't get same seed twice
                   1344:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1345:     my $total=0;
                   1346:     for (my $i=1;$i<=$number;$i++) {
                   1347:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1348:                   sprintf("%lx",int(100000*rand)).'-'.
                   1349:                   sprintf("%lx",int(100000*rand));
                   1350:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1351:        $newkey=~s/0/h/g; # and also 0 and O
                   1352:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1353:        if ($existing{$newkey}) {
                   1354:            $i--;
                   1355:        } else {
1.364     www      1356: 	  if (&put('accesskeys',
                   1357:               { $newkey => '# generated '.localtime().
1.620     albertel 1358:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1359:                            '; '.$logentry },
                   1360: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1361:               $total++;
                   1362: 	  }
                   1363:        }
                   1364:     }
1.620     albertel 1365:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1366:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1367:     return $total;
                   1368: }
                   1369: 
                   1370: # ------------------------------------------------------- Validate an accesskey
                   1371: 
                   1372: sub validate_access_key {
                   1373:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1374:     $cdom=
1.620     albertel 1375:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1376:     $cnum=
1.620     albertel 1377:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1378:     $udom=$env{'user.domain'} unless (defined($udom));
                   1379:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1380:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1381:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1382: }
                   1383: 
                   1384: # ------------------------------------- Find the section of student in a course
1.652     albertel 1385: sub devalidate_getsection_cache {
                   1386:     my ($udom,$unam,$courseid)=@_;
                   1387:     my $hashid="$udom:$unam:$courseid";
                   1388:     &devalidate_cache_new('getsection',$hashid);
                   1389: }
1.298     matthew  1390: 
1.815     albertel 1391: sub courseid_to_courseurl {
                   1392:     my ($courseid) = @_;
                   1393:     #already url style courseid
                   1394:     return $courseid if ($courseid =~ m{^/});
                   1395: 
                   1396:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1397: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1398: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1399: 	return "/$cdom/$cnum";
                   1400:     }
                   1401: 
                   1402:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1403:     if (exists($courseinfo{'num'})) {
                   1404: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1405:     }
                   1406: 
                   1407:     return undef;
                   1408: }
                   1409: 
1.298     matthew  1410: sub getsection {
                   1411:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1412:     my $cachetime=1800;
1.551     albertel 1413: 
                   1414:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1415:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1416:     if (defined($cached)) { return $result; }
                   1417: 
1.298     matthew  1418:     my %Pending; 
                   1419:     my %Expired;
                   1420:     #
                   1421:     # Each role can either have not started yet (pending), be active, 
                   1422:     #    or have expired.
                   1423:     #
                   1424:     # If there is an active role, we are done.
                   1425:     #
                   1426:     # If there is more than one role which has not started yet, 
                   1427:     #     choose the one which will start sooner
                   1428:     # If there is one role which has not started yet, return it.
                   1429:     #
                   1430:     # If there is more than one expired role, choose the one which ended last.
                   1431:     # If there is a role which has expired, return it.
                   1432:     #
1.815     albertel 1433:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1434:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1435:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1436:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1437:         my $section=$1;
                   1438:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1439:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1440:         my $now=time;
1.548     albertel 1441:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1442:             $Expired{$end}=$section;
                   1443:             next;
                   1444:         }
1.548     albertel 1445:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1446:             $Pending{$start}=$section;
                   1447:             next;
                   1448:         }
1.599     albertel 1449:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1450:     }
                   1451:     #
                   1452:     # Presumedly there will be few matching roles from the above
                   1453:     # loop and the sorting time will be negligible.
                   1454:     if (scalar(keys(%Pending))) {
                   1455:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1456:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1457:     } 
                   1458:     if (scalar(keys(%Expired))) {
                   1459:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1460:         my $time = pop(@sorted);
1.599     albertel 1461:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1462:     }
1.599     albertel 1463:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1464: }
1.70      www      1465: 
1.599     albertel 1466: sub save_cache {
                   1467:     &purge_remembered();
1.722     albertel 1468:     #&Apache::loncommon::validate_page();
1.620     albertel 1469:     undef(%env);
1.780     albertel 1470:     undef($env_loaded);
1.599     albertel 1471: }
1.452     albertel 1472: 
1.599     albertel 1473: my $to_remember=-1;
                   1474: my %remembered;
                   1475: my %accessed;
                   1476: my $kicks=0;
                   1477: my $hits=0;
1.849     albertel 1478: sub make_key {
                   1479:     my ($name,$id) = @_;
1.872     albertel 1480:     if (length($id) > 65 
                   1481: 	&& length(&escape($id)) > 200) {
                   1482: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1483:     }
1.849     albertel 1484:     return &escape($name.':'.$id);
                   1485: }
                   1486: 
1.599     albertel 1487: sub devalidate_cache_new {
                   1488:     my ($name,$id,$debug) = @_;
                   1489:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1490:     $id=&make_key($name,$id);
1.599     albertel 1491:     $memcache->delete($id);
                   1492:     delete($remembered{$id});
                   1493:     delete($accessed{$id});
                   1494: }
                   1495: 
                   1496: sub is_cached_new {
                   1497:     my ($name,$id,$debug) = @_;
1.849     albertel 1498:     $id=&make_key($name,$id);
1.599     albertel 1499:     if (exists($remembered{$id})) {
                   1500: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1501: 	$accessed{$id}=[&gettimeofday()];
                   1502: 	$hits++;
                   1503: 	return ($remembered{$id},1);
                   1504:     }
                   1505:     my $value = $memcache->get($id);
                   1506:     if (!(defined($value))) {
                   1507: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1508: 	return (undef,undef);
1.416     albertel 1509:     }
1.599     albertel 1510:     if ($value eq '__undef__') {
                   1511: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1512: 	$value=undef;
                   1513:     }
                   1514:     &make_room($id,$value,$debug);
                   1515:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1516:     return ($value,1);
                   1517: }
                   1518: 
                   1519: sub do_cache_new {
                   1520:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1521:     $id=&make_key($name,$id);
1.599     albertel 1522:     my $setvalue=$value;
                   1523:     if (!defined($setvalue)) {
                   1524: 	$setvalue='__undef__';
                   1525:     }
1.623     albertel 1526:     if (!defined($time) ) {
                   1527: 	$time=600;
                   1528:     }
1.599     albertel 1529:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1530:     my $result = $memcache->set($id,$setvalue,$time);
                   1531:     if (! $result) {
1.872     albertel 1532: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1533: 	$memcache->disconnect_all();
1.872     albertel 1534:     }
1.600     albertel 1535:     # need to make a copy of $value
1.919     albertel 1536:     &make_room($id,$value,$debug);
1.599     albertel 1537:     return $value;
                   1538: }
                   1539: 
                   1540: sub make_room {
                   1541:     my ($id,$value,$debug)=@_;
1.919     albertel 1542: 
                   1543:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1544:                                     : $value;
1.599     albertel 1545:     if ($to_remember<0) { return; }
                   1546:     $accessed{$id}=[&gettimeofday()];
                   1547:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1548:     my $to_kick;
                   1549:     my $max_time=0;
                   1550:     foreach my $other (keys(%accessed)) {
                   1551: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1552: 	    $to_kick=$other;
                   1553: 	    $max_time=&tv_interval($accessed{$other});
                   1554: 	}
                   1555:     }
                   1556:     delete($remembered{$to_kick});
                   1557:     delete($accessed{$to_kick});
                   1558:     $kicks++;
                   1559:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1560:     return;
                   1561: }
                   1562: 
1.599     albertel 1563: sub purge_remembered {
1.604     albertel 1564:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1565:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1566:     undef(%remembered);
                   1567:     undef(%accessed);
1.428     albertel 1568: }
1.70      www      1569: # ------------------------------------- Read an entry from a user's environment
                   1570: 
                   1571: sub userenvironment {
                   1572:     my ($udom,$unam,@what)=@_;
                   1573:     my %returnhash=();
                   1574:     my @answer=split(/\&/,
                   1575:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1576:                       &homeserver($unam,$udom)));
                   1577:     my $i;
                   1578:     for ($i=0;$i<=$#what;$i++) {
                   1579: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1580:     }
                   1581:     return %returnhash;
1.1       albertel 1582: }
                   1583: 
1.617     albertel 1584: # ---------------------------------------------------------- Get a studentphoto
                   1585: sub studentphoto {
                   1586:     my ($udom,$unam,$ext) = @_;
                   1587:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1588:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1589:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1590:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1591:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1592:             } else {
                   1593:                 my ($result,$perm_reqd)=
1.707     albertel 1594: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1595:                 if ($result eq 'ok') {
                   1596:                     if (!($perm_reqd eq 'yes')) {
                   1597:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1598:                     }
                   1599:                 }
                   1600:             }
                   1601:         }
                   1602:     } else {
                   1603:         my ($result,$perm_reqd) = 
1.707     albertel 1604: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1605:         if ($result eq 'ok') {
                   1606:             if (!($perm_reqd eq 'yes')) {
                   1607:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1608:             }
                   1609:         }
                   1610:     }
                   1611:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1612: }
                   1613: 
                   1614: sub retrievestudentphoto {
                   1615:     my ($udom,$unam,$ext,$type) = @_;
                   1616:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1617:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1618:     if ($ret eq 'ok') {
                   1619:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1620:         if ($type eq 'thumbnail') {
                   1621:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1622:         }
                   1623:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1624:         return $tokenurl;
                   1625:     } else {
                   1626:         if ($type eq 'thumbnail') {
                   1627:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1628:         } else { 
                   1629:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1630:         }
1.617     albertel 1631:     }
                   1632: }
                   1633: 
1.263     www      1634: # -------------------------------------------------------------------- New chat
                   1635: 
                   1636: sub chatsend {
1.724     raeburn  1637:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1638:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1639:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1640:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1641:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1642: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1643: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1644: }
                   1645: 
                   1646: # ------------------------------------------ Find current version of a resource
                   1647: 
                   1648: sub getversion {
                   1649:     my $fname=&clutter(shift);
                   1650:     unless ($fname=~/^\/res\//) { return -1; }
                   1651:     return &currentversion(&filelocation('',$fname));
                   1652: }
                   1653: 
                   1654: sub currentversion {
                   1655:     my $fname=shift;
1.599     albertel 1656:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1657:     if (defined($cached)) { return $result; }
1.292     www      1658:     my $author=$fname;
                   1659:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1660:     my ($udom,$uname)=split(/\//,$author);
                   1661:     my $home=homeserver($uname,$udom);
                   1662:     if ($home eq 'no_host') { 
                   1663:         return -1; 
                   1664:     }
                   1665:     my $answer=reply("currentversion:$fname",$home);
                   1666:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1667: 	return -1;
                   1668:     }
1.599     albertel 1669:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1670: }
                   1671: 
1.1       albertel 1672: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1673: 
1.1       albertel 1674: sub subscribe {
                   1675:     my $fname=shift;
1.761     raeburn  1676:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1677:     $fname=~s/[\n\r]//g;
1.1       albertel 1678:     my $author=$fname;
                   1679:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1680:     my ($udom,$uname)=split(/\//,$author);
                   1681:     my $home=homeserver($uname,$udom);
1.335     albertel 1682:     if ($home eq 'no_host') {
                   1683:         return 'not_found';
1.1       albertel 1684:     }
                   1685:     my $answer=reply("sub:$fname",$home);
1.64      www      1686:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1687: 	$answer.=' by '.$home;
                   1688:     }
1.1       albertel 1689:     return $answer;
                   1690: }
                   1691:     
1.8       www      1692: # -------------------------------------------------------------- Replicate file
                   1693: 
                   1694: sub repcopy {
                   1695:     my $filename=shift;
1.23      www      1696:     $filename=~s/\/+/\//g;
1.607     raeburn  1697:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1698:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1699:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1700: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1701: 	return &repcopy_userfile($filename);
                   1702:     }
1.532     albertel 1703:     $filename=~s/[\n\r]//g;
1.8       www      1704:     my $transname="$filename.in.transfer";
1.828     www      1705: # FIXME: this should flock
1.607     raeburn  1706:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1707:     my $remoteurl=subscribe($filename);
1.64      www      1708:     if ($remoteurl =~ /^con_lost by/) {
                   1709: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1710:            return 'unavailable';
1.8       www      1711:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1712: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1713: 	   return 'not_found';
1.64      www      1714:     } elsif ($remoteurl =~ /^rejected by/) {
                   1715: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1716:            return 'forbidden';
1.20      www      1717:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1718:            return 'ok';
1.8       www      1719:     } else {
1.290     www      1720:         my $author=$filename;
                   1721:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1722:         my ($udom,$uname)=split(/\//,$author);
                   1723:         my $home=homeserver($uname,$udom);
                   1724:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1725:            my @parts=split(/\//,$filename);
                   1726:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1727:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1728:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1729: 	       return 'bad_request';
1.8       www      1730:            }
                   1731:            my $count;
                   1732:            for ($count=5;$count<$#parts;$count++) {
                   1733:                $path.="/$parts[$count]";
                   1734:                if ((-e $path)!=1) {
                   1735: 		   mkdir($path,0777);
                   1736:                }
                   1737:            }
                   1738:            my $ua=new LWP::UserAgent;
                   1739:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1740:            my $response=$ua->request($request,$transname);
                   1741:            if ($response->is_error()) {
                   1742: 	       unlink($transname);
                   1743:                my $message=$response->status_line;
1.672     albertel 1744:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1745:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1746:                return 'unavailable';
1.8       www      1747:            } else {
1.16      www      1748: 	       if ($remoteurl!~/\.meta$/) {
                   1749:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1750:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1751:                   if ($mresponse->is_error()) {
                   1752: 		      unlink($filename.'.meta');
                   1753:                       &logthis(
1.672     albertel 1754:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1755:                   }
                   1756: 	       }
1.8       www      1757:                rename($transname,$filename);
1.607     raeburn  1758:                return 'ok';
1.8       www      1759:            }
1.290     www      1760:        }
1.8       www      1761:     }
1.330     www      1762: }
                   1763: 
                   1764: # ------------------------------------------------ Get server side include body
                   1765: sub ssi_body {
1.381     albertel 1766:     my ($filelink,%form)=@_;
1.606     matthew  1767:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1768:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1769:     }
1.953     www      1770:     my $output='';
                   1771:     my $response;
                   1772:     if ($filelink=~/^http\:/) {
1.954     raeburn  1773:        ($output,$response)=&externalssi($filelink);
1.953     www      1774:     } else {
                   1775:        ($output,$response)=&ssi($filelink,%form);
                   1776:     }
1.778     albertel 1777:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1778:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1779:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1780:     if (wantarray) {
                   1781:         return ($output, $response);
                   1782:     } else {
                   1783:         return $output;
                   1784:     }
1.8       www      1785: }
                   1786: 
1.15      www      1787: # --------------------------------------------------------- Server Side Include
                   1788: 
1.782     albertel 1789: sub absolute_url {
                   1790:     my ($host_name) = @_;
                   1791:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1792:     if ($host_name eq '') {
                   1793: 	$host_name = $ENV{'SERVER_NAME'};
                   1794:     }
                   1795:     return $protocol.$host_name;
                   1796: }
                   1797: 
1.942     foxr     1798: #
                   1799: #   Server side include.
                   1800: # Parameters:
                   1801: #  fn     Possibly encrypted resource name/id.
                   1802: #  form   Hash that describes how the rendering should be done
                   1803: #         and other things.
1.944     foxr     1804: # Returns:
1.950     raeburn  1805: #   Scalar context: The content of the response.
                   1806: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1807: #     
1.15      www      1808: sub ssi {
                   1809: 
1.944     foxr     1810:     my ($fn,%form)=@_;
1.15      www      1811:     my $ua=new LWP::UserAgent;
1.23      www      1812:     my $request;
1.711     albertel 1813: 
                   1814:     $form{'no_update_last_known'}=1;
1.895     albertel 1815:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1816:     if (%form) {
1.782     albertel 1817:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1818:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1819:     } else {
1.782     albertel 1820:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1821:     }
                   1822: 
1.15      www      1823:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1824:     my $response=$ua->request($request);
                   1825: 
1.944     foxr     1826:     if (wantarray) {
                   1827: 	return ($response->content, $response);
                   1828:     } else {
                   1829: 	return $response->content;
1.942     foxr     1830:     }
1.324     www      1831: }
                   1832: 
                   1833: sub externalssi {
                   1834:     my ($url)=@_;
                   1835:     my $ua=new LWP::UserAgent;
                   1836:     my $request=new HTTP::Request('GET',$url);
                   1837:     my $response=$ua->request($request);
1.954     raeburn  1838:     if (wantarray) {
                   1839:         return ($response->content, $response);
                   1840:     } else {
                   1841:         return $response->content;
                   1842:     }
1.15      www      1843: }
1.254     www      1844: 
1.492     albertel 1845: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1846: 
                   1847: sub allowuploaded {
                   1848:     my ($srcurl,$url)=@_;
                   1849:     $url=&clutter(&declutter($url));
                   1850:     my $dir=$url;
                   1851:     $dir=~s/\/[^\/]+$//;
                   1852:     my %httpref=();
                   1853:     my $httpurl=&hreflocation('',$url);
                   1854:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1855:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1856: }
1.477     raeburn  1857: 
1.478     albertel 1858: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1859: # input: action, courseID, current domain, intended
1.637     raeburn  1860: #        path to file, source of file, instruction to parse file for objects,
                   1861: #        ref to hash for embedded objects,
                   1862: #        ref to hash for codebase of java objects.
                   1863: #
1.485     raeburn  1864: # output: url to file (if action was uploaddoc), 
                   1865: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1866: #
1.478     albertel 1867: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1868: # course.
1.477     raeburn  1869: #
1.478     albertel 1870: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1871: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1872: #          course's home server.
1.477     raeburn  1873: #
1.478     albertel 1874: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1875: #          be copied from $source (current location) to 
                   1876: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1877: #         and will then be copied to
                   1878: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1879: #         course's home server.
1.485     raeburn  1880: #
1.481     raeburn  1881: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1882: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1883: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1884: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1885: #         in course's home server.
1.637     raeburn  1886: #
1.477     raeburn  1887: 
                   1888: sub process_coursefile {
1.638     albertel 1889:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1890:     my $fetchresult;
1.638     albertel 1891:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1892:     if ($action eq 'propagate') {
1.638     albertel 1893:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1894: 			     $home);
1.481     raeburn  1895:     } else {
1.477     raeburn  1896:         my $fpath = '';
                   1897:         my $fname = $file;
1.478     albertel 1898:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1899:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1900:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1901:         if ($action eq 'copy') {
                   1902:             if ($source eq '') {
                   1903:                 $fetchresult = 'no source file';
                   1904:                 return $fetchresult;
                   1905:             } else {
                   1906:                 my $destination = $filepath.'/'.$fname;
                   1907:                 rename($source,$destination);
                   1908:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1909:                                  $home);
1.481     raeburn  1910:             }
                   1911:         } elsif ($action eq 'uploaddoc') {
                   1912:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1913:             print $fh $env{'form.'.$source};
1.481     raeburn  1914:             close($fh);
1.637     raeburn  1915:             if ($parser eq 'parse') {
1.961     raeburn  1916:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1917:                 unless ($parse_result eq 'ok') {
                   1918:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1919:                 }
                   1920:             }
1.477     raeburn  1921:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1922:                                  $home);
1.481     raeburn  1923:             if ($fetchresult eq 'ok') {
                   1924:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1925:             } else {
                   1926:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1927:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1928:                 return '/adm/notfound.html';
                   1929:             }
1.477     raeburn  1930:         }
                   1931:     }
1.485     raeburn  1932:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1933:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1934:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1935:     }
                   1936:     return $fetchresult;
                   1937: }
                   1938: 
1.637     raeburn  1939: sub build_filepath {
                   1940:     my ($fpath) = @_;
                   1941:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1942:     unless ($fpath eq '') {
                   1943:         my @parts=split('/',$fpath);
                   1944:         foreach my $part (@parts) {
                   1945:             $filepath.= '/'.$part;
                   1946:             if ((-e $filepath)!=1) {
                   1947:                 mkdir($filepath,0777);
                   1948:             }
                   1949:         }
                   1950:     }
                   1951:     return $filepath;
                   1952: }
                   1953: 
                   1954: sub store_edited_file {
1.638     albertel 1955:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1956:     my $file = $primary_url;
                   1957:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1958:     my $fpath = '';
                   1959:     my $fname = $file;
                   1960:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1961:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1962:     my $filepath = &build_filepath($fpath);
                   1963:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1964:     print $fh $content;
                   1965:     close($fh);
1.638     albertel 1966:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1967:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1968: 			  $home);
1.637     raeburn  1969:     if ($$fetchresult eq 'ok') {
                   1970:         return '/uploaded/'.$fpath.'/'.$fname;
                   1971:     } else {
1.638     albertel 1972:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1973: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1974:         return '/adm/notfound.html';
                   1975:     }
                   1976: }
                   1977: 
1.531     albertel 1978: sub clean_filename {
1.831     albertel 1979:     my ($fname,$args)=@_;
1.315     www      1980: # Replace Windows backslashes by forward slashes
1.257     www      1981:     $fname=~s/\\/\//g;
1.831     albertel 1982:     if (!$args->{'keep_path'}) {
                   1983:         # Get rid of everything but the actual filename
                   1984: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1985:     }
1.315     www      1986: # Replace spaces by underscores
                   1987:     $fname=~s/\s+/\_/g;
                   1988: # Replace all other weird characters by nothing
1.831     albertel 1989:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1990: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1991: # numbers
                   1992:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1993:     return $fname;
                   1994: }
                   1995: 
1.608     albertel 1996: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1997: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1998: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1999: #        $coursedoc - if true up to the current course
                   2000: #                     if false
                   2001: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2002: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2003: #        $allfiles - reference to hash for embedded objects
                   2004: #        $codebase - reference to hash for codebase of java objects
                   2005: #        $desuname - username for permanent storage of uploaded file
                   2006: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2007: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2008: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2009: # 
1.686     albertel 2010: # output: url of file in userspace, or error: <message> 
                   2011: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2012: 
                   2013: 
1.531     albertel 2014: sub userfileupload {
1.860     raeburn  2015:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2016:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2017:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2018:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2019:     $fname=&clean_filename($fname);
1.315     www      2020: # See if there is anything left
1.257     www      2021:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2022:     chop($env{'form.'.$formname});
1.523     raeburn  2023:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2024:         my $now = time;
                   2025:         my $filepath = 'tmp/helprequests/'.$now;
                   2026:         my @parts=split(/\//,$filepath);
                   2027:         my $fullpath = $perlvar{'lonDaemons'};
                   2028:         for (my $i=0;$i<@parts;$i++) {
                   2029:             $fullpath .= '/'.$parts[$i];
                   2030:             if ((-e $fullpath)!=1) {
                   2031:                 mkdir($fullpath,0777);
                   2032:             }
                   2033:         }
                   2034:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2035:         print $fh $env{'form.'.$formname};
1.523     raeburn  2036:         close($fh);
1.741     raeburn  2037:         return $fullpath.'/'.$fname;
                   2038:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2039:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2040:                        '_'.$env{'user.domain'}.'/pending';
                   2041:         my @parts=split(/\//,$filepath);
                   2042:         my $fullpath = $perlvar{'lonDaemons'};
                   2043:         for (my $i=0;$i<@parts;$i++) {
                   2044:             $fullpath .= '/'.$parts[$i];
                   2045:             if ((-e $fullpath)!=1) {
                   2046:                 mkdir($fullpath,0777);
                   2047:             }
                   2048:         }
                   2049:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2050:         print $fh $env{'form.'.$formname};
                   2051:         close($fh);
                   2052:         return $fullpath.'/'.$fname;
1.523     raeburn  2053:     }
1.719     banghart 2054:     
1.258     www      2055: # Create the directory if not present
1.493     albertel 2056:     $fname="$subdir/$fname";
1.259     www      2057:     if ($coursedoc) {
1.638     albertel 2058: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2059: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2060:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2061:             return &finishuserfileupload($docuname,$docudom,
                   2062: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2063: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2064:         } else {
1.620     albertel 2065:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2066:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2067: 				       $fname,$formname,$parser,
                   2068: 				       $allfiles,$codebase);
1.481     raeburn  2069:         }
1.719     banghart 2070:     } elsif (defined($destuname)) {
                   2071:         my $docuname=$destuname;
                   2072:         my $docudom=$destudom;
1.860     raeburn  2073: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2074: 				     $parser,$allfiles,$codebase,
                   2075:                                      $thumbwidth,$thumbheight);
1.719     banghart 2076:         
1.259     www      2077:     } else {
1.638     albertel 2078:         my $docuname=$env{'user.name'};
                   2079:         my $docudom=$env{'user.domain'};
1.714     raeburn  2080:         if (exists($env{'form.group'})) {
                   2081:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2082:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2083:         }
1.860     raeburn  2084: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2085: 				     $parser,$allfiles,$codebase,
                   2086:                                      $thumbwidth,$thumbheight);
1.259     www      2087:     }
1.271     www      2088: }
                   2089: 
                   2090: sub finishuserfileupload {
1.860     raeburn  2091:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2092:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2093:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2094:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2095:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2096:     $file=$fname;
                   2097:     if ($fname=~m|/|) {
                   2098:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2099: 	$path.=$fnamepath.'/';
                   2100:     }
1.259     www      2101:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2102:     my $count;
                   2103:     for ($count=4;$count<=$#parts;$count++) {
                   2104:         $filepath.="/$parts[$count]";
                   2105:         if ((-e $filepath)!=1) {
                   2106: 	    mkdir($filepath,0777);
                   2107:         }
                   2108:     }
                   2109: # Save the file
                   2110:     {
1.701     albertel 2111: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2112: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2113: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2114: 	    return '/adm/notfound.html';
                   2115: 	}
                   2116: 	if (!print FH ($env{'form.'.$formname})) {
                   2117: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2118: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2119: 	    return '/adm/notfound.html';
                   2120: 	}
1.570     albertel 2121: 	close(FH);
1.258     www      2122:     }
1.637     raeburn  2123:     if ($parser eq 'parse') {
1.961     raeburn  2124:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2125: 						   $codebase);
1.637     raeburn  2126:         unless ($parse_result eq 'ok') {
1.638     albertel 2127:             &logthis('Failed to parse '.$filepath.$file.
                   2128: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2129:         }
                   2130:     }
1.860     raeburn  2131:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2132:         my $input = $filepath.'/'.$file;
                   2133:         my $output = $filepath.'/'.'tn-'.$file;
                   2134:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2135:         system("convert -sample $thumbsize $input $output");
                   2136:         if (-e $filepath.'/'.'tn-'.$file) {
                   2137:             $fetchthumb  = 1; 
                   2138:         }
                   2139:     }
1.858     raeburn  2140:  
1.259     www      2141: # Notify homeserver to grep it
                   2142: #
1.638     albertel 2143:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2144:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2145:     if ($fetchresult eq 'ok') {
1.860     raeburn  2146:         if ($fetchthumb) {
                   2147:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2148:             if ($thumbresult ne 'ok') {
                   2149:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2150:                          $docuhome.': '.$thumbresult);
                   2151:             }
                   2152:         }
1.259     www      2153: #
1.258     www      2154: # Return the URL to it
1.494     albertel 2155:         return '/uploaded/'.$path.$file;
1.263     www      2156:     } else {
1.494     albertel 2157:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2158: 		 ': '.$fetchresult);
1.263     www      2159:         return '/adm/notfound.html';
1.858     raeburn  2160:     }
1.493     albertel 2161: }
                   2162: 
1.637     raeburn  2163: sub extract_embedded_items {
1.961     raeburn  2164:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2165:     my @state = ();
                   2166:     my %javafiles = (
                   2167:                       codebase => '',
                   2168:                       code => '',
                   2169:                       archive => ''
                   2170:                     );
                   2171:     my %mediafiles = (
                   2172:                       src => '',
                   2173:                       movie => '',
                   2174:                      );
1.648     raeburn  2175:     my $p;
                   2176:     if ($content) {
                   2177:         $p = HTML::LCParser->new($content);
                   2178:     } else {
1.961     raeburn  2179:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2180:     }
1.641     albertel 2181:     while (my $t=$p->get_token()) {
1.640     albertel 2182: 	if ($t->[0] eq 'S') {
                   2183: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2184: 	    push(@state, $tagname);
1.648     raeburn  2185:             if (lc($tagname) eq 'allow') {
                   2186:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2187:             }
1.640     albertel 2188: 	    if (lc($tagname) eq 'img') {
                   2189: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2190: 	    }
1.886     albertel 2191: 	    if (lc($tagname) eq 'a') {
                   2192: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2193: 	    }
1.645     raeburn  2194:             if (lc($tagname) eq 'script') {
                   2195:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2196:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2197:                 } else {
                   2198:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2199:                 }
                   2200:             }
                   2201:             if (lc($tagname) eq 'link') {
                   2202:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2203:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2204:                 }
                   2205:             }
1.640     albertel 2206: 	    if (lc($tagname) eq 'object' ||
                   2207: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2208: 		foreach my $item (keys(%javafiles)) {
                   2209: 		    $javafiles{$item} = '';
                   2210: 		}
                   2211: 	    }
                   2212: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2213: 		my $name = lc($attr->{'name'});
                   2214: 		foreach my $item (keys(%javafiles)) {
                   2215: 		    if ($name eq $item) {
                   2216: 			$javafiles{$item} = $attr->{'value'};
                   2217: 			last;
                   2218: 		    }
                   2219: 		}
                   2220: 		foreach my $item (keys(%mediafiles)) {
                   2221: 		    if ($name eq $item) {
                   2222: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2223: 			last;
                   2224: 		    }
                   2225: 		}
                   2226: 	    }
                   2227: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2228: 		foreach my $item (keys(%javafiles)) {
                   2229: 		    if ($attr->{$item}) {
                   2230: 			$javafiles{$item} = $attr->{$item};
                   2231: 			last;
                   2232: 		    }
                   2233: 		}
                   2234: 		foreach my $item (keys(%mediafiles)) {
                   2235: 		    if ($attr->{$item}) {
                   2236: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2237: 			last;
                   2238: 		    }
                   2239: 		}
                   2240: 	    }
                   2241: 	} elsif ($t->[0] eq 'E') {
                   2242: 	    my ($tagname) = ($t->[1]);
                   2243: 	    if ($javafiles{'codebase'} ne '') {
                   2244: 		$javafiles{'codebase'} .= '/';
                   2245: 	    }  
                   2246: 	    if (lc($tagname) eq 'applet' ||
                   2247: 		lc($tagname) eq 'object' ||
                   2248: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2249: 		) {
                   2250: 		foreach my $item (keys(%javafiles)) {
                   2251: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2252: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2253: 			&add_filetype($allfiles,$file,$item);
                   2254: 		    }
                   2255: 		}
                   2256: 	    } 
                   2257: 	    pop @state;
                   2258: 	}
                   2259:     }
1.637     raeburn  2260:     return 'ok';
                   2261: }
                   2262: 
1.639     albertel 2263: sub add_filetype {
                   2264:     my ($allfiles,$file,$type)=@_;
                   2265:     if (exists($allfiles->{$file})) {
                   2266: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2267: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2268: 	}
                   2269:     } else {
                   2270: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2271:     }
                   2272: }
                   2273: 
1.493     albertel 2274: sub removeuploadedurl {
                   2275:     my ($url)=@_;
                   2276:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2277:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2278: }
                   2279: 
                   2280: sub removeuserfile {
                   2281:     my ($docuname,$docudom,$fname)=@_;
                   2282:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2283:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2284:     if ($result eq 'ok') {
                   2285:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2286:             my $metafile = $fname.'.meta';
                   2287:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2288: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2289:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2290:             my $sqlresult = 
1.823     albertel 2291:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2292:                                         'portfolio_metadata',$group,
                   2293:                                         'delete');
1.798     raeburn  2294:         }
                   2295:     }
                   2296:     return $result;
1.257     www      2297: }
1.15      www      2298: 
1.530     albertel 2299: sub mkdiruserfile {
                   2300:     my ($docuname,$docudom,$dir)=@_;
                   2301:     my $home=&homeserver($docuname,$docudom);
                   2302:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2303: }
                   2304: 
1.531     albertel 2305: sub renameuserfile {
                   2306:     my ($docuname,$docudom,$old,$new)=@_;
                   2307:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2308:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2309:                         &escape("$old").':'.&escape("$new"),$home);
                   2310:     if ($result eq 'ok') {
                   2311:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2312:             my $oldmeta = $old.'.meta';
                   2313:             my $newmeta = $new.'.meta';
                   2314:             my $metaresult = 
                   2315:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2316: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2317:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2318:             my $sqlresult = 
1.823     albertel 2319:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2320:                                         'portfolio_metadata',$group,
                   2321:                                         'delete');
1.798     raeburn  2322:         }
                   2323:     }
                   2324:     return $result;
1.531     albertel 2325: }
                   2326: 
1.14      www      2327: # ------------------------------------------------------------------------- Log
                   2328: 
                   2329: sub log {
                   2330:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2331:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2332: }
                   2333: 
                   2334: # ------------------------------------------------------------------ Course Log
1.352     www      2335: #
                   2336: # This routine flushes several buffers of non-mission-critical nature
                   2337: #
1.157     www      2338: 
                   2339: sub flushcourselogs {
1.352     www      2340:     &logthis('Flushing log buffers');
                   2341: #
                   2342: # course logs
                   2343: # This is a log of all transactions in a course, which can be used
                   2344: # for data mining purposes
                   2345: #
                   2346: # It also collects the courseid database, which lists last transaction
                   2347: # times and course titles for all courseids
                   2348: #
                   2349:     my %courseidbuffer=();
1.921     raeburn  2350:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2351:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2352: 		          &escape($courselogs{$crsid}),
                   2353: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2354: 	    delete $courselogs{$crsid};
                   2355:         } else {
                   2356:             &logthis('Failed to flush log buffer for '.$crsid);
                   2357:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2358:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2359:                         " exceeded maximum size, deleting.</font>");
                   2360:                delete $courselogs{$crsid};
                   2361:             }
1.352     www      2362:         }
1.920     raeburn  2363:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2364:             'description' => $coursedescrbuf{$crsid},
                   2365:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2366:             'type'        => $coursetypebuf{$crsid},
                   2367:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2368:         };
1.191     harris41 2369:     }
1.352     www      2370: #
                   2371: # Write course id database (reverse lookup) to homeserver of courses 
                   2372: # Is used in pickcourse
                   2373: #
1.840     albertel 2374:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2375:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2376:                                     $courseidbuffer{$crs_home},
                   2377:                                     $crs_home,'timeonly');
1.352     www      2378:     }
                   2379: #
                   2380: # File accesses
                   2381: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2382: #
1.449     matthew  2383:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2384:         if ($entry =~ /___count$/) {
                   2385:             my ($dom,$name);
1.807     albertel 2386:             ($dom,$name,undef)=
1.811     albertel 2387: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2388:             if (! defined($dom) || $dom eq '' || 
                   2389:                 ! defined($name) || $name eq '') {
1.620     albertel 2390:                 my $cid = $env{'request.course.id'};
                   2391:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2392:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2393:             }
1.450     matthew  2394:             my $value = $accesshash{$entry};
                   2395:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2396:             my %temphash=($url => $value);
1.449     matthew  2397:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2398:             if ($result eq 'ok') {
                   2399:                 delete $accesshash{$entry};
                   2400:             } elsif ($result eq 'unknown_cmd') {
                   2401:                 # Target server has old code running on it.
1.450     matthew  2402:                 my %temphash=($entry => $value);
1.449     matthew  2403:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2404:                     delete $accesshash{$entry};
                   2405:                 }
                   2406:             }
                   2407:         } else {
1.811     albertel 2408:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2409:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2410:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2411:                 delete $accesshash{$entry};
                   2412:             }
1.185     www      2413:         }
1.191     harris41 2414:     }
1.352     www      2415: #
                   2416: # Roles
                   2417: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2418: #
1.800     albertel 2419:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2420:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2421: 	    split(/\:/,$entry);
                   2422:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2423:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2424:                 $rudom,$runame) eq 'ok') {
                   2425: 	    delete $userrolehash{$entry};
                   2426:         }
                   2427:     }
1.662     raeburn  2428: #
                   2429: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2430: #
                   2431:     my %domrolebuffer = ();
                   2432:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2433:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2434:         if ($domrolebuffer{$rudom}) {
                   2435:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2436:                       '='.&escape($domainrolehash{$entry});
                   2437:         } else {
                   2438:             $domrolebuffer{$rudom}.=&escape($entry).
                   2439:                       '='.&escape($domainrolehash{$entry});
                   2440:         }
                   2441:         delete $domainrolehash{$entry};
                   2442:     }
                   2443:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2444: 	my %servers = &get_servers($dom,'library');
                   2445: 	foreach my $tryserver (keys(%servers)) {
                   2446: 	    unless (&reply('domroleput:'.$dom.':'.
                   2447: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2448: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2449: 	    }
1.662     raeburn  2450:         }
                   2451:     }
1.186     www      2452:     $dumpcount++;
1.157     www      2453: }
                   2454: 
                   2455: sub courselog {
                   2456:     my $what=shift;
1.158     www      2457:     $what=time.':'.$what;
1.620     albertel 2458:     unless ($env{'request.course.id'}) { return ''; }
                   2459:     $coursedombuf{$env{'request.course.id'}}=
                   2460:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2461:     $coursenumbuf{$env{'request.course.id'}}=
                   2462:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2463:     $coursehombuf{$env{'request.course.id'}}=
                   2464:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2465:     $coursedescrbuf{$env{'request.course.id'}}=
                   2466:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2467:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2468:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2469:     $courseownerbuf{$env{'request.course.id'}}=
                   2470:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2471:     $coursetypebuf{$env{'request.course.id'}}=
                   2472:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2473:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2474: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2475:     } else {
1.620     albertel 2476: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2477:     }
1.620     albertel 2478:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2479: 	&flushcourselogs();
                   2480:     }
1.158     www      2481: }
                   2482: 
                   2483: sub courseacclog {
                   2484:     my $fnsymb=shift;
1.620     albertel 2485:     unless ($env{'request.course.id'}) { return ''; }
                   2486:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2487:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2488:         $what.=':POST';
1.583     matthew  2489:         # FIXME: Probably ought to escape things....
1.800     albertel 2490: 	foreach my $key (keys(%env)) {
                   2491:             if ($key=~/^form\.(.*)/) {
                   2492: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2493:             }
1.191     harris41 2494:         }
1.583     matthew  2495:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2496:         # FIXME: We should not be depending on a form parameter that someone
                   2497:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2498:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2499:             $what.= ':POST';
                   2500:             # FIXME: Probably ought to escape things....
                   2501:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2502:                                  'crsdiscuss') {
1.620     albertel 2503:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2504:             }
                   2505:         }
1.158     www      2506:     }
                   2507:     &courselog($what);
1.149     www      2508: }
                   2509: 
1.185     www      2510: sub countacc {
                   2511:     my $url=&declutter(shift);
1.458     matthew  2512:     return if (! defined($url) || $url eq '');
1.620     albertel 2513:     unless ($env{'request.course.id'}) { return ''; }
                   2514:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2515:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2516:     $accesshash{$key}++;
1.185     www      2517: }
1.349     www      2518: 
1.361     www      2519: sub linklog {
                   2520:     my ($from,$to)=@_;
                   2521:     $from=&declutter($from);
                   2522:     $to=&declutter($to);
                   2523:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2524:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2525: }
                   2526:   
1.349     www      2527: sub userrolelog {
                   2528:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2529:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2530:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2531:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2532:         ($trole=~/^ta/)) {
1.350     www      2533:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2534:        $userrolehash
                   2535:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2536:                     =$tend.':'.$tstart;
1.662     raeburn  2537:     }
1.898     albertel 2538:     if (($env{'request.role'} =~ /dc\./) &&
                   2539: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2540: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2541: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2542:        $userrolehash
                   2543:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2544:                     =$tend.':'.$tstart;
                   2545:     }
1.662     raeburn  2546:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2547:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2548:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2549:         ($trole=~/^sc/)) {
                   2550:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2551:        $domainrolehash
                   2552:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2553:                     = $tend.':'.$tstart;
                   2554:     }
1.351     www      2555: }
                   2556: 
1.957     raeburn  2557: sub courserolelog {
                   2558:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2559:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2560:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2561:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2562:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2563:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2564:             my $cdom = $1;
                   2565:             my $cnum = $2;
                   2566:             my $sec = $3;
                   2567:             my $namespace = 'rolelog';
                   2568:             my %storehash = (
                   2569:                                role    => $trole,
                   2570:                                start   => $tstart,
                   2571:                                end     => $tend,
                   2572:                                selfenroll => $selfenroll,
                   2573:                                context    => $context,
                   2574:                             );
                   2575:             if ($trole eq 'gr') {
                   2576:                 $namespace = 'groupslog';
                   2577:                 $storehash{'group'} = $sec;
                   2578:             } else {
                   2579:                 $storehash{'section'} = $sec;
                   2580:             }
                   2581:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2582:         }
                   2583:     }
                   2584:     return;
                   2585: }
                   2586: 
1.351     www      2587: sub get_course_adv_roles {
1.948     raeburn  2588:     my ($cid,$codes) = @_;
1.620     albertel 2589:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2590:     my %coursehash=&coursedescription($cid);
1.470     www      2591:     my %nothide=();
1.800     albertel 2592:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2593:         if ($user !~ /:/) {
                   2594: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2595:         } else {
                   2596:             $nothide{$user}=1;
                   2597:         }
1.470     www      2598:     }
1.351     www      2599:     my %returnhash=();
                   2600:     my %dumphash=
                   2601:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2602:     my $now=time;
1.800     albertel 2603:     foreach my $entry (keys %dumphash) {
                   2604: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2605:         if (($tstart) && ($tstart<0)) { next; }
                   2606:         if (($tend) && ($tend<$now)) { next; }
                   2607:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2608:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2609: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2610: 	if ((&privileged($username,$domain)) && 
                   2611: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2612: 	if ($role eq 'cr') { next; }
1.948     raeburn  2613:         if ($codes) {
                   2614:             if ($section) { $role .= ':'.$section; }
                   2615:             if ($returnhash{$role}) {
                   2616:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2617:             } else {
                   2618:                 $returnhash{$role}=$username.':'.$domain;
                   2619:             }
1.351     www      2620:         } else {
1.948     raeburn  2621:             my $key=&plaintext($role);
1.973   ! bisitz   2622:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2623:             if ($returnhash{$key}) {
                   2624: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2625:             } else {
                   2626:                 $returnhash{$key}=$username.':'.$domain;
                   2627:             }
1.351     www      2628:         }
1.948     raeburn  2629:     }
1.400     www      2630:     return %returnhash;
                   2631: }
                   2632: 
                   2633: sub get_my_roles {
1.937     raeburn  2634:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2635:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2636:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2637:     my (%dumphash,%nothide);
1.858     raeburn  2638:     if ($context eq 'userroles') { 
                   2639:         %dumphash = &dump('roles',$udom,$uname);
                   2640:     } else {
                   2641:         %dumphash=
1.400     www      2642:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2643:         if ($hidepriv) {
                   2644:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2645:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2646:                 if ($user !~ /:/) {
                   2647:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2648:                 } else {
                   2649:                     $nothide{$user} = 1;
                   2650:                 }
                   2651:             }
                   2652:         }
1.858     raeburn  2653:     }
1.400     www      2654:     my %returnhash=();
                   2655:     my $now=time;
1.800     albertel 2656:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2657:         my ($role,$tend,$tstart);
                   2658:         if ($context eq 'userroles') {
                   2659: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2660:         } else {
                   2661:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2662:         }
1.400     www      2663:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2664:         my $status = 'active';
1.939     raeburn  2665:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2666:             $status = 'previous';
                   2667:         } 
                   2668:         if (($tstart) && ($now<$tstart)) {
                   2669:             $status = 'future';
                   2670:         }
                   2671:         if (ref($types) eq 'ARRAY') {
                   2672:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2673:                 next;
                   2674:             } 
                   2675:         } else {
                   2676:             if ($status ne 'active') {
                   2677:                 next;
                   2678:             }
                   2679:         }
1.867     raeburn  2680:         my ($rolecode,$username,$domain,$section,$area);
                   2681:         if ($context eq 'userroles') {
                   2682:             ($area,$rolecode) = split(/_/,$entry);
                   2683:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2684:         } else {
                   2685:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2686:         }
1.832     raeburn  2687:         if (ref($roledoms) eq 'ARRAY') {
                   2688:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2689:                 next;
                   2690:             }
                   2691:         }
                   2692:         if (ref($roles) eq 'ARRAY') {
                   2693:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2694:                 if ($role =~ /^cr\//) {
                   2695:                     if (!grep(/^cr$/,@{$roles})) {
                   2696:                         next;
                   2697:                     }
                   2698:                 } else {
                   2699:                     next;
                   2700:                 }
1.832     raeburn  2701:             }
1.867     raeburn  2702:         }
1.937     raeburn  2703:         if ($hidepriv) {
                   2704:             if ((&privileged($username,$domain)) &&
                   2705:                 (!$nothide{$username.':'.$domain})) { 
                   2706:                 next;
                   2707:             }
                   2708:         }
1.933     raeburn  2709:         if ($withsec) {
                   2710:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2711:                 $tstart.':'.$tend;
                   2712:         } else {
                   2713:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2714:         }
1.832     raeburn  2715:     }
1.373     www      2716:     return %returnhash;
1.399     www      2717: }
                   2718: 
                   2719: # ----------------------------------------------------- Frontpage Announcements
                   2720: #
                   2721: #
                   2722: 
                   2723: sub postannounce {
                   2724:     my ($server,$text)=@_;
1.844     albertel 2725:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2726:     unless ($text=~/\w/) { $text=''; }
                   2727:     return &reply('setannounce:'.&escape($text),$server);
                   2728: }
                   2729: 
                   2730: sub getannounce {
1.448     albertel 2731: 
                   2732:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2733: 	my $announcement='';
1.800     albertel 2734: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2735: 	close($fh);
1.399     www      2736: 	if ($announcement=~/\w/) { 
                   2737: 	    return 
                   2738:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2739:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2740: 	} else {
                   2741: 	    return '';
                   2742: 	}
                   2743:     } else {
                   2744: 	return '';
                   2745:     }
1.351     www      2746: }
1.353     www      2747: 
                   2748: # ---------------------------------------------------------- Course ID routines
                   2749: # Deal with domain's nohist_courseid.db files
                   2750: #
                   2751: 
                   2752: sub courseidput {
1.921     raeburn  2753:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2754:     my $outcome;
                   2755:     if ($caller eq 'timeonly') {
                   2756:         my $cids = '';
                   2757:         foreach my $item (keys(%$storehash)) {
                   2758:             $cids.=&escape($item).'&';
                   2759:         }
                   2760:         $cids=~s/\&$//;
                   2761:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2762:                           $coursehome);       
                   2763:     } else {
                   2764:         my $items = '';
                   2765:         foreach my $item (keys(%$storehash)) {
                   2766:             $items.= &escape($item).'='.
                   2767:                      &freeze_escape($$storehash{$item}).'&';
                   2768:         }
                   2769:         $items=~s/\&$//;
                   2770:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2771:                           $coursehome);
1.918     raeburn  2772:     }
                   2773:     if ($outcome eq 'unknown_cmd') {
                   2774:         my $what;
                   2775:         foreach my $cid (keys(%$storehash)) {
                   2776:             $what .= &escape($cid).'=';
1.921     raeburn  2777:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2778:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2779:             }
                   2780:             $what =~ s/\:$/&/;
                   2781:         }
                   2782:         $what =~ s/\&$//;  
                   2783:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2784:     } else {
                   2785:         return $outcome;
                   2786:     }
1.353     www      2787: }
                   2788: 
                   2789: sub courseiddump {
1.921     raeburn  2790:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2791:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2792:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2793:     my $as_hash = 1;
                   2794:     my %returnhash;
                   2795:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2796:     my %libserv = &all_library();
                   2797:     foreach my $tryserver (keys(%libserv)) {
                   2798:         if ( (  $hostidflag == 1 
                   2799: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2800: 	     || (!defined($hostidflag)) ) {
                   2801: 
1.918     raeburn  2802: 	    if (($domfilter eq '') ||
                   2803: 		(&host_domain($tryserver) eq $domfilter)) {
                   2804:                 my $rep = 
                   2805:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2806:                          $sincefilter.':'.&escape($descfilter).':'.
                   2807:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2808:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2809:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2810:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2811:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2812:                 my @pairs=split(/\&/,$rep);
                   2813:                 foreach my $item (@pairs) {
                   2814:                     my ($key,$value)=split(/\=/,$item,2);
                   2815:                     $key = &unescape($key);
                   2816:                     next if ($key =~ /^error: 2 /);
                   2817:                     my $result = &thaw_unescape($value);
                   2818:                     if (ref($result) eq 'HASH') {
                   2819:                         $returnhash{$key}=$result;
                   2820:                     } else {
1.921     raeburn  2821:                         my @responses = split(/:/,$value);
                   2822:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2823:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2824:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2825:                         }
                   2826:                     } 
1.353     www      2827:                 }
                   2828:             }
                   2829:         }
                   2830:     }
                   2831:     return %returnhash;
                   2832: }
                   2833: 
1.658     raeburn  2834: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2835: 
                   2836: sub dcmailput {
1.685     raeburn  2837:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2838:     my $status = &Apache::lonnet::critical(
1.740     www      2839:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2840:        &escape($message),$server);
1.662     raeburn  2841:     return $status;
                   2842: }
                   2843: 
1.658     raeburn  2844: sub dcmaildump {
                   2845:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2846:     my %returnhash=();
1.846     albertel 2847: 
                   2848:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2849:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2850:                                                          &escape($enddate).':';
                   2851: 	my @esc_senders=map { &escape($_)} @$senders;
                   2852: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2853: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2854:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2855:             if (($key) && ($value)) {
                   2856:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2857:             }
                   2858:         }
                   2859:     }
                   2860:     return %returnhash;
                   2861: }
1.662     raeburn  2862: # ---------------------------------------------------------- Domain roles
                   2863: 
                   2864: sub get_domain_roles {
                   2865:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2866:     if (undef($startdate) || $startdate eq '') {
                   2867:         $startdate = '.';
                   2868:     }
                   2869:     if (undef($enddate) || $enddate eq '') {
                   2870:         $enddate = '.';
                   2871:     }
1.922     raeburn  2872:     my $rolelist;
                   2873:     if (ref($roles) eq 'ARRAY') {
                   2874:         $rolelist = join(':',@{$roles});
                   2875:     }
1.662     raeburn  2876:     my %personnel = ();
1.841     albertel 2877: 
                   2878:     my %servers = &get_servers($dom,'library');
                   2879:     foreach my $tryserver (keys(%servers)) {
                   2880: 	%{$personnel{$tryserver}}=();
                   2881: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2882: 					    &escape($startdate).':'.
                   2883: 					    &escape($enddate).':'.
                   2884: 					    &escape($rolelist), $tryserver))) {
                   2885: 	    my ($key,$value) = split(/\=/,$line,2);
                   2886: 	    if (($key) && ($value)) {
                   2887: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2888: 	    }
                   2889: 	}
1.662     raeburn  2890:     }
                   2891:     return %personnel;
                   2892: }
1.658     raeburn  2893: 
1.149     www      2894: # ----------------------------------------------------------- Check out an item
                   2895: 
1.504     albertel 2896: sub get_first_access {
                   2897:     my ($type,$argsymb)=@_;
1.790     albertel 2898:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2899:     if ($argsymb) { $symb=$argsymb; }
                   2900:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2901:     if ($type eq 'course') {
                   2902: 	$res='course';
                   2903:     } elsif ($type eq 'map') {
1.588     albertel 2904: 	$res=&symbread($map);
                   2905:     } else {
                   2906: 	$res=$symb;
                   2907:     }
                   2908:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2909:     return $times{"$courseid\0$res"};
1.504     albertel 2910: }
                   2911: 
                   2912: sub set_first_access {
                   2913:     my ($type)=@_;
1.790     albertel 2914:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2915:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2916:     if ($type eq 'course') {
                   2917: 	$res='course';
                   2918:     } elsif ($type eq 'map') {
1.588     albertel 2919: 	$res=&symbread($map);
                   2920:     } else {
                   2921: 	$res=$symb;
                   2922:     }
                   2923:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2924:     if (!$firstaccess) {
1.588     albertel 2925: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2926:     }
                   2927:     return 'already_set';
1.504     albertel 2928: }
                   2929: 
1.149     www      2930: sub checkout {
                   2931:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2932:     my $now=time;
                   2933:     my $lonhost=$perlvar{'lonHostID'};
                   2934:     my $infostr=&escape(
1.234     www      2935:                  'CHECKOUTTOKEN&'.
1.149     www      2936:                  $tuname.'&'.
                   2937:                  $tudom.'&'.
                   2938:                  $tcrsid.'&'.
                   2939:                  $symb.'&'.
                   2940: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2941:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2942:     if ($token=~/^error\:/) { 
1.672     albertel 2943:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2944:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2945:                  "</font>");
                   2946:         return ''; 
                   2947:     }
                   2948: 
1.149     www      2949:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2950:     $token=~tr/a-z/A-Z/;
                   2951: 
1.153     www      2952:     my %infohash=('resource.0.outtoken' => $token,
                   2953:                   'resource.0.checkouttime' => $now,
                   2954:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2955: 
                   2956:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2957:        return '';
1.151     www      2958:     } else {
1.672     albertel 2959:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2960:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2961:                  "</font>");
1.149     www      2962:     }    
                   2963: 
                   2964:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2965:                          &escape('Checkout '.$infostr.' - '.
                   2966:                                                  $token)) ne 'ok') {
                   2967: 	return '';
1.151     www      2968:     } else {
1.672     albertel 2969:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2970:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2971:                  "</font>");
1.149     www      2972:     }
1.151     www      2973:     return $token;
1.149     www      2974: }
                   2975: 
                   2976: # ------------------------------------------------------------ Check in an item
                   2977: 
                   2978: sub checkin {
                   2979:     my $token=shift;
1.150     www      2980:     my $now=time;
                   2981:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2982:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2983:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2984:     $dtoken=~s/\W/\_/g;
1.234     www      2985:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2986:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2987: 
1.154     www      2988:     unless (($tuname) && ($tudom)) {
                   2989:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2990:         return '';
                   2991:     }
                   2992:     
                   2993:     unless (&allowed('mgr',$tcrsid)) {
                   2994:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2995:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2996:         return '';
                   2997:     }
                   2998: 
1.153     www      2999:     my %infohash=('resource.0.intoken' => $token,
                   3000:                   'resource.0.checkintime' => $now,
                   3001:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3002: 
                   3003:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3004:        return '';
                   3005:     }    
                   3006: 
                   3007:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3008:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3009: 	return '';
                   3010:     }
                   3011: 
                   3012:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3013: }
                   3014: 
                   3015: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3016: 
                   3017: sub expirespread {
                   3018:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3019:     my $cid=$env{'request.course.id'}; 
1.110     www      3020:     if ($cid) {
                   3021:        my $now=time;
                   3022:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3023:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3024:                             $env{'course.'.$cid.'.num'}.
1.110     www      3025: 	        	    ':nohist_expirationdates:'.
                   3026:                             &escape($key).'='.$now,
1.620     albertel 3027:                             $env{'course.'.$cid.'.home'})
1.110     www      3028:     }
                   3029:     return 'ok';
1.14      www      3030: }
                   3031: 
1.109     www      3032: # ----------------------------------------------------- Devalidate Spreadsheets
                   3033: 
                   3034: sub devalidate {
1.325     www      3035:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3036:     my $cid=$env{'request.course.id'}; 
1.109     www      3037:     if ($cid) {
1.391     matthew  3038:         # delete the stored spreadsheets for
                   3039:         # - the student level sheet of this user in course's homespace
                   3040:         # - the assessment level sheet for this resource 
                   3041:         #   for this user in user's homespace
1.553     albertel 3042: 	# - current conditional state info
1.325     www      3043: 	my $key=$uname.':'.$udom.':';
1.109     www      3044:         my $status=
1.299     matthew  3045: 	    &del('nohist_calculatedsheets',
1.391     matthew  3046: 		 [$key.'studentcalc:'],
1.620     albertel 3047: 		 $env{'course.'.$cid.'.domain'},
                   3048: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3049: 		.' '.
                   3050: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3051: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3052:         unless ($status eq 'ok ok') {
                   3053:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3054:                     $uname.' at '.$udom.' for '.
1.109     www      3055: 		    $symb.': '.$status);
1.133     albertel 3056:         }
1.553     albertel 3057: 	&delenv('user.state.'.$cid);
1.109     www      3058:     }
                   3059: }
                   3060: 
1.265     albertel 3061: sub get_scalar {
                   3062:     my ($string,$end) = @_;
                   3063:     my $value;
                   3064:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3065: 	$value = $1;
                   3066:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3067: 	$value = $1;
                   3068:     }
                   3069:     return &unescape($value);
                   3070: }
                   3071: 
                   3072: sub array2str {
                   3073:   my (@array) = @_;
                   3074:   my $result=&arrayref2str(\@array);
                   3075:   $result=~s/^__ARRAY_REF__//;
                   3076:   $result=~s/__END_ARRAY_REF__$//;
                   3077:   return $result;
                   3078: }
                   3079: 
1.204     albertel 3080: sub arrayref2str {
                   3081:   my ($arrayref) = @_;
1.265     albertel 3082:   my $result='__ARRAY_REF__';
1.204     albertel 3083:   foreach my $elem (@$arrayref) {
1.265     albertel 3084:     if(ref($elem) eq 'ARRAY') {
                   3085:       $result.=&arrayref2str($elem).'&';
                   3086:     } elsif(ref($elem) eq 'HASH') {
                   3087:       $result.=&hashref2str($elem).'&';
                   3088:     } elsif(ref($elem)) {
                   3089:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3090:     } else {
                   3091:       $result.=&escape($elem).'&';
                   3092:     }
                   3093:   }
                   3094:   $result=~s/\&$//;
1.265     albertel 3095:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3096:   return $result;
                   3097: }
                   3098: 
1.168     albertel 3099: sub hash2str {
1.204     albertel 3100:   my (%hash) = @_;
                   3101:   my $result=&hashref2str(\%hash);
1.265     albertel 3102:   $result=~s/^__HASH_REF__//;
                   3103:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3104:   return $result;
                   3105: }
                   3106: 
                   3107: sub hashref2str {
                   3108:   my ($hashref)=@_;
1.265     albertel 3109:   my $result='__HASH_REF__';
1.800     albertel 3110:   foreach my $key (sort(keys(%$hashref))) {
                   3111:     if (ref($key) eq 'ARRAY') {
                   3112:       $result.=&arrayref2str($key).'=';
                   3113:     } elsif (ref($key) eq 'HASH') {
                   3114:       $result.=&hashref2str($key).'=';
                   3115:     } elsif (ref($key)) {
1.265     albertel 3116:       $result.='=';
1.800     albertel 3117:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3118:     } else {
1.800     albertel 3119: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3120:     }
                   3121: 
1.800     albertel 3122:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3123:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3124:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3125:       $result.=&hashref2str($hashref->{$key}).'&';
                   3126:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3127:        $result.='&';
1.800     albertel 3128:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3129:     } else {
1.800     albertel 3130:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3131:     }
                   3132:   }
1.168     albertel 3133:   $result=~s/\&$//;
1.265     albertel 3134:   $result .= '__END_HASH_REF__';
1.168     albertel 3135:   return $result;
                   3136: }
                   3137: 
                   3138: sub str2hash {
1.265     albertel 3139:     my ($string)=@_;
                   3140:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3141:     return %$hash;
                   3142: }
                   3143: 
                   3144: sub str2hashref {
1.168     albertel 3145:   my ($string) = @_;
1.265     albertel 3146: 
                   3147:   my %hash;
                   3148: 
                   3149:   if($string !~ /^__HASH_REF__/) {
                   3150:       if (! ($string eq '' || !defined($string))) {
                   3151: 	  $hash{'error'}='Not hash reference';
                   3152:       }
                   3153:       return (\%hash, $string);
                   3154:   }
                   3155: 
                   3156:   $string =~ s/^__HASH_REF__//;
                   3157: 
                   3158:   while($string !~ /^__END_HASH_REF__/) {
                   3159:       #key
                   3160:       my $key='';
                   3161:       if($string =~ /^__HASH_REF__/) {
                   3162:           ($key, $string)=&str2hashref($string);
                   3163:           if(defined($key->{'error'})) {
                   3164:               $hash{'error'}='Bad data';
                   3165:               return (\%hash, $string);
                   3166:           }
                   3167:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3168:           ($key, $string)=&str2arrayref($string);
                   3169:           if($key->[0] eq 'Array reference error') {
                   3170:               $hash{'error'}='Bad data';
                   3171:               return (\%hash, $string);
                   3172:           }
                   3173:       } else {
                   3174:           $string =~ s/^(.*?)=//;
1.267     albertel 3175: 	  $key=&unescape($1);
1.265     albertel 3176:       }
                   3177:       $string =~ s/^=//;
                   3178: 
                   3179:       #value
                   3180:       my $value='';
                   3181:       if($string =~ /^__HASH_REF__/) {
                   3182:           ($value, $string)=&str2hashref($string);
                   3183:           if(defined($value->{'error'})) {
                   3184:               $hash{'error'}='Bad data';
                   3185:               return (\%hash, $string);
                   3186:           }
                   3187:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3188:           ($value, $string)=&str2arrayref($string);
                   3189:           if($value->[0] eq 'Array reference error') {
                   3190:               $hash{'error'}='Bad data';
                   3191:               return (\%hash, $string);
                   3192:           }
                   3193:       } else {
                   3194: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3195:       }
                   3196:       $string =~ s/^&//;
                   3197: 
                   3198:       $hash{$key}=$value;
1.204     albertel 3199:   }
1.265     albertel 3200: 
                   3201:   $string =~ s/^__END_HASH_REF__//;
                   3202: 
                   3203:   return (\%hash, $string);
1.204     albertel 3204: }
                   3205: 
                   3206: sub str2array {
1.265     albertel 3207:     my ($string)=@_;
                   3208:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3209:     return @$array;
                   3210: }
                   3211: 
                   3212: sub str2arrayref {
1.204     albertel 3213:   my ($string) = @_;
1.265     albertel 3214:   my @array;
                   3215: 
                   3216:   if($string !~ /^__ARRAY_REF__/) {
                   3217:       if (! ($string eq '' || !defined($string))) {
                   3218: 	  $array[0]='Array reference error';
                   3219:       }
                   3220:       return (\@array, $string);
                   3221:   }
                   3222: 
                   3223:   $string =~ s/^__ARRAY_REF__//;
                   3224: 
                   3225:   while($string !~ /^__END_ARRAY_REF__/) {
                   3226:       my $value='';
                   3227:       if($string =~ /^__HASH_REF__/) {
                   3228:           ($value, $string)=&str2hashref($string);
                   3229:           if(defined($value->{'error'})) {
                   3230:               $array[0] ='Array reference error';
                   3231:               return (\@array, $string);
                   3232:           }
                   3233:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3234:           ($value, $string)=&str2arrayref($string);
                   3235:           if($value->[0] eq 'Array reference error') {
                   3236:               $array[0] ='Array reference error';
                   3237:               return (\@array, $string);
                   3238:           }
                   3239:       } else {
                   3240: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3241:       }
                   3242:       $string =~ s/^&//;
                   3243: 
                   3244:       push(@array, $value);
1.191     harris41 3245:   }
1.265     albertel 3246: 
                   3247:   $string =~ s/^__END_ARRAY_REF__//;
                   3248: 
                   3249:   return (\@array, $string);
1.168     albertel 3250: }
                   3251: 
1.167     albertel 3252: # -------------------------------------------------------------------Temp Store
                   3253: 
1.168     albertel 3254: sub tmpreset {
                   3255:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3256:   if (!$symb) {
                   3257:     $symb=&symbread();
1.620     albertel 3258:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3259:   }
                   3260:   $symb=escape($symb);
                   3261: 
1.620     albertel 3262:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3263:   $namespace=~s/\//\_/g;
                   3264:   $namespace=~s/\W//g;
                   3265: 
1.620     albertel 3266:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3267:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3268:   if ($domain eq 'public' && $stuname eq 'public') {
                   3269:       $stuname=$ENV{'REMOTE_ADDR'};
                   3270:   }
1.168     albertel 3271:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3272:   my %hash;
                   3273:   if (tie(%hash,'GDBM_File',
                   3274: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3275: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3276:     foreach my $key (keys %hash) {
1.180     albertel 3277:       if ($key=~ /:$symb/) {
1.168     albertel 3278: 	delete($hash{$key});
                   3279:       }
                   3280:     }
                   3281:   }
                   3282: }
                   3283: 
1.167     albertel 3284: sub tmpstore {
1.168     albertel 3285:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3286: 
                   3287:   if (!$symb) {
                   3288:     $symb=&symbread();
1.620     albertel 3289:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3290:   }
                   3291:   $symb=escape($symb);
                   3292: 
                   3293:   if (!$namespace) {
                   3294:     # I don't think we would ever want to store this for a course.
                   3295:     # it seems this will only be used if we don't have a course.
1.620     albertel 3296:     #$namespace=$env{'request.course.id'};
1.168     albertel 3297:     #if (!$namespace) {
1.620     albertel 3298:       $namespace=$env{'request.state'};
1.168     albertel 3299:     #}
                   3300:   }
                   3301:   $namespace=~s/\//\_/g;
                   3302:   $namespace=~s/\W//g;
1.620     albertel 3303:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3304:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3305:   if ($domain eq 'public' && $stuname eq 'public') {
                   3306:       $stuname=$ENV{'REMOTE_ADDR'};
                   3307:   }
1.168     albertel 3308:   my $now=time;
                   3309:   my %hash;
                   3310:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3311:   if (tie(%hash,'GDBM_File',
                   3312: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3313: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3314:     $hash{"version:$symb"}++;
                   3315:     my $version=$hash{"version:$symb"};
                   3316:     my $allkeys=''; 
                   3317:     foreach my $key (keys(%$storehash)) {
                   3318:       $allkeys.=$key.':';
1.591     albertel 3319:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3320:     }
                   3321:     $hash{"$version:$symb:timestamp"}=$now;
                   3322:     $allkeys.='timestamp';
                   3323:     $hash{"$version:keys:$symb"}=$allkeys;
                   3324:     if (untie(%hash)) {
                   3325:       return 'ok';
                   3326:     } else {
                   3327:       return "error:$!";
                   3328:     }
                   3329:   } else {
                   3330:     return "error:$!";
                   3331:   }
                   3332: }
1.167     albertel 3333: 
1.168     albertel 3334: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3335: 
1.168     albertel 3336: sub tmprestore {
                   3337:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3338: 
1.168     albertel 3339:   if (!$symb) {
                   3340:     $symb=&symbread();
1.620     albertel 3341:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3342:   }
                   3343:   $symb=escape($symb);
                   3344: 
1.620     albertel 3345:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3346: 
1.620     albertel 3347:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3348:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3349:   if ($domain eq 'public' && $stuname eq 'public') {
                   3350:       $stuname=$ENV{'REMOTE_ADDR'};
                   3351:   }
1.168     albertel 3352:   my %returnhash;
                   3353:   $namespace=~s/\//\_/g;
                   3354:   $namespace=~s/\W//g;
                   3355:   my %hash;
                   3356:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3357:   if (tie(%hash,'GDBM_File',
                   3358: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3359: 	  &GDBM_READER(),0640)) {
1.168     albertel 3360:     my $version=$hash{"version:$symb"};
                   3361:     $returnhash{'version'}=$version;
                   3362:     my $scope;
                   3363:     for ($scope=1;$scope<=$version;$scope++) {
                   3364:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3365:       my @keys=split(/:/,$vkeys);
                   3366:       my $key;
                   3367:       $returnhash{"$scope:keys"}=$vkeys;
                   3368:       foreach $key (@keys) {
1.591     albertel 3369: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3370: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3371:       }
                   3372:     }
1.168     albertel 3373:     if (!(untie(%hash))) {
                   3374:       return "error:$!";
                   3375:     }
                   3376:   } else {
                   3377:     return "error:$!";
                   3378:   }
                   3379:   return %returnhash;
1.167     albertel 3380: }
                   3381: 
1.9       www      3382: # ----------------------------------------------------------------------- Store
                   3383: 
                   3384: sub store {
1.124     www      3385:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3386:     my $home='';
                   3387: 
1.168     albertel 3388:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3389: 
1.213     www      3390:     $symb=&symbclean($symb);
1.122     albertel 3391:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3392: 
1.620     albertel 3393:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3394:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3395: 
                   3396:     &devalidate($symb,$stuname,$domain);
1.109     www      3397: 
                   3398:     $symb=escape($symb);
1.187     www      3399:     if (!$namespace) { 
1.620     albertel 3400:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3401:           return ''; 
                   3402:        } 
                   3403:     }
1.620     albertel 3404:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3405: 
                   3406:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3407:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3408: 
1.12      www      3409:     my $namevalue='';
1.800     albertel 3410:     foreach my $key (keys(%$storehash)) {
                   3411:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3412:     }
1.12      www      3413:     $namevalue=~s/\&$//;
1.187     www      3414:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3415:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3416: }
                   3417: 
1.47      www      3418: # -------------------------------------------------------------- Critical Store
                   3419: 
                   3420: sub cstore {
1.124     www      3421:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3422:     my $home='';
                   3423: 
1.168     albertel 3424:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3425: 
1.213     www      3426:     $symb=&symbclean($symb);
1.122     albertel 3427:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3428: 
1.620     albertel 3429:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3430:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3431: 
                   3432:     &devalidate($symb,$stuname,$domain);
1.109     www      3433: 
                   3434:     $symb=escape($symb);
1.187     www      3435:     if (!$namespace) { 
1.620     albertel 3436:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3437:           return ''; 
                   3438:        } 
                   3439:     }
1.620     albertel 3440:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3441: 
                   3442:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3443:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3444: 
1.47      www      3445:     my $namevalue='';
1.800     albertel 3446:     foreach my $key (keys(%$storehash)) {
                   3447:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3448:     }
1.47      www      3449:     $namevalue=~s/\&$//;
1.187     www      3450:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3451:     return critical
                   3452:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3453: }
                   3454: 
1.9       www      3455: # --------------------------------------------------------------------- Restore
                   3456: 
                   3457: sub restore {
1.124     www      3458:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3459:     my $home='';
                   3460: 
1.168     albertel 3461:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3462: 
1.122     albertel 3463:     if (!$symb) {
                   3464:       unless ($symb=escape(&symbread())) { return ''; }
                   3465:     } else {
1.213     www      3466:       $symb=&escape(&symbclean($symb));
1.122     albertel 3467:     }
1.188     www      3468:     if (!$namespace) { 
1.620     albertel 3469:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3470:           return ''; 
                   3471:        } 
                   3472:     }
1.620     albertel 3473:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3474:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3475:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3476:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3477: 
1.12      www      3478:     my %returnhash=();
1.800     albertel 3479:     foreach my $line (split(/\&/,$answer)) {
                   3480: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3481:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3482:     }
1.75      www      3483:     my $version;
                   3484:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3485:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3486:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3487:        }
1.75      www      3488:     }
1.13      www      3489:     return %returnhash;
1.34      www      3490: }
                   3491: 
                   3492: # ---------------------------------------------------------- Course Description
                   3493: 
                   3494: sub coursedescription {
1.731     albertel 3495:     my ($courseid,$args)=@_;
1.34      www      3496:     $courseid=~s/^\///;
1.49      www      3497:     $courseid=~s/\_/\//g;
1.34      www      3498:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3499:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3500:     my $normalid=$cdomain.'_'.$cnum;
                   3501:     # need to always cache even if we get errors otherwise we keep 
                   3502:     # trying and trying and trying to get the course description.
                   3503:     my %envhash=();
                   3504:     my %returnhash=();
1.731     albertel 3505:     
                   3506:     my $expiretime=600;
                   3507:     if ($env{'request.course.id'} eq $normalid) {
                   3508: 	$expiretime=120;
                   3509:     }
                   3510: 
                   3511:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3512:     if (!$args->{'freshen_cache'}
                   3513: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3514: 	foreach my $key (keys(%env)) {
                   3515: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3516: 	    my ($setting) = $1;
                   3517: 	    $returnhash{$setting} = $env{$key};
                   3518: 	}
                   3519: 	return %returnhash;
                   3520:     }
                   3521: 
                   3522:     # get the data agin
                   3523:     if (!$args->{'one_time'}) {
                   3524: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3525:     }
1.811     albertel 3526: 
1.34      www      3527:     if ($chome ne 'no_host') {
1.302     albertel 3528:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3529:        if (!exists($returnhash{'con_lost'})) {
                   3530:            $returnhash{'home'}= $chome;
                   3531: 	   $returnhash{'domain'} = $cdomain;
                   3532: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3533:            if (!defined($returnhash{'type'})) {
                   3534:                $returnhash{'type'} = 'Course';
                   3535:            }
1.130     albertel 3536:            while (my ($name,$value) = each %returnhash) {
1.53      www      3537:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3538:            }
1.270     www      3539:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3540:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3541: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3542:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3543:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3544:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3545:        }
                   3546:     }
1.731     albertel 3547:     if (!$args->{'one_time'}) {
1.949     raeburn  3548: 	&appenv(\%envhash);
1.731     albertel 3549:     }
1.302     albertel 3550:     return %returnhash;
1.461     www      3551: }
                   3552: 
                   3553: # -------------------------------------------------See if a user is privileged
                   3554: 
                   3555: sub privileged {
                   3556:     my ($username,$domain)=@_;
                   3557:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3558: 			&homeserver($username,$domain));
                   3559:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3560:     my $now=time;
                   3561:     if ($rolesdump ne '') {
1.800     albertel 3562:         foreach my $entry (split(/&/,$rolesdump)) {
                   3563: 	    if ($entry!~/^rolesdef_/) {
                   3564: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3565: 		$area=~s/\_\w\w$//;
                   3566: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3567: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3568: 		    my $active=1;
                   3569: 		    if ($tend) {
                   3570: 			if ($tend<$now) { $active=0; }
                   3571: 		    }
                   3572: 		    if ($tstart) {
                   3573: 			if ($tstart>$now) { $active=0; }
                   3574: 		    }
                   3575: 		    if ($active) { return 1; }
                   3576: 		}
                   3577: 	    }
                   3578: 	}
                   3579:     }
                   3580:     return 0;
1.9       www      3581: }
1.1       albertel 3582: 
1.103     harris41 3583: # -------------------------------------------------------- Get user privileges
1.11      www      3584: 
                   3585: sub rolesinit {
                   3586:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3587:     my %userroles;
1.11      www      3588:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3589:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3590:     my %allroles=();
1.678     raeburn  3591:     my %allgroups=();   
1.11      www      3592:     my $now=time;
1.966     raeburn  3593:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3594:     my $group_privs;
1.11      www      3595: 
                   3596:     if ($rolesdump ne '') {
1.800     albertel 3597:         foreach my $entry (split(/&/,$rolesdump)) {
                   3598: 	  if ($entry!~/^rolesdef_/) {
                   3599:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3600: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3601:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3602: 	    if ($role=~/^cr/) { 
1.807     albertel 3603: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3604: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3605: 		    ($tend,$tstart)=split('_',$trest);
                   3606: 		} else {
                   3607: 		    $trole=$role;
                   3608: 		}
1.678     raeburn  3609:             } elsif ($role =~ m|^gr/|) {
                   3610:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3611:                 ($trole,$group_privs) = split(/\//,$trole);
                   3612:                 $group_privs = &unescape($group_privs);
1.587     albertel 3613: 	    } else {
                   3614: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3615: 	    }
1.743     albertel 3616: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3617: 					 $username);
                   3618: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3619:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3620:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3621:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3622: 		my $spec=$trole.'.'.$area;
                   3623: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3624: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3625:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3626:                 } elsif ($trole eq 'gr') {
                   3627:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3628: 		} else {
1.567     raeburn  3629:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3630: 		}
1.12      www      3631:             }
1.662     raeburn  3632:           }
1.191     harris41 3633:         }
1.743     albertel 3634:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3635:         $userroles{'user.adv'}    = $adv;
                   3636: 	$userroles{'user.author'} = $author;
1.620     albertel 3637:         $env{'user.adv'}=$adv;
1.11      www      3638:     }
1.743     albertel 3639:     return \%userroles;  
1.11      www      3640: }
                   3641: 
1.567     raeburn  3642: sub set_arearole {
                   3643:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3644: # log the associated role with the area
                   3645:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3646:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3647: }
                   3648: 
                   3649: sub custom_roleprivs {
                   3650:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3651:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3652:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3653:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3654:         my ($rdummy,$roledef)=
                   3655:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3656:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3657:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3658:             if (defined($syspriv)) {
                   3659:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3660:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3661:             }
                   3662:             if ($tdomain ne '') {
                   3663:                 if (defined($dompriv)) {
                   3664:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3665:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3666:                 }
                   3667:                 if (($trest ne '') && (defined($coursepriv))) {
                   3668:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3669:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3670:                 }
                   3671:             }
                   3672:         }
                   3673:     }
                   3674: }
                   3675: 
1.678     raeburn  3676: sub group_roleprivs {
                   3677:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3678:     my $access = 1;
                   3679:     my $now = time;
                   3680:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3681:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3682:     if ($access) {
1.811     albertel 3683:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3684:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3685:     }
                   3686: }
1.567     raeburn  3687: 
                   3688: sub standard_roleprivs {
                   3689:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3690:     if (defined($pr{$trole.':s'})) {
                   3691:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3692:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3693:     }
                   3694:     if ($tdomain ne '') {
                   3695:         if (defined($pr{$trole.':d'})) {
                   3696:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3697:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3698:         }
                   3699:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3700:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3701:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3702:         }
                   3703:     }
                   3704: }
                   3705: 
                   3706: sub set_userprivs {
1.678     raeburn  3707:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3708:     my $author=0;
                   3709:     my $adv=0;
1.678     raeburn  3710:     my %grouproles = ();
                   3711:     if (keys(%{$allgroups}) > 0) {
                   3712:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3713:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3714:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3715:                 $trole = $1;
                   3716:                 $area = $2;
1.681     raeburn  3717:                 $sec = $3;
                   3718:                 $extendedarea = $area.$sec;
                   3719:                 if (exists($$allgroups{$area})) {
                   3720:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3721:                         my $spec = $trole.'.'.$extendedarea;
                   3722:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3723:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3724:                     }
                   3725:                 }
                   3726:             }
                   3727:         }
                   3728:     }
1.800     albertel 3729:     foreach my $group (keys(%grouproles)) {
                   3730:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3731:     }
1.800     albertel 3732:     foreach my $role (keys(%{$allroles})) {
                   3733:         my %thesepriv;
1.941     raeburn  3734:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3735:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3736:             if ($item ne '') {
                   3737:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3738:                 if ($restrictions eq '') {
                   3739:                     $thesepriv{$privilege}='F';
                   3740:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3741:                     $thesepriv{$privilege}.=$restrictions;
                   3742:                 }
                   3743:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3744:             }
                   3745:         }
                   3746:         my $thesestr='';
1.800     albertel 3747:         foreach my $priv (keys(%thesepriv)) {
                   3748: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3749: 	}
                   3750:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3751:     }
                   3752:     return ($author,$adv);
                   3753: }
                   3754: 
1.12      www      3755: # --------------------------------------------------------------- get interface
                   3756: 
                   3757: sub get {
1.131     albertel 3758:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3759:    my $items='';
1.800     albertel 3760:    foreach my $item (@$storearr) {
                   3761:        $items.=&escape($item).'&';
1.191     harris41 3762:    }
1.12      www      3763:    $items=~s/\&$//;
1.620     albertel 3764:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3765:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3766:    my $uhome=&homeserver($uname,$udomain);
                   3767: 
1.133     albertel 3768:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3769:    my @pairs=split(/\&/,$rep);
1.273     albertel 3770:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3771:      return @pairs;
                   3772:    }
1.15      www      3773:    my %returnhash=();
1.42      www      3774:    my $i=0;
1.800     albertel 3775:    foreach my $item (@$storearr) {
                   3776:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3777:       $i++;
1.191     harris41 3778:    }
1.15      www      3779:    return %returnhash;
1.27      www      3780: }
                   3781: 
                   3782: # --------------------------------------------------------------- del interface
                   3783: 
                   3784: sub del {
1.133     albertel 3785:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3786:    my $items='';
1.800     albertel 3787:    foreach my $item (@$storearr) {
                   3788:        $items.=&escape($item).'&';
1.191     harris41 3789:    }
1.27      www      3790:    $items=~s/\&$//;
1.620     albertel 3791:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3792:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3793:    my $uhome=&homeserver($uname,$udomain);
                   3794: 
                   3795:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3796: }
                   3797: 
                   3798: # -------------------------------------------------------------- dump interface
                   3799: 
                   3800: sub dump {
1.755     albertel 3801:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3802:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3803:     if (!$uname) { $uname=$env{'user.name'}; }
                   3804:     my $uhome=&homeserver($uname,$udomain);
                   3805:     if ($regexp) {
                   3806: 	$regexp=&escape($regexp);
                   3807:     } else {
                   3808: 	$regexp='.';
                   3809:     }
                   3810:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3811:     my @pairs=split(/\&/,$rep);
                   3812:     my %returnhash=();
                   3813:     foreach my $item (@pairs) {
                   3814: 	my ($key,$value)=split(/=/,$item,2);
                   3815: 	$key = &unescape($key);
                   3816: 	next if ($key =~ /^error: 2 /);
                   3817: 	$returnhash{$key}=&thaw_unescape($value);
                   3818:     }
                   3819:     return %returnhash;
1.407     www      3820: }
                   3821: 
1.717     albertel 3822: # --------------------------------------------------------- dumpstore interface
                   3823: 
                   3824: sub dumpstore {
                   3825:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3826:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3827:    if (!$uname) { $uname=$env{'user.name'}; }
                   3828:    my $uhome=&homeserver($uname,$udomain);
                   3829:    if ($regexp) {
                   3830:        $regexp=&escape($regexp);
                   3831:    } else {
                   3832:        $regexp='.';
                   3833:    }
                   3834:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3835:    my @pairs=split(/\&/,$rep);
                   3836:    my %returnhash=();
                   3837:    foreach my $item (@pairs) {
                   3838:        my ($key,$value)=split(/=/,$item,2);
                   3839:        next if ($key =~ /^error: 2 /);
                   3840:        $returnhash{$key}=&thaw_unescape($value);
                   3841:    }
                   3842:    return %returnhash;
1.717     albertel 3843: }
                   3844: 
1.407     www      3845: # -------------------------------------------------------------- keys interface
                   3846: 
                   3847: sub getkeys {
                   3848:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3850:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3851:    my $uhome=&homeserver($uname,$udomain);
                   3852:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3853:    my @keyarray=();
1.800     albertel 3854:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3855:       next if ($key =~ /^error: 2 /);
1.800     albertel 3856:       push(@keyarray,&unescape($key));
1.407     www      3857:    }
                   3858:    return @keyarray;
1.318     matthew  3859: }
                   3860: 
1.319     matthew  3861: # --------------------------------------------------------------- currentdump
                   3862: sub currentdump {
1.328     matthew  3863:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3864:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3865:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3866:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3867:    my $uhome = &homeserver($sname,$sdom);
                   3868:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3869:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3870:    #
1.318     matthew  3871:    my %returnhash=();
1.319     matthew  3872:    #
                   3873:    if ($rep eq "unknown_cmd") { 
                   3874:        # an old lond will not know currentdump
                   3875:        # Do a dump and make it look like a currentdump
1.822     albertel 3876:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3877:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3878:        my %hash = @tmp;
                   3879:        @tmp=();
1.424     matthew  3880:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3881:    } else {
                   3882:        my @pairs=split(/\&/,$rep);
1.800     albertel 3883:        foreach my $pair (@pairs) {
                   3884:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3885:            my ($symb,$param) = split(/:/,$key);
                   3886:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3887:                                                         &thaw_unescape($value);
1.319     matthew  3888:        }
1.191     harris41 3889:    }
1.12      www      3890:    return %returnhash;
1.424     matthew  3891: }
                   3892: 
                   3893: sub convert_dump_to_currentdump{
                   3894:     my %hash = %{shift()};
                   3895:     my %returnhash;
                   3896:     # Code ripped from lond, essentially.  The only difference
                   3897:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3898:     # we might run in to problems with parameter names =~ /^v\./
                   3899:     while (my ($key,$value) = each(%hash)) {
                   3900:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3901: 	$symb  = &unescape($symb);
                   3902: 	$param = &unescape($param);
1.424     matthew  3903:         next if ($v eq 'version' || $symb eq 'keys');
                   3904:         next if (exists($returnhash{$symb}) &&
                   3905:                  exists($returnhash{$symb}->{$param}) &&
                   3906:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3907:         $returnhash{$symb}->{$param}=$value;
                   3908:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3909:     }
                   3910:     #
                   3911:     # Remove all of the keys in the hashes which keep track of
                   3912:     # the version of the parameter.
                   3913:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3914:         # use a foreach because we are going to delete from the hash.
                   3915:         foreach my $key (keys(%$param_hash)) {
                   3916:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3917:         }
                   3918:     }
                   3919:     return \%returnhash;
1.12      www      3920: }
                   3921: 
1.627     albertel 3922: # ------------------------------------------------------ critical inc interface
                   3923: 
                   3924: sub cinc {
                   3925:     return &inc(@_,'critical');
                   3926: }
                   3927: 
1.449     matthew  3928: # --------------------------------------------------------------- inc interface
                   3929: 
                   3930: sub inc {
1.627     albertel 3931:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3932:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3933:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3934:     my $uhome=&homeserver($uname,$udomain);
                   3935:     my $items='';
                   3936:     if (! ref($store)) {
                   3937:         # got a single value, so use that instead
                   3938:         $items = &escape($store).'=&';
                   3939:     } elsif (ref($store) eq 'SCALAR') {
                   3940:         $items = &escape($$store).'=&';        
                   3941:     } elsif (ref($store) eq 'ARRAY') {
                   3942:         $items = join('=&',map {&escape($_);} @{$store});
                   3943:     } elsif (ref($store) eq 'HASH') {
                   3944:         while (my($key,$value) = each(%{$store})) {
                   3945:             $items.= &escape($key).'='.&escape($value).'&';
                   3946:         }
                   3947:     }
                   3948:     $items=~s/\&$//;
1.627     albertel 3949:     if ($critical) {
                   3950: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3951:     } else {
                   3952: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3953:     }
1.449     matthew  3954: }
                   3955: 
1.12      www      3956: # --------------------------------------------------------------- put interface
                   3957: 
                   3958: sub put {
1.134     albertel 3959:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3960:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3961:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3962:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3963:    my $items='';
1.800     albertel 3964:    foreach my $item (keys(%$storehash)) {
                   3965:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3966:    }
1.12      www      3967:    $items=~s/\&$//;
1.134     albertel 3968:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3969: }
                   3970: 
1.631     albertel 3971: # ------------------------------------------------------------ newput interface
                   3972: 
                   3973: sub newput {
                   3974:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3975:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3976:    if (!$uname) { $uname=$env{'user.name'}; }
                   3977:    my $uhome=&homeserver($uname,$udomain);
                   3978:    my $items='';
                   3979:    foreach my $key (keys(%$storehash)) {
                   3980:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3981:    }
                   3982:    $items=~s/\&$//;
                   3983:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3984: }
                   3985: 
                   3986: # ---------------------------------------------------------  putstore interface
                   3987: 
1.524     raeburn  3988: sub putstore {
1.715     albertel 3989:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3990:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3991:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3992:    my $uhome=&homeserver($uname,$udomain);
                   3993:    my $items='';
1.715     albertel 3994:    foreach my $key (keys(%$storehash)) {
                   3995:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3996:    }
1.715     albertel 3997:    $items=~s/\&$//;
1.716     albertel 3998:    my $esc_symb=&escape($symb);
                   3999:    my $esc_v=&escape($version);
1.715     albertel 4000:    my $reply =
1.716     albertel 4001:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4002: 	      $uhome);
                   4003:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4004:        # gfall back to way things use to be done
1.715     albertel 4005:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4006: 			    $uname);
1.524     raeburn  4007:    }
1.715     albertel 4008:    return $reply;
                   4009: }
                   4010: 
                   4011: sub old_putstore {
1.716     albertel 4012:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4013:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4014:     if (!$uname) { $uname=$env{'user.name'}; }
                   4015:     my $uhome=&homeserver($uname,$udomain);
                   4016:     my %newstorehash;
1.800     albertel 4017:     foreach my $item (keys(%$storehash)) {
                   4018: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4019: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4020:     }
                   4021:     my $items='';
                   4022:     my %allitems = ();
1.800     albertel 4023:     foreach my $item (keys(%newstorehash)) {
                   4024: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4025: 	    my $key = $1.':keys:'.$2;
                   4026: 	    $allitems{$key} .= $3.':';
                   4027: 	}
1.800     albertel 4028: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4029:     }
1.800     albertel 4030:     foreach my $item (keys(%allitems)) {
                   4031: 	$allitems{$item} =~ s/\:$//;
                   4032: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4033:     }
                   4034:     $items=~s/\&$//;
                   4035:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4036: }
                   4037: 
1.47      www      4038: # ------------------------------------------------------ critical put interface
                   4039: 
                   4040: sub cput {
1.134     albertel 4041:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4042:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4043:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4044:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4045:    my $items='';
1.800     albertel 4046:    foreach my $item (keys(%$storehash)) {
                   4047:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4048:    }
1.47      www      4049:    $items=~s/\&$//;
1.134     albertel 4050:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4051: }
                   4052: 
                   4053: # -------------------------------------------------------------- eget interface
                   4054: 
                   4055: sub eget {
1.133     albertel 4056:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4057:    my $items='';
1.800     albertel 4058:    foreach my $item (@$storearr) {
                   4059:        $items.=&escape($item).'&';
1.191     harris41 4060:    }
1.12      www      4061:    $items=~s/\&$//;
1.620     albertel 4062:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4063:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4064:    my $uhome=&homeserver($uname,$udomain);
                   4065:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4066:    my @pairs=split(/\&/,$rep);
                   4067:    my %returnhash=();
1.42      www      4068:    my $i=0;
1.800     albertel 4069:    foreach my $item (@$storearr) {
                   4070:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4071:       $i++;
1.191     harris41 4072:    }
1.12      www      4073:    return %returnhash;
                   4074: }
                   4075: 
1.667     albertel 4076: # ------------------------------------------------------------ tmpput interface
                   4077: sub tmpput {
1.802     raeburn  4078:     my ($storehash,$server,$context)=@_;
1.667     albertel 4079:     my $items='';
1.800     albertel 4080:     foreach my $item (keys(%$storehash)) {
                   4081: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4082:     }
                   4083:     $items=~s/\&$//;
1.802     raeburn  4084:     if (defined($context)) {
                   4085:         $items .= ':'.&escape($context);
                   4086:     }
1.667     albertel 4087:     return &reply("tmpput:$items",$server);
                   4088: }
                   4089: 
                   4090: # ------------------------------------------------------------ tmpget interface
                   4091: sub tmpget {
1.688     albertel 4092:     my ($token,$server)=@_;
                   4093:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4094:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4095:     my %returnhash;
                   4096:     foreach my $item (split(/\&/,$rep)) {
                   4097: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4098:         next if ($key =~ /^error: 2 /);
1.667     albertel 4099: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4100:     }
                   4101:     return %returnhash;
                   4102: }
                   4103: 
1.688     albertel 4104: # ------------------------------------------------------------ tmpget interface
                   4105: sub tmpdel {
                   4106:     my ($token,$server)=@_;
                   4107:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4108:     return &reply("tmpdel:$token",$server);
                   4109: }
                   4110: 
1.765     albertel 4111: # -------------------------------------------------- portfolio access checking
                   4112: 
                   4113: sub portfolio_access {
1.766     albertel 4114:     my ($requrl) = @_;
1.765     albertel 4115:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4116:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4117:     if ($result) {
                   4118:         my %setters;
                   4119:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4120:             my ($startblock,$endblock) =
                   4121:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4122:             if ($startblock && $endblock) {
                   4123:                 return 'B';
                   4124:             }
                   4125:         } else {
                   4126:             my ($startblock,$endblock) =
                   4127:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4128:             if ($startblock && $endblock) {
                   4129:                 return 'B';
                   4130:             }
                   4131:         }
                   4132:     }
1.765     albertel 4133:     if ($result eq 'ok') {
1.766     albertel 4134:        return 'F';
1.765     albertel 4135:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4136:        return 'A';
1.765     albertel 4137:     }
1.766     albertel 4138:     return '';
1.765     albertel 4139: }
                   4140: 
                   4141: sub get_portfolio_access {
1.767     albertel 4142:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4143: 
                   4144:     if (!ref($access_hash)) {
                   4145: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4146: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4147: 						   $file_name);
                   4148: 	$access_hash = $access_controls{$file_name};
                   4149:     }
                   4150: 
1.765     albertel 4151:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4152:     my $now = time;
                   4153:     if (ref($access_hash) eq 'HASH') {
                   4154:         foreach my $key (keys(%{$access_hash})) {
                   4155:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4156:             if ($start > $now) {
                   4157:                 next;
                   4158:             }
                   4159:             if ($end && $end<$now) {
                   4160:                 next;
                   4161:             }
                   4162:             if ($scope eq 'public') {
                   4163:                 $public = $key;
                   4164:                 last;
                   4165:             } elsif ($scope eq 'guest') {
                   4166:                 $guest = $key;
                   4167:             } elsif ($scope eq 'domains') {
                   4168:                 push(@domains,$key);
                   4169:             } elsif ($scope eq 'users') {
                   4170:                 push(@users,$key);
                   4171:             } elsif ($scope eq 'course') {
                   4172:                 push(@courses,$key);
                   4173:             } elsif ($scope eq 'group') {
                   4174:                 push(@groups,$key);
                   4175:             }
                   4176:         }
                   4177:         if ($public) {
                   4178:             return 'ok';
                   4179:         }
                   4180:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4181:             if ($guest) {
                   4182:                 return $guest;
                   4183:             }
                   4184:         } else {
                   4185:             if (@domains > 0) {
                   4186:                 foreach my $domkey (@domains) {
                   4187:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4188:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4189:                             return 'ok';
                   4190:                         }
                   4191:                     }
                   4192:                 }
                   4193:             }
                   4194:             if (@users > 0) {
                   4195:                 foreach my $userkey (@users) {
1.865     raeburn  4196:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4197:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4198:                             if (ref($item) eq 'HASH') {
                   4199:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4200:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4201:                                     return 'ok';
                   4202:                                 }
                   4203:                             }
                   4204:                         }
                   4205:                     } 
1.765     albertel 4206:                 }
                   4207:             }
                   4208:             my %roleshash;
                   4209:             my @courses_and_groups = @courses;
                   4210:             push(@courses_and_groups,@groups); 
                   4211:             if (@courses_and_groups > 0) {
                   4212:                 my (%allgroups,%allroles); 
                   4213:                 my ($start,$end,$role,$sec,$group);
                   4214:                 foreach my $envkey (%env) {
1.811     albertel 4215:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4216:                         my $cid = $2.'_'.$3; 
                   4217:                         if ($1 eq 'gr') {
                   4218:                             $group = $4;
                   4219:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4220:                         } else {
                   4221:                             if ($4 eq '') {
                   4222:                                 $sec = 'none';
                   4223:                             } else {
                   4224:                                 $sec = $4;
                   4225:                             }
                   4226:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4227:                         }
1.811     albertel 4228:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4229:                         my $cid = $2.'_'.$3;
                   4230:                         if ($4 eq '') {
                   4231:                             $sec = 'none';
                   4232:                         } else {
                   4233:                             $sec = $4;
                   4234:                         }
                   4235:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4236:                     }
                   4237:                 }
                   4238:                 if (keys(%allroles) == 0) {
                   4239:                     return;
                   4240:                 }
                   4241:                 foreach my $key (@courses_and_groups) {
                   4242:                     my %content = %{$$access_hash{$key}};
                   4243:                     my $cnum = $content{'number'};
                   4244:                     my $cdom = $content{'domain'};
                   4245:                     my $cid = $cdom.'_'.$cnum;
                   4246:                     if (!exists($allroles{$cid})) {
                   4247:                         next;
                   4248:                     }    
                   4249:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4250:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4251:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4252:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4253:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4254:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4255:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4256:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4257:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4258:                                         if (grep/^all$/,@sections) {
                   4259:                                             return 'ok';
                   4260:                                         } else {
                   4261:                                             if (grep/^$sec$/,@sections) {
                   4262:                                                 return 'ok';
                   4263:                                             }
                   4264:                                         }
                   4265:                                     }
                   4266:                                 }
                   4267:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4268:                                     if (grep/^none$/,@groups) {
                   4269:                                         return 'ok';
                   4270:                                     }
                   4271:                                 } else {
                   4272:                                     if (grep/^all$/,@groups) {
                   4273:                                         return 'ok';
                   4274:                                     } 
                   4275:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4276:                                         if (grep/^$group$/,@groups) {
                   4277:                                             return 'ok';
                   4278:                                         }
                   4279:                                     }
                   4280:                                 } 
                   4281:                             }
                   4282:                         }
                   4283:                     }
                   4284:                 }
                   4285:             }
                   4286:             if ($guest) {
                   4287:                 return $guest;
                   4288:             }
                   4289:         }
                   4290:     }
                   4291:     return;
                   4292: }
                   4293: 
                   4294: sub course_group_datechecker {
                   4295:     my ($dates,$now,$status) = @_;
                   4296:     my ($start,$end) = split(/\./,$dates);
                   4297:     if (!$start && !$end) {
                   4298:         return 'ok';
                   4299:     }
                   4300:     if (grep/^active$/,@{$status}) {
                   4301:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4302:             return 'ok';
                   4303:         }
                   4304:     }
                   4305:     if (grep/^previous$/,@{$status}) {
                   4306:         if ($end > $now ) {
                   4307:             return 'ok';
                   4308:         }
                   4309:     }
                   4310:     if (grep/^future$/,@{$status}) {
                   4311:         if ($start > $now) {
                   4312:             return 'ok';
                   4313:         }
                   4314:     }
                   4315:     return; 
                   4316: }
                   4317: 
                   4318: sub parse_portfolio_url {
                   4319:     my ($url) = @_;
                   4320: 
                   4321:     my ($type,$udom,$unum,$group,$file_name);
                   4322:     
1.823     albertel 4323:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4324: 	$type = 1;
                   4325:         $udom = $1;
                   4326:         $unum = $2;
                   4327:         $file_name = $3;
1.823     albertel 4328:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4329: 	$type = 2;
                   4330:         $udom = $1;
                   4331:         $unum = $2;
                   4332:         $group = $3;
                   4333:         $file_name = $3.'/'.$4;
                   4334:     }
                   4335:     if (wantarray) {
                   4336: 	return ($type,$udom,$unum,$file_name,$group);
                   4337:     }
                   4338:     return $type;
                   4339: }
                   4340: 
                   4341: sub is_portfolio_url {
                   4342:     my ($url) = @_;
                   4343:     return scalar(&parse_portfolio_url($url));
                   4344: }
                   4345: 
1.798     raeburn  4346: sub is_portfolio_file {
                   4347:     my ($file) = @_;
1.820     raeburn  4348:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4349:         return 1;
                   4350:     }
                   4351:     return;
                   4352: }
                   4353: 
                   4354: 
1.341     www      4355: # ---------------------------------------------- Custom access rule evaluation
                   4356: 
                   4357: sub customaccess {
                   4358:     my ($priv,$uri)=@_;
1.807     albertel 4359:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4360:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4361:     $udom = &LONCAPA::clean_domain($udom);
                   4362:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4363:     my $access=0;
1.800     albertel 4364:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4365: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4366: 	if ($type eq 'user') {
                   4367: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4368: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4369: 		if ($tdom) {
                   4370: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4371: 		}
1.896     albertel 4372: 		if ($tuname) {
                   4373: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4374: 		}
                   4375: 		$access=($effect eq 'allow');
                   4376: 		last;
                   4377: 	    }
                   4378: 	} else {
                   4379: 	    if ($role) {
                   4380: 		if ($role ne $urole) { next; }
                   4381: 	    }
                   4382: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4383: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4384: 		if ($tdom) {
                   4385: 		    if ($tdom ne $udom) { next; }
                   4386: 		}
                   4387: 		if ($tcrs) {
                   4388: 		    if ($tcrs ne $ucrs) { next; }
                   4389: 		}
                   4390: 		if ($tsec) {
                   4391: 		    if ($tsec ne $usec) { next; }
                   4392: 		}
                   4393: 		$access=($effect eq 'allow');
                   4394: 		last;
                   4395: 	    }
                   4396: 	    if ($realm eq '' && $role eq '') {
                   4397: 		$access=($effect eq 'allow');
                   4398: 	    }
1.402     bowersj2 4399: 	}
1.341     www      4400:     }
                   4401:     return $access;
                   4402: }
                   4403: 
1.103     harris41 4404: # ------------------------------------------------- Check for a user privilege
1.12      www      4405: 
                   4406: sub allowed {
1.810     raeburn  4407:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4408:     my $ver_orguri=$uri;
1.439     www      4409:     $uri=&deversion($uri);
1.152     www      4410:     my $orguri=$uri;
1.52      www      4411:     $uri=&declutter($uri);
1.809     raeburn  4412: 
1.810     raeburn  4413:     if ($priv eq 'evb') {
                   4414: # Evade communication block restrictions for specified role in a course
                   4415:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4416:             return $1;
                   4417:         } else {
                   4418:             return;
                   4419:         }
                   4420:     }
                   4421: 
1.620     albertel 4422:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4423: # Free bre access to adm and meta resources
1.775     albertel 4424:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4425: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4426: 	&& ($priv eq 'bre')) {
1.14      www      4427: 	return 'F';
1.159     www      4428:     }
                   4429: 
1.545     banghart 4430: # Free bre access to user's own portfolio contents
1.714     raeburn  4431:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4432:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4433: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4434:         my %setters;
                   4435:         my ($startblock,$endblock) = 
                   4436:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4437:         if ($startblock && $endblock) {
                   4438:             return 'B';
                   4439:         } else {
                   4440:             return 'F';
                   4441:         }
1.545     banghart 4442:     }
                   4443: 
1.762     raeburn  4444: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4445:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4446:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4447:         if (exists($env{'request.course.id'})) {
                   4448:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4449:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4450:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4451:                 my $courseprivid=$env{'request.course.id'};
                   4452:                 $courseprivid=~s/\_/\//;
                   4453:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4454:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4455:                     return $1; 
1.762     raeburn  4456:                 } else {
                   4457:                     if ($env{'request.course.sec'}) {
                   4458:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4459:                     }
                   4460:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4461:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4462:                         return $2;
                   4463:                     }
1.714     raeburn  4464:                 }
                   4465:             }
                   4466:         }
                   4467:     }
                   4468: 
1.159     www      4469: # Free bre to public access
                   4470: 
                   4471:     if ($priv eq 'bre') {
1.238     www      4472:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4473: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4474:            return 'F'; 
                   4475:         }
1.238     www      4476:         if ($copyright eq 'priv') {
                   4477:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4478: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4479: 		return '';
                   4480:             }
                   4481:         }
                   4482:         if ($copyright eq 'domain') {
                   4483:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4484: 	    unless (($env{'user.domain'} eq $1) ||
                   4485:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4486: 		return '';
                   4487:             }
1.262     matthew  4488:         }
1.620     albertel 4489:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4490:             # Library role, so allow browsing of resources in this domain.
                   4491:             return 'F';
1.238     www      4492:         }
1.341     www      4493:         if ($copyright eq 'custom') {
                   4494: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4495:         }
1.14      www      4496:     }
1.264     matthew  4497:     # Domain coordinator is trying to create a course
1.620     albertel 4498:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4499:         # uri is the requested domain in this case.
                   4500:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4501:         # a role of dc for the domain in question.
1.620     albertel 4502:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4503:     }
1.29      www      4504: 
1.52      www      4505:     my $thisallowed='';
                   4506:     my $statecond=0;
                   4507:     my $courseprivid='';
                   4508: 
                   4509: # Course
                   4510: 
1.620     albertel 4511:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4512:        $thisallowed.=$1;
                   4513:     }
1.29      www      4514: 
1.52      www      4515: # Domain
                   4516: 
1.620     albertel 4517:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4518:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4519:        $thisallowed.=$1;
                   4520:     }
1.52      www      4521: 
                   4522: # Course: uri itself is a course
1.66      www      4523:     my $courseuri=$uri;
                   4524:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4525:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4526: 
1.620     albertel 4527:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4528:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4529:        $thisallowed.=$1;
                   4530:     }
1.29      www      4531: 
1.665     albertel 4532: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4533: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4534:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4535: 	$thisallowed='';
1.671     raeburn  4536:         my ($match)=&is_on_map($uri);
                   4537:         if ($match) {
                   4538:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4539:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4540:                 $thisallowed.=$1;
                   4541:             }
                   4542:         } else {
1.705     albertel 4543:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4544:             if ($refuri) {
                   4545:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4546:                     $thisallowed='F';
1.671     raeburn  4547:                 } else {
                   4548:                     $refuri=&declutter($refuri);
                   4549:                     my ($match) = &is_on_map($refuri);
                   4550:                     if ($match) {
                   4551:                         $thisallowed='F';
                   4552:                     }
1.669     raeburn  4553:                 }
1.671     raeburn  4554:             }
                   4555:         }
1.314     www      4556:     }
1.492     albertel 4557: 
1.766     albertel 4558:     if ($priv eq 'bre'
                   4559: 	&& $thisallowed ne 'F' 
                   4560: 	&& $thisallowed ne '2'
                   4561: 	&& &is_portfolio_url($uri)) {
                   4562: 	$thisallowed = &portfolio_access($uri);
                   4563:     }
                   4564:     
1.52      www      4565: # Full access at system, domain or course-wide level? Exit.
1.29      www      4566:     if ($thisallowed=~/F/) {
                   4567: 	return 'F';
                   4568:     }
                   4569: 
1.52      www      4570: # If this is generating or modifying users, exit with special codes
1.29      www      4571: 
1.643     www      4572:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4573: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4574: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4575: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4576: 	    unless ($auname) { return $thisallowed; }
                   4577: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4578: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4579: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4580: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4581: 	}
1.52      www      4582: 	return $thisallowed;
                   4583:     }
                   4584: #
1.103     harris41 4585: # Gathered so far: system, domain and course wide privileges
1.52      www      4586: #
                   4587: # Course: See if uri or referer is an individual resource that is part of 
                   4588: # the course
                   4589: 
1.620     albertel 4590:     if ($env{'request.course.id'}) {
1.232     www      4591: 
1.620     albertel 4592:        $courseprivid=$env{'request.course.id'};
                   4593:        if ($env{'request.course.sec'}) {
                   4594:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4595:        }
                   4596:        $courseprivid=~s/\_/\//;
                   4597:        my $checkreferer=1;
1.232     www      4598:        my ($match,$cond)=&is_on_map($uri);
                   4599:        if ($match) {
                   4600:            $statecond=$cond;
1.620     albertel 4601:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4602:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4603:                $thisallowed.=$1;
                   4604:                $checkreferer=0;
                   4605:            }
1.29      www      4606:        }
1.83      www      4607:        
1.148     www      4608:        if ($checkreferer) {
1.620     albertel 4609: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4610:             unless ($refuri) {
1.800     albertel 4611:                 foreach my $key (keys(%env)) {
                   4612: 		    if ($key=~/^httpref\..*\*/) {
                   4613: 			my $pattern=$key;
1.156     www      4614:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4615:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4616:                         $pattern=~s/\//\\\//g;
1.152     www      4617:                         if ($orguri=~/$pattern/) {
1.800     albertel 4618: 			    $refuri=$env{$key};
1.148     www      4619:                         }
                   4620:                     }
1.191     harris41 4621:                 }
1.148     www      4622:             }
1.232     www      4623: 
1.148     www      4624:          if ($refuri) { 
1.152     www      4625: 	  $refuri=&declutter($refuri);
1.232     www      4626:           my ($match,$cond)=&is_on_map($refuri);
                   4627:             if ($match) {
                   4628:               my $refstatecond=$cond;
1.620     albertel 4629:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4630:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4631:                   $thisallowed.=$1;
1.53      www      4632:                   $uri=$refuri;
                   4633:                   $statecond=$refstatecond;
1.52      www      4634:               }
                   4635:           }
1.148     www      4636:         }
1.29      www      4637:        }
1.52      www      4638:    }
1.29      www      4639: 
1.52      www      4640: #
1.103     harris41 4641: # Gathered now: all privileges that could apply, and condition number
1.52      www      4642: # 
                   4643: #
                   4644: # Full or no access?
                   4645: #
1.29      www      4646: 
1.52      www      4647:     if ($thisallowed=~/F/) {
                   4648: 	return 'F';
                   4649:     }
1.29      www      4650: 
1.52      www      4651:     unless ($thisallowed) {
                   4652:         return '';
                   4653:     }
1.29      www      4654: 
1.52      www      4655: # Restrictions exist, deal with them
                   4656: #
                   4657: #   C:according to course preferences
                   4658: #   R:according to resource settings
                   4659: #   L:unless locked
                   4660: #   X:according to user session state
                   4661: #
                   4662: 
                   4663: # Possibly locked functionality, check all courses
1.54      www      4664: # Locks might take effect only after 10 minutes cache expiration for other
                   4665: # courses, and 2 minutes for current course
1.52      www      4666: 
                   4667:     my $envkey;
                   4668:     if ($thisallowed=~/L/) {
1.620     albertel 4669:         foreach $envkey (keys %env) {
1.54      www      4670:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4671:                my $courseid=$2;
                   4672:                my $roleid=$1.'.'.$2;
1.92      www      4673:                $courseid=~s/^\///;
1.54      www      4674:                my $expiretime=600;
1.620     albertel 4675:                if ($env{'request.role'} eq $roleid) {
1.54      www      4676: 		  $expiretime=120;
                   4677:                }
                   4678: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4679:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4680:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4681: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4682:                }
1.620     albertel 4683:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4684:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4685: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4686:                        &log($env{'user.domain'},$env{'user.name'},
                   4687:                             $env{'user.home'},
1.57      www      4688:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4689:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4690:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4691: 		       return '';
                   4692:                    }
                   4693:                }
1.620     albertel 4694:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4695:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4696: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4697:                        &log($env{'user.domain'},$env{'user.name'},
                   4698:                             $env{'user.home'},
1.57      www      4699:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4700:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4701:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4702: 		       return '';
                   4703:                    }
                   4704:                }
                   4705: 	   }
1.29      www      4706:        }
1.52      www      4707:     }
                   4708:    
                   4709: #
                   4710: # Rest of the restrictions depend on selected course
                   4711: #
                   4712: 
1.620     albertel 4713:     unless ($env{'request.course.id'}) {
1.766     albertel 4714: 	if ($thisallowed eq 'A') {
                   4715: 	    return 'A';
1.814     raeburn  4716:         } elsif ($thisallowed eq 'B') {
                   4717:             return 'B';
1.766     albertel 4718: 	} else {
                   4719: 	    return '1';
                   4720: 	}
1.52      www      4721:     }
1.29      www      4722: 
1.52      www      4723: #
                   4724: # Now user is definitely in a course
                   4725: #
1.53      www      4726: 
                   4727: 
                   4728: # Course preferences
                   4729: 
                   4730:    if ($thisallowed=~/C/) {
1.620     albertel 4731:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4732:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4733:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4734: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4735: 	   if ($priv ne 'pch') { 
                   4736: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4737: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4738: 			$env{'request.course.id'});
                   4739: 	   }
1.237     www      4740:            return '';
                   4741:        }
                   4742: 
1.620     albertel 4743:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4744: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4745: 	   if ($priv ne 'pch') { 
                   4746: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4747: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4748: 			$env{'request.course.id'});
                   4749: 	   }
1.54      www      4750:            return '';
                   4751:        }
1.53      www      4752:    }
                   4753: 
                   4754: # Resource preferences
                   4755: 
                   4756:    if ($thisallowed=~/R/) {
1.620     albertel 4757:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4758:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4759: 	   if ($priv ne 'pch') { 
                   4760: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4761: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4762: 	   }
                   4763: 	   return '';
1.54      www      4764:        }
1.53      www      4765:    }
1.30      www      4766: 
1.246     www      4767: # Restricted by state or randomout?
1.30      www      4768: 
1.52      www      4769:    if ($thisallowed=~/X/) {
1.620     albertel 4770:       if ($env{'acc.randomout'}) {
1.579     albertel 4771: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4772:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4773:             return ''; 
                   4774:          }
1.247     www      4775:       }
                   4776:       if (&condval($statecond)) {
1.52      www      4777: 	 return '2';
                   4778:       } else {
                   4779:          return '';
                   4780:       }
                   4781:    }
1.30      www      4782: 
1.766     albertel 4783:     if ($thisallowed eq 'A') {
                   4784: 	return 'A';
1.814     raeburn  4785:     } elsif ($thisallowed eq 'B') {
                   4786:         return 'B';
1.766     albertel 4787:     }
1.52      www      4788:    return 'F';
1.232     www      4789: }
                   4790: 
1.710     albertel 4791: sub split_uri_for_cond {
                   4792:     my $uri=&deversion(&declutter(shift));
                   4793:     my @uriparts=split(/\//,$uri);
                   4794:     my $filename=pop(@uriparts);
                   4795:     my $pathname=join('/',@uriparts);
                   4796:     return ($pathname,$filename);
                   4797: }
1.232     www      4798: # --------------------------------------------------- Is a resource on the map?
                   4799: 
                   4800: sub is_on_map {
1.710     albertel 4801:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4802:     #Trying to find the conditional for the file
1.620     albertel 4803:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4804: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4805:     if ($match) {
1.289     bowersj2 4806: 	return (1,$1);
                   4807:     } else {
1.434     www      4808: 	return (0,0);
1.289     bowersj2 4809:     }
1.12      www      4810: }
                   4811: 
1.427     www      4812: # --------------------------------------------------------- Get symb from alias
                   4813: 
                   4814: sub get_symb_from_alias {
                   4815:     my $symb=shift;
                   4816:     my ($map,$resid,$url)=&decode_symb($symb);
                   4817: # Already is a symb
                   4818:     if ($url) { return $symb; }
                   4819: # Must be an alias
                   4820:     my $aliassymb='';
                   4821:     my %bighash;
1.620     albertel 4822:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4823:                             &GDBM_READER(),0640)) {
                   4824:         my $rid=$bighash{'mapalias_'.$symb};
                   4825: 	if ($rid) {
                   4826: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4827: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4828: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4829: 	}
                   4830:         untie %bighash;
                   4831:     }
                   4832:     return $aliassymb;
                   4833: }
                   4834: 
1.12      www      4835: # ----------------------------------------------------------------- Define Role
                   4836: 
                   4837: sub definerole {
                   4838:   if (allowed('mcr','/')) {
                   4839:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4840:     foreach my $role (split(':',$sysrole)) {
                   4841: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4842:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4843:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4844: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4845:                return "refused:s:$crole&$cqual"; 
                   4846:             }
                   4847:         }
1.191     harris41 4848:     }
1.800     albertel 4849:     foreach my $role (split(':',$domrole)) {
                   4850: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4851:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4852:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4853: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4854:                return "refused:d:$crole&$cqual"; 
                   4855:             }
                   4856:         }
1.191     harris41 4857:     }
1.800     albertel 4858:     foreach my $role (split(':',$courole)) {
                   4859: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4860:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4861:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4862: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4863:                return "refused:c:$crole&$cqual"; 
                   4864:             }
                   4865:         }
1.191     harris41 4866:     }
1.620     albertel 4867:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4868:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4869: 	        "rolesdef_$rolename=".
                   4870:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4871:     return reply($command,$env{'user.home'});
1.12      www      4872:   } else {
                   4873:     return 'refused';
                   4874:   }
1.105     harris41 4875: }
                   4876: 
                   4877: # ---------------- Make a metadata query against the network of library servers
                   4878: 
                   4879: sub metadata_query {
1.244     matthew  4880:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4881:     my %rhash;
1.845     albertel 4882:     my %libserv = &all_library();
1.244     matthew  4883:     my @server_list = (defined($server_array) ? @$server_array
                   4884:                                               : keys(%libserv) );
                   4885:     for my $server (@server_list) {
1.118     harris41 4886: 	unless ($custom or $customshow) {
                   4887: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4888: 	    $rhash{$server}=$reply;
                   4889: 	}
                   4890: 	else {
                   4891: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4892: 			     &escape($custom).':'.&escape($customshow),
                   4893: 			     $server);
                   4894: 	    $rhash{$server}=$reply;
                   4895: 	}
1.112     harris41 4896:     }
1.118     harris41 4897:     return \%rhash;
1.240     www      4898: }
                   4899: 
                   4900: # ----------------------------------------- Send log queries and wait for reply
                   4901: 
                   4902: sub log_query {
                   4903:     my ($uname,$udom,$query,%filters)=@_;
                   4904:     my $uhome=&homeserver($uname,$udom);
                   4905:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4906:     my $uhost=&hostname($uhome);
1.800     albertel 4907:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4908:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4909:                        $uhome);
1.479     albertel 4910:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4911:     return get_query_reply($queryid);
                   4912: }
                   4913: 
1.818     raeburn  4914: # -------------------------- Update MySQL table for portfolio file
                   4915: 
                   4916: sub update_portfolio_table {
1.821     raeburn  4917:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  4918:     if ($group ne '') {
                   4919:         $file_name =~s /^\Q$group\E//;
                   4920:     }
1.818     raeburn  4921:     my $homeserver = &homeserver($uname,$udom);
                   4922:     my $queryid=
1.821     raeburn  4923:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4924:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4925:     my $reply = &get_query_reply($queryid);
                   4926:     return $reply;
                   4927: }
                   4928: 
1.899     raeburn  4929: # -------------------------- Update MySQL allusers table
                   4930: 
                   4931: sub update_allusers_table {
                   4932:     my ($uname,$udom,$names) = @_;
                   4933:     my $homeserver = &homeserver($uname,$udom);
                   4934:     my $queryid=
                   4935:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4936:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4937:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4938:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4939:                'generation='.&escape($names->{'generation'}).'%%'.
                   4940:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4941:                'id='.&escape($names->{'id'}),$homeserver);
                   4942:     my $reply = &get_query_reply($queryid);
                   4943:     return $reply;
                   4944: }
                   4945: 
1.508     raeburn  4946: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4947: 
                   4948: sub fetch_enrollment_query {
1.511     raeburn  4949:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4950:     my $homeserver;
1.547     raeburn  4951:     my $maxtries = 1;
1.508     raeburn  4952:     if ($context eq 'automated') {
                   4953:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4954:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4955:     } else {
                   4956:         $homeserver = &homeserver($cnum,$dom);
                   4957:     }
1.838     albertel 4958:     my $host=&hostname($homeserver);
1.506     raeburn  4959:     my $cmd = '';
1.800     albertel 4960:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4961:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4962:     }
                   4963:     $cmd =~ s/%%$//;
                   4964:     $cmd = &escape($cmd);
                   4965:     my $query = 'fetchenrollment';
1.620     albertel 4966:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4967:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4968:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4969:         return 'error: '.$queryid;
                   4970:     }
1.506     raeburn  4971:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4972:     my $tries = 1;
                   4973:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4974:         $reply = &get_query_reply($queryid);
                   4975:         $tries ++;
                   4976:     }
1.526     raeburn  4977:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4978:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4979:     } else {
1.901     albertel 4980:         my @responses = split(/:/,$reply);
1.515     raeburn  4981:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4982:             foreach my $line (@responses) {
                   4983:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4984:                 $$replyref{$key} = $value;
                   4985:             }
                   4986:         } else {
1.506     raeburn  4987:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4988:             foreach my $line (@responses) {
                   4989:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4990:                 $$replyref{$key} = $value;
                   4991:                 if ($value > 0) {
1.800     albertel 4992:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4993:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4994:                         my $destname = $pathname.'/'.$filename;
                   4995:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4996:                         if ($xml_classlist =~ /^error/) {
                   4997:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4998:                         } else {
1.506     raeburn  4999:                             if ( open(FILE,">$destname") ) {
                   5000:                                 print FILE &unescape($xml_classlist);
                   5001:                                 close(FILE);
1.526     raeburn  5002:                             } else {
                   5003:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5004:                             }
                   5005:                         }
                   5006:                     }
                   5007:                 }
                   5008:             }
                   5009:         }
                   5010:         return 'ok';
                   5011:     }
                   5012:     return 'error';
                   5013: }
                   5014: 
1.242     www      5015: sub get_query_reply {
                   5016:     my $queryid=shift;
1.240     www      5017:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5018:     my $reply='';
                   5019:     for (1..100) {
                   5020: 	sleep 2;
                   5021:         if (-e $replyfile.'.end') {
1.448     albertel 5022: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5023: 		$reply = join('',<$fh>);
                   5024: 		close($fh);
1.240     www      5025: 	   } else { return 'error: reply_file_error'; }
1.242     www      5026:            return &unescape($reply);
                   5027: 	}
1.240     www      5028:     }
1.242     www      5029:     return 'timeout:'.$queryid;
1.240     www      5030: }
                   5031: 
                   5032: sub courselog_query {
1.241     www      5033: #
                   5034: # possible filters:
                   5035: # url: url or symb
                   5036: # username
                   5037: # domain
                   5038: # action: view, submit, grade
                   5039: # start: timestamp
                   5040: # end: timestamp
                   5041: #
1.240     www      5042:     my (%filters)=@_;
1.620     albertel 5043:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5044:     if ($filters{'url'}) {
                   5045: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5046:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5047:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5048:     }
1.620     albertel 5049:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5050:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5051:     return &log_query($cname,$cdom,'courselog',%filters);
                   5052: }
                   5053: 
                   5054: sub userlog_query {
1.858     raeburn  5055: #
                   5056: # possible filters:
                   5057: # action: log check role
                   5058: # start: timestamp
                   5059: # end: timestamp
                   5060: #
1.240     www      5061:     my ($uname,$udom,%filters)=@_;
                   5062:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5063: }
                   5064: 
1.506     raeburn  5065: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5066: 
                   5067: sub auto_run {
1.508     raeburn  5068:     my ($cnum,$cdom) = @_;
1.876     raeburn  5069:     my $response = 0;
                   5070:     my $settings;
                   5071:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5072:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5073:         $settings = $domconfig{'autoenroll'};
                   5074:         if ($settings->{'run'} eq '1') {
                   5075:             $response = 1;
                   5076:         }
                   5077:     } else {
1.934     raeburn  5078:         my $homeserver;
                   5079:         if (&is_course($cdom,$cnum)) {
                   5080:             $homeserver = &homeserver($cnum,$cdom);
                   5081:         } else {
                   5082:             $homeserver = &domain($cdom,'primary');
                   5083:         }
                   5084:         if ($homeserver ne 'no_host') {
                   5085:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5086:         }
1.876     raeburn  5087:     }
1.506     raeburn  5088:     return $response;
                   5089: }
1.776     albertel 5090: 
1.506     raeburn  5091: sub auto_get_sections {
1.508     raeburn  5092:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5093:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5094:     my @secs = ();
1.511     raeburn  5095:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5096:     unless ($response eq 'refused') {
1.901     albertel 5097:         @secs = split(/:/,$response);
1.506     raeburn  5098:     }
                   5099:     return @secs;
                   5100: }
1.776     albertel 5101: 
1.506     raeburn  5102: sub auto_new_course {
1.508     raeburn  5103:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5104:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5105:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5106:     return $response;
                   5107: }
1.776     albertel 5108: 
1.506     raeburn  5109: sub auto_validate_courseID {
1.508     raeburn  5110:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5111:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5112:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5113:     return $response;
                   5114: }
1.776     albertel 5115: 
1.506     raeburn  5116: sub auto_create_password {
1.873     raeburn  5117:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5118:     my ($homeserver,$response);
1.506     raeburn  5119:     my $create_passwd = 0;
                   5120:     my $authchk = '';
1.873     raeburn  5121:     if ($udom =~ /^$match_domain$/) {
                   5122:         $homeserver = &domain($udom,'primary');
                   5123:     }
                   5124:     if ($homeserver eq '') {
                   5125:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5126:             $homeserver = &homeserver($cnum,$cdom);
                   5127:         }
                   5128:     }
                   5129:     if ($homeserver eq '') {
                   5130:         $authchk = 'nodomain';
1.506     raeburn  5131:     } else {
1.873     raeburn  5132:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5133:         if ($response eq 'refused') {
                   5134:             $authchk = 'refused';
                   5135:         } else {
1.901     albertel 5136:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5137:         }
1.506     raeburn  5138:     }
                   5139:     return ($authparam,$create_passwd,$authchk);
                   5140: }
                   5141: 
1.706     raeburn  5142: sub auto_photo_permission {
                   5143:     my ($cnum,$cdom,$students) = @_;
                   5144:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5145:     my ($outcome,$perm_reqd,$conditions) = 
                   5146: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5147:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5148: 	return (undef,undef);
                   5149:     }
1.706     raeburn  5150:     return ($outcome,$perm_reqd,$conditions);
                   5151: }
                   5152: 
                   5153: sub auto_checkphotos {
                   5154:     my ($uname,$udom,$pid) = @_;
                   5155:     my $homeserver = &homeserver($uname,$udom);
                   5156:     my ($result,$resulttype);
                   5157:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5158: 				   &escape($uname).':'.&escape($pid),
                   5159: 				   $homeserver));
1.709     albertel 5160:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5161: 	return (undef,undef);
                   5162:     }
1.706     raeburn  5163:     if ($outcome) {
                   5164:         ($result,$resulttype) = split(/:/,$outcome);
                   5165:     } 
                   5166:     return ($result,$resulttype);
                   5167: }
                   5168: 
                   5169: sub auto_photochoice {
                   5170:     my ($cnum,$cdom) = @_;
                   5171:     my $homeserver = &homeserver($cnum,$cdom);
                   5172:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5173: 						       &escape($cdom),
                   5174: 						       $homeserver)));
1.709     albertel 5175:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5176: 	return (undef,undef);
                   5177:     }
1.706     raeburn  5178:     return ($update,$comment);
                   5179: }
                   5180: 
                   5181: sub auto_photoupdate {
                   5182:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5183:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5184:     my $host=&hostname($homeserver);
1.706     raeburn  5185:     my $cmd = '';
                   5186:     my $maxtries = 1;
1.800     albertel 5187:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5188:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5189:     }
                   5190:     $cmd =~ s/%%$//;
                   5191:     $cmd = &escape($cmd);
                   5192:     my $query = 'institutionalphotos';
                   5193:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5194:     unless ($queryid=~/^\Q$host\E\_/) {
                   5195:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5196:         return 'error: '.$queryid;
                   5197:     }
                   5198:     my $reply = &get_query_reply($queryid);
                   5199:     my $tries = 1;
                   5200:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5201:         $reply = &get_query_reply($queryid);
                   5202:         $tries ++;
                   5203:     }
                   5204:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5205:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5206:     } else {
                   5207:         my @responses = split(/:/,$reply);
                   5208:         my $outcome = shift(@responses); 
                   5209:         foreach my $item (@responses) {
                   5210:             my ($key,$value) = split(/=/,$item);
                   5211:             $$photo{$key} = $value;
                   5212:         }
                   5213:         return $outcome;
                   5214:     }
                   5215:     return 'error';
                   5216: }
                   5217: 
1.521     raeburn  5218: sub auto_instcode_format {
1.793     albertel 5219:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5220: 	$cat_order) = @_;
1.521     raeburn  5221:     my $courses = '';
1.772     raeburn  5222:     my @homeservers;
1.521     raeburn  5223:     if ($caller eq 'global') {
1.841     albertel 5224: 	my %servers = &get_servers($codedom,'library');
                   5225: 	foreach my $tryserver (keys(%servers)) {
                   5226: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5227: 		push(@homeservers,$tryserver);
                   5228: 	    }
1.584     raeburn  5229:         }
1.521     raeburn  5230:     } else {
1.772     raeburn  5231:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5232:     }
1.793     albertel 5233:     foreach my $code (keys(%{$instcodes})) {
                   5234:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5235:     }
                   5236:     chop($courses);
1.772     raeburn  5237:     my $ok_response = 0;
                   5238:     my $response;
                   5239:     while (@homeservers > 0 && $ok_response == 0) {
                   5240:         my $server = shift(@homeservers); 
                   5241:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5242:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5243:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5244: 		split(/:/,$response);
1.772     raeburn  5245:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5246:             push(@{$codetitles},&str2array($codetitles_str));
                   5247:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5248:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5249:             $ok_response = 1;
                   5250:         }
                   5251:     }
                   5252:     if ($ok_response) {
1.521     raeburn  5253:         return 'ok';
1.772     raeburn  5254:     } else {
                   5255:         return $response;
1.521     raeburn  5256:     }
                   5257: }
                   5258: 
1.792     raeburn  5259: sub auto_instcode_defaults {
                   5260:     my ($domain,$returnhash,$code_order) = @_;
                   5261:     my @homeservers;
1.841     albertel 5262: 
                   5263:     my %servers = &get_servers($domain,'library');
                   5264:     foreach my $tryserver (keys(%servers)) {
                   5265: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5266: 	    push(@homeservers,$tryserver);
                   5267: 	}
1.792     raeburn  5268:     }
1.841     albertel 5269: 
1.792     raeburn  5270:     my $response;
1.841     albertel 5271:     foreach my $server (@homeservers) {
1.792     raeburn  5272:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5273:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5274: 	
                   5275: 	foreach my $pair (split(/\&/,$response)) {
                   5276: 	    my ($name,$value)=split(/\=/,$pair);
                   5277: 	    if ($name eq 'code_order') {
                   5278: 		@{$code_order} = split(/\&/,&unescape($value));
                   5279: 	    } else {
                   5280: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5281: 	    }
                   5282: 	}
                   5283: 	return 'ok';
1.792     raeburn  5284:     }
1.841     albertel 5285: 
                   5286:     return $response;
1.792     raeburn  5287: } 
                   5288: 
1.777     albertel 5289: sub auto_validate_class_sec {
1.918     raeburn  5290:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5291:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5292:     my $ownerlist;
                   5293:     if (ref($owners) eq 'ARRAY') {
                   5294:         $ownerlist = join(',',@{$owners});
                   5295:     } else {
                   5296:         $ownerlist = $owners;
                   5297:     }
1.773     raeburn  5298:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5299:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5300:     return $response;
                   5301: }
                   5302: 
1.679     raeburn  5303: # ------------------------------------------------------- Course Group routines
                   5304: 
                   5305: sub get_coursegroups {
1.809     raeburn  5306:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5307:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5308: }
                   5309: 
1.679     raeburn  5310: sub modify_coursegroup {
                   5311:     my ($cdom,$cnum,$groupsettings) = @_;
                   5312:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5313: }
                   5314: 
1.809     raeburn  5315: sub toggle_coursegroup_status {
                   5316:     my ($cdom,$cnum,$group,$action) = @_;
                   5317:     my ($from_namespace,$to_namespace);
                   5318:     if ($action eq 'delete') {
                   5319:         $from_namespace = 'coursegroups';
                   5320:         $to_namespace = 'deleted_groups';
                   5321:     } else {
                   5322:         $from_namespace = 'deleted_groups';
                   5323:         $to_namespace = 'coursegroups';
                   5324:     }
                   5325:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5326:     if (my $tmp = &error(%curr_group)) {
                   5327:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5328:         return ('read error',$tmp);
                   5329:     } else {
                   5330:         my %savedsettings = %curr_group; 
1.809     raeburn  5331:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5332:         my $deloutcome;
                   5333:         if ($result eq 'ok') {
1.809     raeburn  5334:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5335:         } else {
                   5336:             return ('write error',$result);
                   5337:         }
                   5338:         if ($deloutcome eq 'ok') {
                   5339:             return 'ok';
                   5340:         } else {
                   5341:             return ('delete error',$deloutcome);
                   5342:         }
                   5343:     }
                   5344: }
                   5345: 
1.679     raeburn  5346: sub modify_group_roles {
1.957     raeburn  5347:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5348:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5349:     my $role = 'gr/'.&escape($userprivs);
                   5350:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5351:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5352:     if ($result eq 'ok') {
                   5353:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5354:     }
1.679     raeburn  5355:     return $result;
                   5356: }
                   5357: 
                   5358: sub modify_coursegroup_membership {
                   5359:     my ($cdom,$cnum,$membership) = @_;
                   5360:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5361:     return $result;
                   5362: }
                   5363: 
1.682     raeburn  5364: sub get_active_groups {
                   5365:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5366:     my $now = time;
                   5367:     my %groups = ();
                   5368:     foreach my $key (keys(%env)) {
1.811     albertel 5369:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5370:             my ($start,$end) = split(/\./,$env{$key});
                   5371:             if (($end!=0) && ($end<$now)) { next; }
                   5372:             if (($start!=0) && ($start>$now)) { next; }
                   5373:             if ($1 eq $cdom && $2 eq $cnum) {
                   5374:                 $groups{$3} = $env{$key} ;
                   5375:             }
                   5376:         }
                   5377:     }
                   5378:     return %groups;
                   5379: }
                   5380: 
1.683     raeburn  5381: sub get_group_membership {
                   5382:     my ($cdom,$cnum,$group) = @_;
                   5383:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5384: }
                   5385: 
                   5386: sub get_users_groups {
                   5387:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5388:     my @usersgroups;
1.683     raeburn  5389:     my $cachetime=1800;
                   5390: 
                   5391:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5392:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5393:     if (defined($cached)) {
1.734     albertel 5394:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5395:     } else {  
                   5396:         $grouplist = '';
1.816     raeburn  5397:         my $courseurl = &courseid_to_courseurl($courseid);
                   5398:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5399:         my $access_end = $env{'course.'.$courseid.
                   5400:                               '.default_enrollment_end_date'};
                   5401:         my $now = time;
                   5402:         foreach my $key (keys(%roleshash)) {
                   5403:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5404:                 my $group = $1;
                   5405:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5406:                     my $start = $2;
                   5407:                     my $end = $1;
                   5408:                     if ($start == -1) { next; } # deleted from group
                   5409:                     if (($start!=0) && ($start>$now)) { next; }
                   5410:                     if (($end!=0) && ($end<$now)) {
                   5411:                         if ($access_end && $access_end < $now) {
                   5412:                             if ($access_end - $end < 86400) {
                   5413:                                 push(@usersgroups,$group);
1.733     raeburn  5414:                             }
                   5415:                         }
1.817     raeburn  5416:                         next;
1.733     raeburn  5417:                     }
1.817     raeburn  5418:                     push(@usersgroups,$group);
1.683     raeburn  5419:                 }
                   5420:             }
                   5421:         }
1.817     raeburn  5422:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5423:         $grouplist = join(':',@usersgroups);
                   5424:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5425:     }
1.733     raeburn  5426:     return @usersgroups;
1.683     raeburn  5427: }
                   5428: 
                   5429: sub devalidate_getgroups_cache {
                   5430:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5431:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5432: 
1.683     raeburn  5433:     my $hashid="$udom:$uname:$courseid";
                   5434:     &devalidate_cache_new('getgroups',$hashid);
                   5435: }
                   5436: 
1.12      www      5437: # ------------------------------------------------------------------ Plain Text
                   5438: 
                   5439: sub plaintext {
1.742     raeburn  5440:     my ($short,$type,$cid) = @_;
1.758     albertel 5441:     if ($short =~ /^cr/) {
                   5442: 	return (split('/',$short))[-1];
                   5443:     }
1.742     raeburn  5444:     if (!defined($cid)) {
                   5445:         $cid = $env{'request.course.id'};
                   5446:     }
                   5447:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5448:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5449:                                           '.plaintext'});
                   5450:     }
                   5451:     my %rolenames = (
                   5452:                       Course => 'std',
                   5453:                       Group => 'alt1',
                   5454:                     );
                   5455:     if (defined($type) && 
                   5456:          defined($rolenames{$type}) && 
                   5457:          defined($prp{$short}{$rolenames{$type}})) {
                   5458:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5459:     } else {
                   5460:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5461:     }
1.12      www      5462: }
                   5463: 
                   5464: # ----------------------------------------------------------------- Assign Role
                   5465: 
                   5466: sub assignrole {
1.957     raeburn  5467:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5468:         $context)=@_;
1.21      www      5469:     my $mrole;
                   5470:     if ($role =~ /^cr\//) {
1.393     www      5471:         my $cwosec=$url;
1.811     albertel 5472:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5473: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5474:            &logthis('Refused custom assignrole: '.
                   5475:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5476: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5477:            return 'refused'; 
                   5478:         }
1.21      www      5479:         $mrole='cr';
1.678     raeburn  5480:     } elsif ($role =~ /^gr\//) {
                   5481:         my $cwogrp=$url;
1.811     albertel 5482:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5483:         unless (&allowed('mdg',$cwogrp)) {
                   5484:             &logthis('Refused group assignrole: '.
                   5485:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5486:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5487:             return 'refused';
                   5488:         }
                   5489:         $mrole='gr';
1.21      www      5490:     } else {
1.82      www      5491:         my $cwosec=$url;
1.811     albertel 5492:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5493:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5494:             my $refused;
                   5495:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5496:                 if (!(&allowed('c'.$role,$url))) {
                   5497:                     $refused = 1;
                   5498:                 }
                   5499:             } else {
                   5500:                 $refused = 1;
                   5501:             }
1.947     raeburn  5502:             if ($refused) {
                   5503:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5504:                     $refused = '';
                   5505:                 } else {
                   5506:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5507:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5508: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5509:                     return 'refused';
                   5510:                 }
1.932     raeburn  5511:             }
1.104     www      5512:         }
1.21      www      5513:         $mrole=$role;
                   5514:     }
1.620     albertel 5515:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5516:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5517:     if ($end) { $command.='_'.$end; }
1.21      www      5518:     if ($start) {
                   5519: 	if ($end) { 
1.81      www      5520:            $command.='_'.$start; 
1.21      www      5521:         } else {
1.81      www      5522:            $command.='_0_'.$start;
1.21      www      5523:         }
                   5524:     }
1.739     raeburn  5525:     my $origstart = $start;
                   5526:     my $origend = $end;
1.957     raeburn  5527:     my $delflag;
1.357     www      5528: # actually delete
                   5529:     if ($deleteflag) {
1.373     www      5530: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5531: # modify command to delete the role
1.620     albertel 5532:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5533:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5534: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5535: # set start and finish to negative values for userrolelog
                   5536:            $start=-1;
                   5537:            $end=-1;
1.957     raeburn  5538:            $delflag = 1;
1.357     www      5539:         }
                   5540:     }
                   5541: # send command
1.349     www      5542:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5543: # log new user role if status is ok
1.349     www      5544:     if ($answer eq 'ok') {
1.663     raeburn  5545: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5546: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5547:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5548:         unless ($role =~ /^gr/) {
                   5549:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5550:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5551:         }
1.349     www      5552:     }
                   5553:     return $answer;
1.169     harris41 5554: }
                   5555: 
                   5556: # -------------------------------------------------- Modify user authentication
1.197     www      5557: # Overrides without validation
                   5558: 
1.169     harris41 5559: sub modifyuserauth {
                   5560:     my ($udom,$uname,$umode,$upass)=@_;
                   5561:     my $uhome=&homeserver($uname,$udom);
1.197     www      5562:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5563:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5564:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5565:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5566:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5567: 		     &escape($upass),$uhome);
1.620     albertel 5568:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5569:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5570:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5571:     &log($udom,,$uname,$uhome,
1.620     albertel 5572:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5573:                                      $env{'user.name'}.', '.$umode.
1.197     www      5574:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5575:     unless ($reply eq 'ok') {
1.197     www      5576:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5577: 	return 'error: '.$reply;
                   5578:     }   
1.170     harris41 5579:     return 'ok';
1.80      www      5580: }
                   5581: 
1.81      www      5582: # --------------------------------------------------------------- Modify a user
1.80      www      5583: 
1.81      www      5584: sub modifyuser {
1.206     matthew  5585:     my ($udom,    $uname, $uid,
                   5586:         $umode,   $upass, $first,
                   5587:         $middle,  $last,  $gene,
1.963     raeburn  5588:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5589:     $udom= &LONCAPA::clean_domain($udom);
                   5590:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5591:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5592:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5593: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5594:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5595:                                      ' desiredhome not specified'). 
1.620     albertel 5596:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5597:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5598:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5599: # ----------------------------------------------------------------- Create User
1.406     albertel 5600:     if (($uhome eq 'no_host') && 
                   5601: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5602:         my $unhome='';
1.844     albertel 5603:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5604:             $unhome = $desiredhome;
1.620     albertel 5605: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5606: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5607:         } else { # load balancing routine for determining $unhome
1.81      www      5608:             my $loadm=10000000;
1.841     albertel 5609: 	    my %servers = &get_servers($udom,'library');
                   5610: 	    foreach my $tryserver (keys(%servers)) {
                   5611: 		my $answer=reply('load',$tryserver);
                   5612: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5613: 		    $loadm=$answer;
                   5614: 		    $unhome=$tryserver;
                   5615: 		}
1.80      www      5616: 	    }
                   5617:         }
                   5618:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5619: 	    return 'error: unable to find a home server for '.$uname.
                   5620:                    ' in domain '.$udom;
1.80      www      5621:         }
                   5622:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5623:                          &escape($upass),$unhome);
                   5624: 	unless ($reply eq 'ok') {
                   5625:             return 'error: '.$reply;
                   5626:         }   
1.230     stredwic 5627:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5628:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5629: 	    return 'error: unable verify users home machine.';
1.80      www      5630:         }
1.209     matthew  5631:     }   # End of creation of new user
1.80      www      5632: # ---------------------------------------------------------------------- Add ID
                   5633:     if ($uid) {
                   5634:        $uid=~tr/A-Z/a-z/;
                   5635:        my %uidhash=&idrget($udom,$uname);
1.196     www      5636:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5637:          && (!$forceid)) {
1.80      www      5638: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5639: 	      return 'error: user id "'.$uid.'" does not match '.
                   5640:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5641:           }
                   5642:        } else {
                   5643: 	  &idput($udom,($uname => $uid));
                   5644:        }
                   5645:     }
                   5646: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5647:     my @tmp=&get('environment',
1.899     raeburn  5648: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5649:                     'permanentemail','inststatus'],
1.134     albertel 5650: 		   $udom,$uname);
1.313     matthew  5651:     my %names;
                   5652:     if ($tmp[0] =~ m/^error:.*/) { 
                   5653:         %names=(); 
                   5654:     } else {
                   5655:         %names = @tmp;
                   5656:     }
1.388     www      5657: #
                   5658: # Make sure to not trash student environment if instructor does not bother
                   5659: # to supply name and email information
                   5660: #
                   5661:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5662:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5663:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5664:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5665:     if ($email) {
                   5666:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5667:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5668:     }
1.899     raeburn  5669:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5670:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5671:     my $reply = &put('environment', \%names, $udom,$uname);
                   5672:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5673:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5674:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5675:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5676:                  $umode.', '.$first.', '.$middle.', '.
                   5677: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5678:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5679:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5680:     } else {
                   5681:         $logmsg .= ' during self creation';
                   5682:     }
                   5683:     &logthis($logmsg);
1.134     albertel 5684:     return 'ok';
1.80      www      5685: }
                   5686: 
1.81      www      5687: # -------------------------------------------------------------- Modify student
1.80      www      5688: 
1.81      www      5689: sub modifystudent {
                   5690:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5691:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5692:         $selfenroll,$context)=@_;
1.455     albertel 5693:     if (!$cid) {
1.620     albertel 5694: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5695: 	    return 'not_in_class';
                   5696: 	}
1.80      www      5697:     }
                   5698: # --------------------------------------------------------------- Make the user
1.81      www      5699:     my $reply=&modifyuser
1.209     matthew  5700: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5701:          $desiredhome,$email);
1.80      www      5702:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5703:     # This will cause &modify_student_enrollment to get the uid from the
                   5704:     # students environment
                   5705:     $uid = undef if (!$forceid);
1.455     albertel 5706:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5707: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5708:     return $reply;
                   5709: }
                   5710: 
                   5711: sub modify_student_enrollment {
1.957     raeburn  5712:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5713:     my ($cdom,$cnum,$chome);
                   5714:     if (!$cid) {
1.620     albertel 5715: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5716: 	    return 'not_in_class';
                   5717: 	}
1.620     albertel 5718: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5719: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5720:     } else {
                   5721: 	($cdom,$cnum)=split(/_/,$cid);
                   5722:     }
1.620     albertel 5723:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5724:     if (!$chome) {
1.457     raeburn  5725: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5726:     }
1.455     albertel 5727:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5728:     # Make sure the user exists
1.81      www      5729:     my $uhome=&homeserver($uname,$udom);
                   5730:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5731: 	return 'error: no such user';
                   5732:     }
1.297     matthew  5733:     # Get student data if we were not given enough information
                   5734:     if (!defined($first)  || $first  eq '' || 
                   5735:         !defined($last)   || $last   eq '' || 
                   5736:         !defined($uid)    || $uid    eq '' || 
                   5737:         !defined($middle) || $middle eq '' || 
                   5738:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5739:         # They did not supply us with enough data to enroll the student, so
                   5740:         # we need to pick up more information.
1.297     matthew  5741:         my %tmp = &get('environment',
1.294     matthew  5742:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5743:                        ,$udom,$uname);
                   5744: 
1.800     albertel 5745:         #foreach my $key (keys(%tmp)) {
                   5746:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5747:         #}
1.294     matthew  5748:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5749:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5750:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5751:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5752:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5753:     }
1.556     albertel 5754:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5755:     my $reply=cput('classlist',
                   5756: 		   {"$uname:$udom" => 
1.515     raeburn  5757: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5758: 		   $cdom,$cnum);
1.81      www      5759:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5760: 	return 'error: '.$reply;
1.652     albertel 5761:     } else {
                   5762: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5763:     }
1.297     matthew  5764:     # Add student role to user
1.83      www      5765:     my $uurl='/'.$cid;
1.81      www      5766:     $uurl=~s/\_/\//g;
                   5767:     if ($usec) {
                   5768: 	$uurl.='/'.$usec;
                   5769:     }
1.957     raeburn  5770:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5771: }
                   5772: 
1.556     albertel 5773: sub format_name {
                   5774:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5775:     my $name;
                   5776:     if ($first ne 'lastname') {
                   5777: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5778:     } else {
                   5779: 	if ($lastname=~/\S/) {
                   5780: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5781: 	    $name=~s/\s+,/,/;
                   5782: 	} else {
                   5783: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5784: 	}
                   5785:     }
                   5786:     $name=~s/^\s+//;
                   5787:     $name=~s/\s+$//;
                   5788:     $name=~s/\s+/ /g;
                   5789:     return $name;
                   5790: }
                   5791: 
1.84      www      5792: # ------------------------------------------------- Write to course preferences
                   5793: 
                   5794: sub writecoursepref {
                   5795:     my ($courseid,%prefs)=@_;
                   5796:     $courseid=~s/^\///;
                   5797:     $courseid=~s/\_/\//g;
                   5798:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5799:     my $chome=homeserver($cnum,$cdomain);
                   5800:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5801: 	return 'error: no such course';
                   5802:     }
                   5803:     my $cstring='';
1.800     albertel 5804:     foreach my $pref (keys(%prefs)) {
                   5805: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5806:     }
1.84      www      5807:     $cstring=~s/\&$//;
                   5808:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5809: }
                   5810: 
                   5811: # ---------------------------------------------------------- Make/modify course
                   5812: 
                   5813: sub createcourse {
1.741     raeburn  5814:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5815:         $course_owner,$crstype)=@_;
1.84      www      5816:     $url=&declutter($url);
                   5817:     my $cid='';
1.264     matthew  5818:     unless (&allowed('ccc',$udom)) {
1.84      www      5819:         return 'refused';
                   5820:     }
                   5821: # ------------------------------------------------------------------- Create ID
1.674     www      5822:    my $uname=int(1+rand(9)).
                   5823:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5824:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5825:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5826: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5827:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5828:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5829:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5830:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5831:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5832:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5833:            return 'error: unable to generate unique course-ID';
                   5834:        } 
                   5835:    }
1.264     matthew  5836: # ------------------------------------------------ Check supplied server name
1.620     albertel 5837:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5838:     if (! &is_library($course_server)) {
1.264     matthew  5839:         return 'error:bad server name '.$course_server;
                   5840:     }
1.84      www      5841: # ------------------------------------------------------------- Make the course
                   5842:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5843:                       $course_server);
1.84      www      5844:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5845:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5846:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5847: 	return 'error: no such course';
                   5848:     }
1.271     www      5849: # ----------------------------------------------------------------- Course made
1.516     raeburn  5850: # log existence
1.918     raeburn  5851:     my $newcourse = {
                   5852:                     $udom.'_'.$uname => {
1.921     raeburn  5853:                                      description => $description,
                   5854:                                      inst_code   => $inst_code,
                   5855:                                      owner       => $course_owner,
                   5856:                                      type        => $crstype,
1.918     raeburn  5857:                                                 },
                   5858:                     };
1.921     raeburn  5859:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5860: # set toplevel url
1.271     www      5861:     my $topurl=$url;
                   5862:     unless ($nonstandard) {
                   5863: # ------------------------------------------ For standard courses, make top url
                   5864:         my $mapurl=&clutter($url);
1.278     www      5865:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5866:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5867: <map>
                   5868: <resource id="1" type="start"></resource>
                   5869: <resource id="2" src="$mapurl"></resource>
                   5870: <resource id="3" type="finish"></resource>
                   5871: <link index="1" from="1" to="2"></link>
                   5872: <link index="2" from="2" to="3"></link>
                   5873: </map>
                   5874: ENDINITMAP
                   5875:         $topurl=&declutter(
1.638     albertel 5876:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5877:                           );
                   5878:     }
                   5879: # ----------------------------------------------------------- Write preferences
1.84      www      5880:     &writecoursepref($udom.'_'.$uname,
                   5881:                      ('description' => $description,
1.271     www      5882:                       'url'         => $topurl));
1.84      www      5883:     return '/'.$udom.'/'.$uname;
                   5884: }
                   5885: 
1.813     albertel 5886: sub is_course {
                   5887:     my ($cdom,$cnum) = @_;
                   5888:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5889: 				undef,'.');
1.813     albertel 5890:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5891:         return 1;
                   5892:     }
                   5893:     return 0;
                   5894: }
                   5895: 
1.21      www      5896: # ---------------------------------------------------------- Assign Custom Role
                   5897: 
                   5898: sub assigncustomrole {
1.957     raeburn  5899:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5900:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  5901:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      5902: }
                   5903: 
                   5904: # ----------------------------------------------------------------- Revoke Role
                   5905: 
                   5906: sub revokerole {
1.957     raeburn  5907:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5908:     my $now=time;
1.965     raeburn  5909:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      5910: }
                   5911: 
                   5912: # ---------------------------------------------------------- Revoke Custom Role
                   5913: 
                   5914: sub revokecustomrole {
1.957     raeburn  5915:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5916:     my $now=time;
1.357     www      5917:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  5918:            $deleteflag,$selfenroll,$context);
1.17      www      5919: }
                   5920: 
1.533     banghart 5921: # ------------------------------------------------------------ Disk usage
1.535     albertel 5922: sub diskusage {
1.955     raeburn  5923:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   5924:     $directorypath =~ s/\/$//;
                   5925:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   5926:                        .&escape($getpropath).':'.&escape($uname).':'
                   5927:                        .&escape($udom),homeserver($uname,$udom));
                   5928:     if ($listing eq 'unknown_cmd') {
                   5929:         if ($getpropath) {
                   5930:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   5931:         }
                   5932:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   5933:     }
1.514     albertel 5934:     return $listing;
1.512     banghart 5935: }
                   5936: 
1.566     banghart 5937: sub is_locked {
                   5938:     my ($file_name, $domain, $user) = @_;
                   5939:     my @check;
                   5940:     my $is_locked;
                   5941:     push @check, $file_name;
1.613     albertel 5942:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5943: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5944:     my ($tmp)=keys(%locked);
                   5945:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5946:     
1.566     banghart 5947:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5948:         $is_locked = 'false';
                   5949:         foreach my $entry (@{$locked{$file_name}}) {
                   5950:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5951:                $is_locked = 'true';
                   5952:                last;
1.745     raeburn  5953:            }
                   5954:        }
1.566     banghart 5955:     } else {
                   5956:         $is_locked = 'false';
                   5957:     }
                   5958: }
                   5959: 
1.759     albertel 5960: sub declutter_portfile {
                   5961:     my ($file) = @_;
1.833     albertel 5962:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5963:     return $file;
                   5964: }
                   5965: 
1.559     banghart 5966: # ------------------------------------------------------------- Mark as Read Only
                   5967: 
                   5968: sub mark_as_readonly {
                   5969:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5970:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5971:     my ($tmp)=keys(%current_permissions);
                   5972:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5973:     foreach my $file (@{$files}) {
1.759     albertel 5974: 	$file = &declutter_portfile($file);
1.561     banghart 5975:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5976:     }
1.613     albertel 5977:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5978:     return;
                   5979: }
                   5980: 
1.572     banghart 5981: # ------------------------------------------------------------Save Selected Files
                   5982: 
                   5983: sub save_selected_files {
                   5984:     my ($user, $path, @files) = @_;
                   5985:     my $filename = $user."savedfiles";
1.573     banghart 5986:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5987:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5988:     foreach my $file (@files) {
1.620     albertel 5989:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5990:     }
                   5991:     foreach my $file (@other_files) {
1.574     banghart 5992:         print (OUT $file."\n");
1.572     banghart 5993:     }
1.574     banghart 5994:     close (OUT);
1.572     banghart 5995:     return 'ok';
                   5996: }
                   5997: 
1.574     banghart 5998: sub clear_selected_files {
                   5999:     my ($user) = @_;
                   6000:     my $filename = $user."savedfiles";
                   6001:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6002:     print (OUT undef);
                   6003:     close (OUT);
                   6004:     return ("ok");    
                   6005: }
                   6006: 
1.572     banghart 6007: sub files_in_path {
                   6008:     my ($user, $path) = @_;
                   6009:     my $filename = $user."savedfiles";
                   6010:     my %return_files;
1.574     banghart 6011:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6012:     while (my $line_in = <IN>) {
1.574     banghart 6013:         chomp ($line_in);
                   6014:         my @paths_and_file = split (m!/!, $line_in);
                   6015:         my $file_part = pop (@paths_and_file);
                   6016:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6017:         $path_part.='/';
                   6018:         my $path_and_file = $path_part.$file_part;
                   6019:         if ($path_part eq $path) {
                   6020:             $return_files{$file_part}= 'selected';
                   6021:         }
                   6022:     }
1.574     banghart 6023:     close (IN);
                   6024:     return (\%return_files);
1.572     banghart 6025: }
                   6026: 
                   6027: # called in portfolio select mode, to show files selected NOT in current directory
                   6028: sub files_not_in_path {
                   6029:     my ($user, $path) = @_;
                   6030:     my $filename = $user."savedfiles";
                   6031:     my @return_files;
                   6032:     my $path_part;
1.800     albertel 6033:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6034:     while (my $line = <IN>) {
1.572     banghart 6035:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6036:         my @paths_and_file = split(m|/|, $line);
                   6037:         my $file_part = pop(@paths_and_file);
                   6038:         chomp($file_part);
                   6039:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6040:         $path_part .= '/';
                   6041:         my $path_and_file = $path_part.$file_part;
                   6042:         if ($path_part ne $path) {
1.800     albertel 6043:             push(@return_files, ($path_and_file));
1.572     banghart 6044:         }
                   6045:     }
1.800     albertel 6046:     close(OUT);
1.574     banghart 6047:     return (@return_files);
1.572     banghart 6048: }
                   6049: 
1.745     raeburn  6050: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6051: 
1.745     raeburn  6052: sub get_portfile_permissions {
                   6053:     my ($domain,$user) = @_;
1.613     albertel 6054:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6055:     my ($tmp)=keys(%current_permissions);
                   6056:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6057:     return \%current_permissions;
                   6058: }
                   6059: 
                   6060: #---------------------------------------------Get portfolio file access controls
                   6061: 
1.749     raeburn  6062: sub get_access_controls {
1.745     raeburn  6063:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6064:     my %access;
                   6065:     my $real_file = $file;
                   6066:     $file =~ s/\.meta$//;
1.745     raeburn  6067:     if (defined($file)) {
1.749     raeburn  6068:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6069:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6070:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6071:             }
                   6072:         }
1.745     raeburn  6073:     } else {
1.749     raeburn  6074:         foreach my $key (keys(%{$current_permissions})) {
                   6075:             if ($key =~ /\0accesscontrol$/) {
                   6076:                 if (defined($group)) {
                   6077:                     if ($key !~ m-^\Q$group\E/-) {
                   6078:                         next;
                   6079:                     }
                   6080:                 }
                   6081:                 my ($fullpath) = split(/\0/,$key);
                   6082:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6083:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6084:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6085:                     }
                   6086:                 }
                   6087:             }
                   6088:         }
                   6089:     }
                   6090:     return %access;
                   6091: }
                   6092: 
                   6093: sub modify_access_controls {
                   6094:     my ($file_name,$changes,$domain,$user)=@_;
                   6095:     my ($outcome,$deloutcome);
                   6096:     my %store_permissions;
                   6097:     my %new_values;
                   6098:     my %new_control;
                   6099:     my %translation;
                   6100:     my @deletions = ();
                   6101:     my $now = time;
                   6102:     if (exists($$changes{'activate'})) {
                   6103:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6104:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6105:             my $numnew = scalar(@newitems);
                   6106:             for (my $i=0; $i<$numnew; $i++) {
                   6107:                 my $newkey = $newitems[$i];
                   6108:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6109:                 if ($newkey =~ /^\d+:/) { 
                   6110:                     $newkey =~ s/^(\d+)/$newid/;
                   6111:                     $translation{$1} = $newid;
                   6112:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6113:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6114:                     $translation{$1} = $newid;
                   6115:                 }
1.749     raeburn  6116:                 $new_values{$file_name."\0".$newkey} = 
                   6117:                                           $$changes{'activate'}{$newitems[$i]};
                   6118:                 $new_control{$newkey} = $now;
                   6119:             }
                   6120:         }
                   6121:     }
                   6122:     my %todelete;
                   6123:     my %changed_items;
                   6124:     foreach my $action ('delete','update') {
                   6125:         if (exists($$changes{$action})) {
                   6126:             if (ref($$changes{$action}) eq 'HASH') {
                   6127:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6128:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6129:                     if ($action eq 'delete') { 
                   6130:                         $todelete{$itemnum} = 1;
                   6131:                     } else {
                   6132:                         $changed_items{$itemnum} = $key;
                   6133:                     }
                   6134:                 }
1.745     raeburn  6135:             }
                   6136:         }
1.749     raeburn  6137:     }
                   6138:     # get lock on access controls for file.
                   6139:     my $lockhash = {
                   6140:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6141:                                                        ':'.$env{'user.domain'},
                   6142:                    }; 
                   6143:     my $tries = 0;
                   6144:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6145:    
                   6146:     while (($gotlock ne 'ok') && $tries <3) {
                   6147:         $tries ++;
                   6148:         sleep 1;
                   6149:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6150:     }
                   6151:     if ($gotlock eq 'ok') {
                   6152:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6153:         my ($tmp)=keys(%curr_permissions);
                   6154:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6155:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6156:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6157:             if (ref($curr_controls) eq 'HASH') {
                   6158:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6159:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6160:                     if (defined($todelete{$itemnum})) {
                   6161:                         push(@deletions,$file_name."\0".$control_item);
                   6162:                     } else {
                   6163:                         if (defined($changed_items{$itemnum})) {
                   6164:                             $new_control{$changed_items{$itemnum}} = $now;
                   6165:                             push(@deletions,$file_name."\0".$control_item);
                   6166:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6167:                         } else {
                   6168:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6169:                         }
                   6170:                     }
1.745     raeburn  6171:                 }
                   6172:             }
                   6173:         }
1.970     raeburn  6174:         my ($group);
                   6175:         if (&is_course($domain,$user)) {
                   6176:             ($group,my $file) = split(/\//,$file_name,2);
                   6177:         }
1.749     raeburn  6178:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6179:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6180:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6181:         #  remove lock
                   6182:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6183:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6184:         my $sqlresult =
1.970     raeburn  6185:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6186:                                     $group);
1.749     raeburn  6187:     } else {
                   6188:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6189:     }
1.749     raeburn  6190:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6191: }
                   6192: 
1.827     raeburn  6193: sub make_public_indefinitely {
                   6194:     my ($requrl) = @_;
                   6195:     my $now = time;
                   6196:     my $action = 'activate';
                   6197:     my $aclnum = 0;
                   6198:     if (&is_portfolio_url($requrl)) {
                   6199:         my (undef,$udom,$unum,$file_name,$group) =
                   6200:             &parse_portfolio_url($requrl);
                   6201:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6202:         my %access_controls = &get_access_controls($current_perms,
                   6203:                                                    $group,$file_name);
                   6204:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6205:             my ($num,$scope,$end,$start) = 
                   6206:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6207:             if ($scope eq 'public') {
                   6208:                 if ($start <= $now && $end == 0) {
                   6209:                     $action = 'none';
                   6210:                 } else {
                   6211:                     $action = 'update';
                   6212:                     $aclnum = $num;
                   6213:                 }
                   6214:                 last;
                   6215:             }
                   6216:         }
                   6217:         if ($action eq 'none') {
                   6218:              return 'ok';
                   6219:         } else {
                   6220:             my %changes;
                   6221:             my $newend = 0;
                   6222:             my $newstart = $now;
                   6223:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6224:             $changes{$action}{$newkey} = {
                   6225:                 type => 'public',
                   6226:                 time => {
                   6227:                     start => $newstart,
                   6228:                     end   => $newend,
                   6229:                 },
                   6230:             };
                   6231:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6232:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6233:             return $outcome;
                   6234:         }
                   6235:     } else {
                   6236:         return 'invalid';
                   6237:     }
                   6238: }
                   6239: 
1.745     raeburn  6240: #------------------------------------------------------Get Marked as Read Only
                   6241: 
                   6242: sub get_marked_as_readonly {
                   6243:     my ($domain,$user,$what,$group) = @_;
                   6244:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6245:     my @readonly_files;
1.629     banghart 6246:     my $cmp1=$what;
                   6247:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6248:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6249:         if (defined($group)) {
                   6250:             if ($file_name !~ m-^\Q$group\E/-) {
                   6251:                 next;
                   6252:             }
                   6253:         }
1.561     banghart 6254:         if (ref($value) eq "ARRAY"){
                   6255:             foreach my $stored_what (@{$value}) {
1.629     banghart 6256:                 my $cmp2=$stored_what;
1.759     albertel 6257:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6258:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6259:                 }
1.629     banghart 6260:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6261:                     push(@readonly_files, $file_name);
1.745     raeburn  6262:                     last;
1.563     banghart 6263:                 } elsif (!defined($what)) {
                   6264:                     push(@readonly_files, $file_name);
1.745     raeburn  6265:                     last;
1.561     banghart 6266:                 }
                   6267:             }
1.745     raeburn  6268:         }
1.561     banghart 6269:     }
                   6270:     return @readonly_files;
                   6271: }
1.577     banghart 6272: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6273: 
1.577     banghart 6274: sub get_marked_as_readonly_hash {
1.745     raeburn  6275:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6276:     my %readonly_files;
1.745     raeburn  6277:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6278:         if (defined($group)) {
                   6279:             if ($file_name !~ m-^\Q$group\E/-) {
                   6280:                 next;
                   6281:             }
                   6282:         }
1.577     banghart 6283:         if (ref($value) eq "ARRAY"){
                   6284:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6285:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6286:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6287:                         if ($lock_descriptor eq 'graded') {
                   6288:                             $readonly_files{$file_name} = 'graded';
                   6289:                         } elsif ($lock_descriptor eq 'handback') {
                   6290:                             $readonly_files{$file_name} = 'handback';
                   6291:                         } else {
                   6292:                             if (!exists($readonly_files{$file_name})) {
                   6293:                                 $readonly_files{$file_name} = 'locked';
                   6294:                             }
                   6295:                         }
1.745     raeburn  6296:                     }
1.750     banghart 6297:                 } 
1.577     banghart 6298:             }
                   6299:         } 
                   6300:     }
                   6301:     return %readonly_files;
                   6302: }
1.559     banghart 6303: # ------------------------------------------------------------ Unmark as Read Only
                   6304: 
                   6305: sub unmark_as_readonly {
1.629     banghart 6306:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6307:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6308:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6309:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6310:     my $symb_crs = $what;
                   6311:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6312:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6313:     my ($tmp)=keys(%current_permissions);
                   6314:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6315:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6316:     foreach my $file (@readonly_files) {
1.759     albertel 6317: 	my $clean_file = &declutter_portfile($file);
                   6318: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6319: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6320:         my @new_locks;
                   6321:         my @del_keys;
                   6322:         if (ref($current_locks) eq "ARRAY"){
                   6323:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6324:                 my $compare=$locker;
1.749     raeburn  6325:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6326:                     $compare=join('',@{$locker});
1.746     raeburn  6327:                     if ($compare ne $symb_crs) {
                   6328:                         push(@new_locks, $locker);
                   6329:                     }
1.563     banghart 6330:                 }
                   6331:             }
1.650     albertel 6332:             if (scalar(@new_locks) > 0) {
1.563     banghart 6333:                 $current_permissions{$file} = \@new_locks;
                   6334:             } else {
                   6335:                 push(@del_keys, $file);
1.613     albertel 6336:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6337:                 delete($current_permissions{$file});
1.563     banghart 6338:             }
                   6339:         }
1.561     banghart 6340:     }
1.613     albertel 6341:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6342:     return;
                   6343: }
1.512     banghart 6344: 
1.17      www      6345: # ------------------------------------------------------------ Directory lister
                   6346: 
                   6347: sub dirlist {
1.955     raeburn  6348:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6349:     $uri=~s/^\///;
                   6350:     $uri=~s/\/$//;
1.253     stredwic 6351:     my ($udom, $uname);
1.955     raeburn  6352:     if ($getuserdir) {
1.253     stredwic 6353:         $udom = $userdomain;
                   6354:         $uname = $username;
1.955     raeburn  6355:     } else {
                   6356:         (undef,$udom,$uname)=split(/\//,$uri);
                   6357:         if(defined($userdomain)) {
                   6358:             $udom = $userdomain;
                   6359:         }
                   6360:         if(defined($username)) {
                   6361:             $uname = $username;
                   6362:         }
1.253     stredwic 6363:     }
1.955     raeburn  6364:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6365: 
1.955     raeburn  6366:     $dirRoot = $perlvar{'lonDocRoot'};
                   6367:     if (defined($getpropath)) {
                   6368:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6369:         $dirRoot =~ s/\/$//;
1.955     raeburn  6370:     } elsif (defined($getuserdir)) {
                   6371:         my $subdir=$uname.'__';
                   6372:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6373:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6374:                    ."/$udom/$subdir/$uname";
                   6375:     } elsif (defined($alternateRoot)) {
                   6376:         $dirRoot = $alternateRoot;
1.751     banghart 6377:     }
1.253     stredwic 6378: 
                   6379:     if($udom) {
                   6380:         if($uname) {
1.955     raeburn  6381:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6382:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6383:                               .':'.&escape($uname).':'.&escape($udom),
                   6384:                               &homeserver($uname,$udom));
                   6385:             if ($listing eq 'unknown_cmd') {
                   6386:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6387:                                   &homeserver($uname,$udom));
                   6388:             } else {
                   6389:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6390:             }
1.605     matthew  6391:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6392:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6393: 				  &homeserver($uname,$udom));
1.605     matthew  6394:                 @listing_results = split(/:/,$listing);
                   6395:             } else {
                   6396:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6397:             }
                   6398:             return @listing_results;
1.955     raeburn  6399:         } elsif(!$alternateRoot) {
1.800     albertel 6400:             my %allusers;
1.841     albertel 6401: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6402:  	    foreach my $tryserver (keys(%servers)) {
                   6403:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6404:                                   &escape($udom),$tryserver);
                   6405:                 if ($listing eq 'unknown_cmd') {
                   6406: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6407: 				      $udom, $tryserver);
                   6408:                 } else {
                   6409:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6410:                 }
1.841     albertel 6411: 		if ($listing eq 'unknown_cmd') {
                   6412: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6413: 				      $udom, $tryserver);
                   6414: 		    @listing_results = split(/:/,$listing);
                   6415: 		} else {
                   6416: 		    @listing_results =
                   6417: 			map { &unescape($_); } split(/:/,$listing);
                   6418: 		}
                   6419: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6420: 		    $listing_results[0] ne 'empty'       &&
                   6421: 		    $listing_results[0] ne 'con_lost') {
                   6422: 		    foreach my $line (@listing_results) {
                   6423: 			my ($entry) = split(/&/,$line,2);
                   6424: 			$allusers{$entry} = 1;
                   6425: 		    }
                   6426: 		}
1.253     stredwic 6427:             }
                   6428:             my $alluserstr='';
1.800     albertel 6429:             foreach my $user (sort(keys(%allusers))) {
                   6430:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6431:             }
                   6432:             $alluserstr=~s/:$//;
                   6433:             return split(/:/,$alluserstr);
                   6434:         } else {
1.800     albertel 6435:             return ('missing user name');
1.253     stredwic 6436:         }
1.955     raeburn  6437:     } elsif(!defined($getpropath)) {
1.841     albertel 6438:         my @all_domains = sort(&all_domains());
1.955     raeburn  6439:         foreach my $domain (@all_domains) {
                   6440:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6441:         }
                   6442:         return @all_domains;
                   6443:     } else {
1.800     albertel 6444:         return ('missing domain');
1.275     stredwic 6445:     }
                   6446: }
                   6447: 
                   6448: # --------------------------------------------- GetFileTimestamp
                   6449: # This function utilizes dirlist and returns the date stamp for
                   6450: # when it was last modified.  It will also return an error of -1
                   6451: # if an error occurs
                   6452: 
                   6453: sub GetFileTimestamp {
1.955     raeburn  6454:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6455:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6456:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6457:     my ($fileStat) = 
                   6458:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6459:                                  undef,$getuserdir);
1.275     stredwic 6460:     my @stats = split('&', $fileStat);
                   6461:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6462:         # @stats contains first the filename, then the stat output
                   6463:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6464:     } else {
                   6465:         return -1;
1.253     stredwic 6466:     }
1.26      www      6467: }
                   6468: 
1.712     albertel 6469: sub stat_file {
                   6470:     my ($uri) = @_;
1.787     albertel 6471:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6472: 
1.955     raeburn  6473:     my ($udom,$uname,$file);
1.712     albertel 6474:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6475: 	($udom,$uname,$file) =
1.811     albertel 6476: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6477: 	$file = 'userfiles/'.$file;
                   6478:     }
                   6479:     if ($uri =~ m-^/res/-) {
                   6480: 	($udom,$uname) = 
1.807     albertel 6481: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6482: 	$file = $uri;
                   6483:     }
                   6484: 
                   6485:     if (!$udom || !$uname || !$file) {
                   6486: 	# unable to handle the uri
                   6487: 	return ();
                   6488:     }
1.956     raeburn  6489:     my $getpropath;
                   6490:     if ($file =~ /^userfiles\//) {
                   6491:         $getpropath = 1;
                   6492:     }
1.955     raeburn  6493:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6494:     my @stats = split('&', $result);
1.721     banghart 6495:     
1.712     albertel 6496:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6497: 	shift(@stats); #filename is first
                   6498: 	return @stats;
                   6499:     }
                   6500:     return ();
                   6501: }
                   6502: 
1.26      www      6503: # -------------------------------------------------------- Value of a Condition
                   6504: 
1.713     albertel 6505: # gets the value of a specific preevaluated condition
                   6506: #    stored in the string  $env{user.state.<cid>}
                   6507: # or looks up a condition reference in the bighash and if if hasn't
                   6508: # already been evaluated recurses into docondval to get the value of
                   6509: # the condition, then memoizing it to 
                   6510: #   $env{user.state.<cid>.<condition>}
1.40      www      6511: sub directcondval {
                   6512:     my $number=shift;
1.620     albertel 6513:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6514: 	&Apache::lonuserstate::evalstate();
                   6515:     }
1.713     albertel 6516:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6517: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6518:     } elsif ($number =~ /^_/) {
                   6519: 	my $sub_condition;
                   6520: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6521: 		&GDBM_READER(),0640)) {
                   6522: 	    $sub_condition=$bighash{'conditions'.$number};
                   6523: 	    untie(%bighash);
                   6524: 	}
                   6525: 	my $value = &docondval($sub_condition);
1.949     raeburn  6526: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6527: 	return $value;
                   6528:     }
1.620     albertel 6529:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6530:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6531:     } else {
                   6532:        return 2;
                   6533:     }
                   6534: }
                   6535: 
1.713     albertel 6536: # get the collection of conditions for this resource
1.26      www      6537: sub condval {
                   6538:     my $condidx=shift;
1.54      www      6539:     my $allpathcond='';
1.713     albertel 6540:     foreach my $cond (split(/\|/,$condidx)) {
                   6541: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6542: 	    $allpathcond.=
                   6543: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6544: 	}
1.191     harris41 6545:     }
1.54      www      6546:     $allpathcond=~s/\|$//;
1.713     albertel 6547:     return &docondval($allpathcond);
                   6548: }
                   6549: 
                   6550: #evaluates an expression of conditions
                   6551: sub docondval {
                   6552:     my ($allpathcond) = @_;
                   6553:     my $result=0;
                   6554:     if ($env{'request.course.id'}
                   6555: 	&& defined($allpathcond)) {
                   6556: 	my $operand='|';
                   6557: 	my @stack;
                   6558: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6559: 	    if ($chunk eq '(') {
                   6560: 		push @stack,($operand,$result);
                   6561: 	    } elsif ($chunk eq ')') {
                   6562: 		my $before=pop @stack;
                   6563: 		if (pop @stack eq '&') {
                   6564: 		    $result=$result>$before?$before:$result;
                   6565: 		} else {
                   6566: 		    $result=$result>$before?$result:$before;
                   6567: 		}
                   6568: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6569: 		$operand=$chunk;
                   6570: 	    } else {
                   6571: 		my $new=directcondval($chunk);
                   6572: 		if ($operand eq '&') {
                   6573: 		    $result=$result>$new?$new:$result;
                   6574: 		} else {
                   6575: 		    $result=$result>$new?$result:$new;
                   6576: 		}
                   6577: 	    }
                   6578: 	}
1.26      www      6579:     }
                   6580:     return $result;
1.421     albertel 6581: }
                   6582: 
                   6583: # ---------------------------------------------------- Devalidate courseresdata
                   6584: 
                   6585: sub devalidatecourseresdata {
                   6586:     my ($coursenum,$coursedomain)=@_;
                   6587:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6588:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6589: }
                   6590: 
1.763     www      6591: 
1.200     www      6592: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6593: #
                   6594: #  Parameters:
                   6595: #      $coursenum    - Number of the course.
                   6596: #      $coursedomain - Domain at which the course was created.
                   6597: #  Returns:
                   6598: #     A hash of the course parameters along (I think) with timestamps
                   6599: #     and version info.
1.877     foxr     6600: 
1.624     albertel 6601: sub get_courseresdata {
                   6602:     my ($coursenum,$coursedomain)=@_;
1.200     www      6603:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6604:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6605:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6606:     my %dumpreply;
1.417     albertel 6607:     unless (defined($cached)) {
1.624     albertel 6608: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6609: 	$result=\%dumpreply;
1.251     albertel 6610: 	my ($tmp) = keys(%dumpreply);
                   6611: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6612: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6613: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6614: 	    return $tmp;
1.416     albertel 6615: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6616: 	    $result=undef;
1.599     albertel 6617: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6618: 	}
                   6619:     }
1.624     albertel 6620:     return $result;
                   6621: }
                   6622: 
1.633     albertel 6623: sub devalidateuserresdata {
                   6624:     my ($uname,$udom)=@_;
                   6625:     my $hashid="$udom:$uname";
                   6626:     &devalidate_cache_new('userres',$hashid);
                   6627: }
                   6628: 
1.624     albertel 6629: sub get_userresdata {
                   6630:     my ($uname,$udom)=@_;
                   6631:     #most student don\'t have any data set, check if there is some data
                   6632:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6633: 
                   6634:     my $hashid="$udom:$uname";
                   6635:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6636:     if (!defined($cached)) {
                   6637: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6638: 	$result=\%resourcedata;
                   6639: 	&do_cache_new('userres',$hashid,$result,600);
                   6640:     }
                   6641:     my ($tmp)=keys(%$result);
                   6642:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6643: 	return $result;
                   6644:     }
                   6645:     #error 2 occurs when the .db doesn't exist
                   6646:     if ($tmp!~/error: 2 /) {
1.672     albertel 6647: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6648: 		 " Trying to get resource data for ".
                   6649: 		 $uname." at ".$udom.": ".
                   6650: 		 $tmp."</font>");
                   6651:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6652: 	#&EXT_cache_set($udom,$uname);
                   6653: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6654: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6655:     }
                   6656:     return $tmp;
                   6657: }
1.879     foxr     6658: #----------------------------------------------- resdata - return resource data
                   6659: #  Purpose:
                   6660: #    Return resource data for either users or for a course.
                   6661: #  Parameters:
                   6662: #     $name      - Course/user name.
                   6663: #     $domain    - Name of the domain the user/course is registered on.
                   6664: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6665: #     @which     - Array of names of resources desired.
                   6666: #  Returns:
                   6667: #     The value of the first reasource in @which that is found in the
                   6668: #     resource hash.
                   6669: #  Exceptional Conditions:
                   6670: #     If the $type passed in is not valid (not the string 'course' or 
                   6671: #     'user', an undefined  reference is returned.
                   6672: #     If none of the resources are found, an undef is returned
1.624     albertel 6673: sub resdata {
                   6674:     my ($name,$domain,$type,@which)=@_;
                   6675:     my $result;
                   6676:     if ($type eq 'course') {
                   6677: 	$result=&get_courseresdata($name,$domain);
                   6678:     } elsif ($type eq 'user') {
                   6679: 	$result=&get_userresdata($name,$domain);
                   6680:     }
                   6681:     if (!ref($result)) { return $result; }    
1.251     albertel 6682:     foreach my $item (@which) {
1.927     albertel 6683: 	if (defined($result->{$item->[0]})) {
                   6684: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6685: 	}
1.250     albertel 6686:     }
1.291     albertel 6687:     return undef;
1.200     www      6688: }
                   6689: 
1.379     matthew  6690: #
                   6691: # EXT resource caching routines
                   6692: #
                   6693: 
                   6694: sub clear_EXT_cache_status {
1.383     albertel 6695:     &delenv('cache.EXT.');
1.379     matthew  6696: }
                   6697: 
                   6698: sub EXT_cache_status {
                   6699:     my ($target_domain,$target_user) = @_;
1.383     albertel 6700:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6701:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6702:         # We know already the user has no data
                   6703:         return 1;
                   6704:     } else {
                   6705:         return 0;
                   6706:     }
                   6707: }
                   6708: 
                   6709: sub EXT_cache_set {
                   6710:     my ($target_domain,$target_user) = @_;
1.383     albertel 6711:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6712:     #&appenv({$cachename => time});
1.379     matthew  6713: }
                   6714: 
1.28      www      6715: # --------------------------------------------------------- Value of a Variable
1.58      www      6716: sub EXT {
1.715     albertel 6717: 
1.395     albertel 6718:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6719:     unless ($varname) { return ''; }
1.218     albertel 6720:     #get real user name/domain, courseid and symb
                   6721:     my $courseid;
1.359     albertel 6722:     my $publicuser;
1.427     www      6723:     if ($symbparm) {
                   6724: 	$symbparm=&get_symb_from_alias($symbparm);
                   6725:     }
1.218     albertel 6726:     if (!($uname && $udom)) {
1.790     albertel 6727:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6728:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6729:     } else {
1.620     albertel 6730: 	$courseid=$env{'request.course.id'};
1.218     albertel 6731:     }
1.48      www      6732:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6733:     my $rest;
1.320     albertel 6734:     if (defined($therest[0])) {
1.48      www      6735:        $rest=join('.',@therest);
                   6736:     } else {
                   6737:        $rest='';
                   6738:     }
1.320     albertel 6739: 
1.57      www      6740:     my $qualifierrest=$qualifier;
                   6741:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6742:     my $spacequalifierrest=$space;
                   6743:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6744:     if ($realm eq 'user') {
1.48      www      6745: # --------------------------------------------------------------- user.resource
                   6746: 	if ($space eq 'resource') {
1.651     albertel 6747: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6748: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6749: 		 &&
1.744     albertel 6750: 		 ($symbparm eq &symbread()) ) {	
                   6751: 		# if we are in the middle of processing the resource the
                   6752: 		# get the value we are planning on committing
                   6753:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6754:                     return $Apache::lonhomework::results{$qualifierrest};
                   6755:                 } else {
                   6756:                     return $Apache::lonhomework::history{$qualifierrest};
                   6757:                 }
1.335     albertel 6758: 	    } else {
1.359     albertel 6759: 		my %restored;
1.620     albertel 6760: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6761: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6762: 		} else {
                   6763: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6764: 		}
1.335     albertel 6765: 		return $restored{$qualifierrest};
                   6766: 	    }
1.48      www      6767: # ----------------------------------------------------------------- user.access
                   6768:         } elsif ($space eq 'access') {
1.218     albertel 6769: 	    # FIXME - not supporting calls for a specific user
1.48      www      6770:             return &allowed($qualifier,$rest);
                   6771: # ------------------------------------------ user.preferences, user.environment
                   6772:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6773: 	    if (($uname eq $env{'user.name'}) &&
                   6774: 		($udom eq $env{'user.domain'})) {
                   6775: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6776: 	    } else {
1.359     albertel 6777: 		my %returnhash;
                   6778: 		if (!$publicuser) {
                   6779: 		    %returnhash=&userenvironment($udom,$uname,
                   6780: 						 $qualifierrest);
                   6781: 		}
1.218     albertel 6782: 		return $returnhash{$qualifierrest};
                   6783: 	    }
1.48      www      6784: # ----------------------------------------------------------------- user.course
                   6785:         } elsif ($space eq 'course') {
1.218     albertel 6786: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6787:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6788: # ------------------------------------------------------------------- user.role
                   6789:         } elsif ($space eq 'role') {
1.218     albertel 6790: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6791:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6792:             if ($qualifier eq 'value') {
                   6793: 		return $role;
                   6794:             } elsif ($qualifier eq 'extent') {
                   6795:                 return $where;
                   6796:             }
                   6797: # ----------------------------------------------------------------- user.domain
                   6798:         } elsif ($space eq 'domain') {
1.218     albertel 6799:             return $udom;
1.48      www      6800: # ------------------------------------------------------------------- user.name
                   6801:         } elsif ($space eq 'name') {
1.218     albertel 6802:             return $uname;
1.48      www      6803: # ---------------------------------------------------- Any other user namespace
1.29      www      6804:         } else {
1.359     albertel 6805: 	    my %reply;
                   6806: 	    if (!$publicuser) {
                   6807: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6808: 	    }
                   6809: 	    return $reply{$qualifierrest};
1.48      www      6810:         }
1.236     www      6811:     } elsif ($realm eq 'query') {
                   6812: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6813:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6814: 						[$spacequalifierrest]);
1.620     albertel 6815: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6816:    } elsif ($realm eq 'request') {
1.48      www      6817: # ------------------------------------------------------------- request.browser
                   6818:         if ($space eq 'browser') {
1.430     www      6819: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6820: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6821: 		    return 1;
                   6822: 		} else {
                   6823: 		    return 0;
                   6824: 		}
                   6825: 	    } else {
1.620     albertel 6826: 		return $env{'browser.'.$qualifier};
1.430     www      6827: 	    }
1.57      www      6828: # ------------------------------------------------------------ request.filename
                   6829:         } else {
1.620     albertel 6830:             return $env{'request.'.$spacequalifierrest};
1.29      www      6831:         }
1.28      www      6832:     } elsif ($realm eq 'course') {
1.48      www      6833: # ---------------------------------------------------------- course.description
1.620     albertel 6834:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6835:     } elsif ($realm eq 'resource') {
1.165     www      6836: 
1.620     albertel 6837: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6838: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6839: 	}
1.693     albertel 6840: 
                   6841: 	if ($space eq 'title') {
                   6842: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6843: 	    return &gettitle($symbparm);
                   6844: 	}
                   6845: 	
                   6846: 	if ($space eq 'map') {
                   6847: 	    my ($map) = &decode_symb($symbparm);
                   6848: 	    return &symbread($map);
                   6849: 	}
1.905     albertel 6850: 	if ($space eq 'filename') {
                   6851: 	    if ($symbparm) {
                   6852: 		return &clutter((&decode_symb($symbparm))[2]);
                   6853: 	    }
                   6854: 	    return &hreflocation('',$env{'request.filename'});
                   6855: 	}
1.693     albertel 6856: 
                   6857: 	my ($section, $group, @groups);
1.593     albertel 6858: 	my ($courselevelm,$courselevel);
1.539     albertel 6859: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6860: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6861: 
1.218     albertel 6862: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6863: 
1.60      www      6864: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6865: 	    my $symbp=$symbparm;
1.735     albertel 6866: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6867: 
                   6868: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6869: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6870: 
1.620     albertel 6871: 	    if (($env{'user.name'} eq $uname) &&
                   6872: 		($env{'user.domain'} eq $udom)) {
                   6873: 		$section=$env{'request.course.sec'};
1.733     raeburn  6874:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6875:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6876: 	    } else {
1.539     albertel 6877: 		if (! defined($usection)) {
1.551     albertel 6878: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6879: 		} else {
                   6880: 		    $section = $usection;
                   6881: 		}
1.733     raeburn  6882:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6883: 	    }
                   6884: 
                   6885: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6886: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6887: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6888: 
1.593     albertel 6889: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6890: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6891: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6892: 
1.60      www      6893: # ----------------------------------------------------------- first, check user
1.624     albertel 6894: 
                   6895: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6896: 				       ([$courselevelr,'resource'],
                   6897: 					[$courselevelm,'map'     ],
                   6898: 					[$courselevel, 'course'  ]));
1.931     albertel 6899: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6900: 
1.594     albertel 6901: # ------------------------------------------------ second, check some of course
1.684     raeburn  6902:             my $coursereply;
1.691     raeburn  6903:             if (@groups > 0) {
                   6904:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6905:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6906:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6907:             }
1.96      www      6908: 
1.684     raeburn  6909: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6910: 				  $env{'course.'.$courseid.'.domain'},
                   6911: 				  'course',
                   6912: 				  ([$seclevelr,   'resource'],
                   6913: 				   [$seclevelm,   'map'     ],
                   6914: 				   [$seclevel,    'course'  ],
                   6915: 				   [$courselevelr,'resource']));
                   6916: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6917: 
1.60      www      6918: # ------------------------------------------------------ third, check map parms
1.218     albertel 6919: 	    my %parmhash=();
                   6920: 	    my $thisparm='';
                   6921: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6922: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6923: 		    &GDBM_READER(),0640)) {
1.218     albertel 6924: 		$thisparm=$parmhash{$symbparm};
                   6925: 		untie(%parmhash);
                   6926: 	    }
1.927     albertel 6927: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6928: 	}
1.594     albertel 6929: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6930: 
1.218     albertel 6931: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6932: 	my $filename;
                   6933: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6934: 	if ($symbparm) {
1.409     www      6935: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6936: 	} else {
1.620     albertel 6937: 	    $filename=$env{'request.filename'};
1.282     albertel 6938: 	}
                   6939: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6940: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6941: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6942: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6943: 
1.927     albertel 6944: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6945: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6946: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6947: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6948: 				     $env{'course.'.$courseid.'.domain'},
                   6949: 				     'course',
1.927     albertel 6950: 				     ([$courselevelm,'map'   ],
                   6951: 				      [$courselevel, 'course']));
                   6952: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6953: 	}
1.145     www      6954: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6955: 	unless ($space eq '0') {
1.336     albertel 6956: 	    my @parts=split(/_/,$space);
                   6957: 	    my $id=pop(@parts);
                   6958: 	    my $part=join('_',@parts);
                   6959: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6960: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6961: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6962: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6963: 	}
1.395     albertel 6964: 	if ($recurse) { return undef; }
                   6965: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6966: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6967: # ---------------------------------------------------- Any other user namespace
                   6968:     } elsif ($realm eq 'environment') {
                   6969: # ----------------------------------------------------------------- environment
1.620     albertel 6970: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6971: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6972: 	} else {
1.770     albertel 6973: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6974: 		return '';
                   6975: 	    }
1.219     albertel 6976: 	    my %returnhash=&userenvironment($udom,$uname,
                   6977: 					    $spacequalifierrest);
                   6978: 	    return $returnhash{$spacequalifierrest};
                   6979: 	}
1.28      www      6980:     } elsif ($realm eq 'system') {
1.48      www      6981: # ----------------------------------------------------------------- system.time
                   6982: 	if ($space eq 'time') {
                   6983: 	    return time;
                   6984:         }
1.696     albertel 6985:     } elsif ($realm eq 'server') {
                   6986: # ----------------------------------------------------------------- system.time
                   6987: 	if ($space eq 'name') {
                   6988: 	    return $ENV{'SERVER_NAME'};
                   6989:         }
1.28      www      6990:     }
1.48      www      6991:     return '';
1.61      www      6992: }
                   6993: 
1.927     albertel 6994: sub get_reply {
                   6995:     my ($reply_value) = @_;
1.940     raeburn  6996:     if (ref($reply_value) eq 'ARRAY') {
                   6997:         if (wantarray) {
                   6998: 	    return @$reply_value;
                   6999:         }
                   7000:         return $reply_value->[0];
                   7001:     } else {
                   7002:         return $reply_value;
1.927     albertel 7003:     }
                   7004: }
                   7005: 
1.691     raeburn  7006: sub check_group_parms {
                   7007:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7008:     my @groupitems = ();
                   7009:     my $resultitem;
1.927     albertel 7010:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7011:     foreach my $group (@{$groups}) {
                   7012:         foreach my $level (@levels) {
1.927     albertel 7013:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7014:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7015:         }
                   7016:     }
                   7017:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7018:                             $env{'course.'.$courseid.'.domain'},
                   7019:                                      'course',@groupitems);
                   7020:     return $coursereply;
                   7021: }
                   7022: 
                   7023: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7024:     my ($courseid,@groups) = @_;
                   7025:     @groups = sort(@groups);
1.691     raeburn  7026:     return @groups;
                   7027: }
                   7028: 
1.395     albertel 7029: sub packages_tab_default {
                   7030:     my ($uri,$varname)=@_;
                   7031:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7032: 
                   7033:     my (@extension,@specifics,$do_default);
                   7034:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7035: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7036: 	if ($pack_type eq 'default') {
                   7037: 	    $do_default=1;
                   7038: 	} elsif ($pack_type eq 'extension') {
                   7039: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7040: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7041: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7042: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7043: 	}
                   7044:     }
                   7045:     # first look for a package that matches the requested part id
                   7046:     foreach my $package (@specifics) {
                   7047: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7048: 	next if ($pack_part ne $part);
                   7049: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7050: 	    return $packagetab{"$pack_type&$name&default"};
                   7051: 	}
                   7052:     }
                   7053:     # look for any possible matching non extension_ package
                   7054:     foreach my $package (@specifics) {
                   7055: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7056: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7057: 	    return $packagetab{"$pack_type&$name&default"};
                   7058: 	}
1.585     albertel 7059: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7060: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7061: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7062: 	}
                   7063:     }
1.738     albertel 7064:     # look for any posible extension_ match
                   7065:     foreach my $package (@extension) {
                   7066: 	my ($package,$pack_type)=@{$package};
                   7067: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7068: 	    return $packagetab{"$pack_type&$name&default"};
                   7069: 	}
                   7070: 	if (defined($packagetab{$package."&$name&default"})) {
                   7071: 	    return $packagetab{$package."&$name&default"};
                   7072: 	}
                   7073:     }
                   7074:     # look for a global default setting
                   7075:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7076: 	return $packagetab{"default&$name&default"};
                   7077:     }
1.395     albertel 7078:     return undef;
                   7079: }
                   7080: 
1.334     albertel 7081: sub add_prefix_and_part {
                   7082:     my ($prefix,$part)=@_;
                   7083:     my $keyroot;
                   7084:     if (defined($prefix) && $prefix !~ /^__/) {
                   7085: 	# prefix that has a part already
                   7086: 	$keyroot=$prefix;
                   7087:     } elsif (defined($prefix)) {
                   7088: 	# prefix that is missing a part
                   7089: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7090:     } else {
                   7091: 	# no prefix at all
                   7092: 	if (defined($part)) { $keyroot='_'.$part; }
                   7093:     }
                   7094:     return $keyroot;
                   7095: }
                   7096: 
1.71      www      7097: # ---------------------------------------------------------------- Get metadata
                   7098: 
1.599     albertel 7099: my %metaentry;
1.71      www      7100: sub metadata {
1.176     www      7101:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7102:     $uri=&declutter($uri);
1.288     albertel 7103:     # if it is a non metadata possible uri return quickly
1.529     albertel 7104:     if (($uri eq '') || 
                   7105: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7106: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7107:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7108: 	return undef;
                   7109:     }
                   7110:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7111: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7112: 	return undef;
1.288     albertel 7113:     }
1.73      www      7114:     my $filename=$uri;
                   7115:     $uri=~s/\.meta$//;
1.172     www      7116: #
                   7117: # Is the metadata already cached?
1.177     www      7118: # Look at timestamp of caching
1.172     www      7119: # Everything is cached by the main uri, libraries are never directly cached
                   7120: #
1.428     albertel 7121:     if (!defined($liburi)) {
1.599     albertel 7122: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7123: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7124:     }
                   7125:     {
1.172     www      7126: #
                   7127: # Is this a recursive call for a library?
                   7128: #
1.599     albertel 7129: #	if (! exists($metacache{$uri})) {
                   7130: #	    $metacache{$uri}={};
                   7131: #	}
1.924     albertel 7132: 	my $cachetime = 60*60;
1.171     www      7133:         if ($liburi) {
                   7134: 	    $liburi=&declutter($liburi);
                   7135:             $filename=$liburi;
1.401     bowersj2 7136:         } else {
1.599     albertel 7137: 	    &devalidate_cache_new('meta',$uri);
                   7138: 	    undef(%metaentry);
1.401     bowersj2 7139: 	}
1.140     www      7140:         my %metathesekeys=();
1.73      www      7141:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7142: 	my $metastring;
1.924     albertel 7143: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7144: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7145: 	    $metastring = 
1.929     albertel 7146: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7147: 					  ('grade_target' => 'meta'));
                   7148: 	    $cachetime = 1; # only want this cached in the child not long term
                   7149: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7150: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7151: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7152: 	    $metastring=&getfile($file);
1.489     albertel 7153: 	}
1.208     albertel 7154:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7155:         my $token;
1.140     www      7156:         undef %metathesekeys;
1.71      www      7157:         while ($token=$parser->get_token) {
1.339     albertel 7158: 	    if ($token->[0] eq 'S') {
                   7159: 		if (defined($token->[2]->{'package'})) {
1.172     www      7160: #
                   7161: # This is a package - get package info
                   7162: #
1.339     albertel 7163: 		    my $package=$token->[2]->{'package'};
                   7164: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7165: 		    if (defined($token->[2]->{'id'})) { 
                   7166: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7167: 		    }
1.599     albertel 7168: 		    if ($metaentry{':packages'}) {
                   7169: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7170: 		    } else {
1.599     albertel 7171: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7172: 		    }
1.736     albertel 7173: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7174: 			my $part=$keyroot;
                   7175: 			$part=~s/^\_//;
1.736     albertel 7176: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7177: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7178: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7179: 			    # ignore package.tab specified default values
                   7180:                             # here &package_tab_default() will fetch those
                   7181: 			    if ($subp eq 'default') { next; }
1.736     albertel 7182: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7183: 			    my $unikey;
                   7184: 			    if ($pack =~ /_0$/) {
                   7185: 				$unikey='parameter_0_'.$name;
                   7186: 				$part=0;
                   7187: 			    } else {
                   7188: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7189: 			    }
1.339     albertel 7190: 			    if ($subp eq 'display') {
                   7191: 				$value.=' [Part: '.$part.']';
                   7192: 			    }
1.599     albertel 7193: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7194: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7195: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7196: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7197: 			    }
1.599     albertel 7198: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7199: 				$metaentry{':'.$unikey}=
                   7200: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7201: 			    }
1.339     albertel 7202: 			}
                   7203: 		    }
                   7204: 		} else {
1.172     www      7205: #
                   7206: # This is not a package - some other kind of start tag
1.339     albertel 7207: #
                   7208: 		    my $entry=$token->[1];
                   7209: 		    my $unikey;
                   7210: 		    if ($entry eq 'import') {
                   7211: 			$unikey='';
                   7212: 		    } else {
                   7213: 			$unikey=$entry;
                   7214: 		    }
                   7215: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7216: 
                   7217: 		    if (defined($token->[2]->{'id'})) { 
                   7218: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7219: 		    }
1.175     www      7220: 
1.339     albertel 7221: 		    if ($entry eq 'import') {
1.175     www      7222: #
                   7223: # Importing a library here
1.339     albertel 7224: #
                   7225: 			if ($depthcount<20) {
                   7226: 			    my $location=$parser->get_text('/import');
                   7227: 			    my $dir=$filename;
                   7228: 			    $dir=~s|[^/]*$||;
                   7229: 			    $location=&filelocation($dir,$location);
1.736     albertel 7230: 			    my $metadata = 
                   7231: 				&metadata($uri,'keys', $location,$unikey,
                   7232: 					  $depthcount+1);
                   7233: 			    foreach my $meta (split(',',$metadata)) {
                   7234: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7235: 				$metathesekeys{$meta}=1;
1.339     albertel 7236: 			    }
                   7237: 			}
                   7238: 		    } else { 
                   7239: 			
                   7240: 			if (defined($token->[2]->{'name'})) { 
                   7241: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7242: 			}
                   7243: 			$metathesekeys{$unikey}=1;
1.736     albertel 7244: 			foreach my $param (@{$token->[3]}) {
                   7245: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7246: 				$token->[2]->{$param};
1.339     albertel 7247: 			}
                   7248: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7249: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7250: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7251: 		 # only ws inside the tag, and not in default, so use default
                   7252: 		 # as value
1.599     albertel 7253: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7254: 			} elsif ( $internaltext =~ /\S/ ) {
                   7255: 		  # something interesting inside the tag
                   7256: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7257: 			} else {
1.908     albertel 7258: 		  # no interesting values, don't set a default
1.339     albertel 7259: 			}
1.172     www      7260: # end of not-a-package not-a-library import
1.339     albertel 7261: 		    }
1.172     www      7262: # end of not-a-package start tag
1.339     albertel 7263: 		}
1.172     www      7264: # the next is the end of "start tag"
1.339     albertel 7265: 	    }
                   7266: 	}
1.483     albertel 7267: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7268: 	$extension = lc($extension);
                   7269: 	if ($extension eq 'htm') { $extension='html'; }
                   7270: 
1.737     albertel 7271: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7272: 	    #no specific packages #how's our extension
                   7273: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7274: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7275: 					 \%metathesekeys);
                   7276: 	}
1.883     albertel 7277: 
                   7278: 	if (!exists($metaentry{':packages'})
                   7279: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7280: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7281: 		#no specific packages well let's get default then
                   7282: 		if ($key!~/^default&/) { next; }
1.488     albertel 7283: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7284: 					     \%metathesekeys);
                   7285: 	    }
                   7286: 	}
1.338     www      7287: # are there custom rights to evaluate
1.599     albertel 7288: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7289: 
1.338     www      7290:     #
                   7291:     # Importing a rights file here
1.339     albertel 7292:     #
                   7293: 	    unless ($depthcount) {
1.599     albertel 7294: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7295: 		my $dir=$filename;
                   7296: 		$dir=~s|[^/]*$||;
                   7297: 		$location=&filelocation($dir,$location);
1.736     albertel 7298: 		my $rights_metadata =
                   7299: 		    &metadata($uri,'keys',$location,'_rights',
                   7300: 			      $depthcount+1);
                   7301: 		foreach my $rights (split(',',$rights_metadata)) {
                   7302: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7303: 		    $metathesekeys{$rights}=1;
1.339     albertel 7304: 		}
                   7305: 	    }
                   7306: 	}
1.737     albertel 7307: 	# uniqifiy package listing
                   7308: 	my %seen;
                   7309: 	my @uniq_packages =
                   7310: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7311: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7312: 
                   7313: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7314: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7315: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7316: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7317: # this is the end of "was not already recently cached
1.71      www      7318:     }
1.599     albertel 7319:     return $metaentry{':'.$what};
1.261     albertel 7320: }
                   7321: 
1.488     albertel 7322: sub metadata_create_package_def {
1.483     albertel 7323:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7324:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7325:     if ($subp eq 'default') { next; }
                   7326:     
1.599     albertel 7327:     if (defined($metaentry{':packages'})) {
                   7328: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7329:     } else {
1.599     albertel 7330: 	$metaentry{':packages'}=$package;
1.483     albertel 7331:     }
                   7332:     my $value=$packagetab{$key};
                   7333:     my $unikey;
                   7334:     $unikey='parameter_0_'.$name;
1.599     albertel 7335:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7336:     $$metathesekeys{$unikey}=1;
1.599     albertel 7337:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7338: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7339:     }
1.599     albertel 7340:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7341: 	$metaentry{':'.$unikey}=
                   7342: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7343:     }
                   7344: }
                   7345: 
1.261     albertel 7346: sub metadata_generate_part0 {
                   7347:     my ($metadata,$metacache,$uri) = @_;
                   7348:     my %allnames;
1.737     albertel 7349:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7350: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7351: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7352: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7353: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7354: 	    $allnames{$name}=$part;
                   7355: 	  }
                   7356: 	}
                   7357:     }
                   7358:     foreach my $name (keys(%allnames)) {
                   7359:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7360:       my $key=":parameter_0_$name";
1.261     albertel 7361:       $$metacache{"$key.part"}='0';
                   7362:       $$metacache{"$key.name"}=$name;
1.428     albertel 7363:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7364: 					   $allnames{$name}.'_'.$name.
                   7365: 					   '.type'};
1.428     albertel 7366:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7367: 			     '.display'};
1.644     www      7368:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7369:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7370:       $$metacache{"$key.display"}=$olddis;
                   7371:     }
1.71      www      7372: }
                   7373: 
1.764     albertel 7374: # ------------------------------------------------------ Devalidate title cache
                   7375: 
                   7376: sub devalidate_title_cache {
                   7377:     my ($url)=@_;
                   7378:     if (!$env{'request.course.id'}) { return; }
                   7379:     my $symb=&symbread($url);
                   7380:     if (!$symb) { return; }
                   7381:     my $key=$env{'request.course.id'}."\0".$symb;
                   7382:     &devalidate_cache_new('title',$key);
                   7383: }
                   7384: 
1.301     www      7385: # ------------------------------------------------- Get the title of a resource
                   7386: 
                   7387: sub gettitle {
                   7388:     my $urlsymb=shift;
                   7389:     my $symb=&symbread($urlsymb);
1.534     albertel 7390:     if ($symb) {
1.620     albertel 7391: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7392: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7393: 	if (defined($cached)) { 
                   7394: 	    return $result;
                   7395: 	}
1.534     albertel 7396: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7397: 	my $title='';
1.907     albertel 7398: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7399: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7400: 	} else {
                   7401: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7402: 		    &GDBM_READER(),0640)) {
                   7403: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7404: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7405: 		untie(%bighash);
                   7406: 	    }
1.534     albertel 7407: 	}
                   7408: 	$title=~s/\&colon\;/\:/gs;
                   7409: 	if ($title) {
1.599     albertel 7410: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7411: 	}
                   7412: 	$urlsymb=$url;
                   7413:     }
                   7414:     my $title=&metadata($urlsymb,'title');
                   7415:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7416:     return $title;
1.301     www      7417: }
1.613     albertel 7418: 
1.614     albertel 7419: sub get_slot {
                   7420:     my ($which,$cnum,$cdom)=@_;
                   7421:     if (!$cnum || !$cdom) {
1.790     albertel 7422: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7423: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7424: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7425:     }
1.703     albertel 7426:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7427:     my %slotinfo;
                   7428:     if (exists($remembered{$key})) {
                   7429: 	$slotinfo{$which} = $remembered{$key};
                   7430:     } else {
                   7431: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7432: 	&Apache::lonhomework::showhash(%slotinfo);
                   7433: 	my ($tmp)=keys(%slotinfo);
                   7434: 	if ($tmp=~/^error:/) { return (); }
                   7435: 	$remembered{$key} = $slotinfo{$which};
                   7436:     }
1.616     albertel 7437:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7438: 	return %{$slotinfo{$which}};
                   7439:     }
                   7440:     return $slotinfo{$which};
1.614     albertel 7441: }
1.31      www      7442: # ------------------------------------------------- Update symbolic store links
                   7443: 
                   7444: sub symblist {
                   7445:     my ($mapname,%newhash)=@_;
1.438     www      7446:     $mapname=&deversion(&declutter($mapname));
1.31      www      7447:     my %hash;
1.620     albertel 7448:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7449:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7450:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7451: 	    foreach my $url (keys %newhash) {
                   7452: 		next if ($url eq 'last_known'
                   7453: 			 && $env{'form.no_update_last_known'});
                   7454: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7455: 						    $newhash{$url}->[1],
                   7456: 						    $newhash{$url}->[0]);
1.191     harris41 7457:             }
1.31      www      7458:             if (untie(%hash)) {
                   7459: 		return 'ok';
                   7460:             }
                   7461:         }
                   7462:     }
                   7463:     return 'error';
1.212     www      7464: }
                   7465: 
                   7466: # --------------------------------------------------------------- Verify a symb
                   7467: 
                   7468: sub symbverify {
1.510     www      7469:     my ($symb,$thisurl)=@_;
                   7470:     my $thisfn=$thisurl;
1.439     www      7471:     $thisfn=&declutter($thisfn);
1.215     www      7472: # direct jump to resource in page or to a sequence - will construct own symbs
                   7473:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7474: # check URL part
1.409     www      7475:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7476: 
1.431     www      7477:     unless ($url eq $thisfn) { return 0; }
1.213     www      7478: 
1.216     www      7479:     $symb=&symbclean($symb);
1.510     www      7480:     $thisurl=&deversion($thisurl);
1.439     www      7481:     $thisfn=&deversion($thisfn);
1.213     www      7482: 
                   7483:     my %bighash;
                   7484:     my $okay=0;
1.431     www      7485: 
1.620     albertel 7486:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7487:                             &GDBM_READER(),0640)) {
1.510     www      7488:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7489:         unless ($ids) { 
1.510     www      7490:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7491:         }
                   7492:         if ($ids) {
                   7493: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7494: 	    foreach my $id (split(/\,/,$ids)) {
                   7495: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7496:                if (
                   7497:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7498:    eq $symb) { 
1.620     albertel 7499: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7500: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7501: 		       $okay=1; 
                   7502: 		   }
                   7503: 	       }
1.216     www      7504: 	   }
                   7505:         }
1.213     www      7506: 	untie(%bighash);
                   7507:     }
                   7508:     return $okay;
1.31      www      7509: }
                   7510: 
1.210     www      7511: # --------------------------------------------------------------- Clean-up symb
                   7512: 
                   7513: sub symbclean {
                   7514:     my $symb=shift;
1.568     albertel 7515:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7516: # remove version from map
                   7517:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7518: 
1.210     www      7519: # remove version from URL
                   7520:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7521: 
1.507     www      7522: # remove wrapper
                   7523: 
1.510     www      7524:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7525:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7526:     return $symb;
1.409     www      7527: }
                   7528: 
                   7529: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7530: 
                   7531: sub encode_symb {
                   7532:     my ($map,$resid,$url)=@_;
                   7533:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7534: }
1.409     www      7535: 
                   7536: sub decode_symb {
1.568     albertel 7537:     my $symb=shift;
                   7538:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7539:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7540:     return (&fixversion($map),$resid,&fixversion($url));
                   7541: }
                   7542: 
                   7543: sub fixversion {
                   7544:     my $fn=shift;
1.609     banghart 7545:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7546:     my %bighash;
                   7547:     my $uri=&clutter($fn);
1.620     albertel 7548:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7549: # is this cached?
1.599     albertel 7550:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7551:     if (defined($cached)) { return $result; }
                   7552: # unfortunately not cached, or expired
1.620     albertel 7553:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7554: 	    &GDBM_READER(),0640)) {
                   7555:  	if ($bighash{'version_'.$uri}) {
                   7556:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7557:  	    unless (($version eq 'mostrecent') || 
                   7558: 		    ($version==&getversion($uri))) {
1.440     www      7559:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7560:  	    }
                   7561:  	}
                   7562:  	untie %bighash;
1.413     www      7563:     }
1.599     albertel 7564:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7565: }
                   7566: 
                   7567: sub deversion {
                   7568:     my $url=shift;
                   7569:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7570:     return $url;
1.210     www      7571: }
                   7572: 
1.31      www      7573: # ------------------------------------------------------ Return symb list entry
                   7574: 
                   7575: sub symbread {
1.249     www      7576:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7577:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7578:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7579: # no filename provided? try from environment
1.44      www      7580:     unless ($thisfn) {
1.620     albertel 7581:         if ($env{'request.symb'}) {
                   7582: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7583: 	}
1.620     albertel 7584: 	$thisfn=$env{'request.filename'};
1.44      www      7585:     }
1.569     albertel 7586:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7587: # is that filename actually a symb? Verify, clean, and return
                   7588:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7589: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7590: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7591: 	}
1.242     www      7592:     }
1.44      www      7593:     $thisfn=declutter($thisfn);
1.31      www      7594:     my %hash;
1.37      www      7595:     my %bighash;
                   7596:     my $syval='';
1.620     albertel 7597:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7598:         my $targetfn = $thisfn;
1.609     banghart 7599:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7600:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7601:         }
1.687     albertel 7602: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7603: 	    $targetfn=$1;
                   7604: 	}
1.620     albertel 7605:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7606:                       &GDBM_READER(),0640)) {
1.481     raeburn  7607: 	    $syval=$hash{$targetfn};
1.37      www      7608:             untie(%hash);
                   7609:         }
                   7610: # ---------------------------------------------------------- There was an entry
                   7611:         if ($syval) {
1.601     albertel 7612: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7613: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7614: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7615: 		    #return $env{$cache_str}='';
1.601     albertel 7616: 		#}    
                   7617: 		#$syval.=$1;
                   7618: 	    #}
1.37      www      7619:         } else {
                   7620: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7621:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7622:                             &GDBM_READER(),0640)) {
1.37      www      7623: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7624:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7625:               unless ($ids) { 
                   7626:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7627:               }
                   7628:               unless ($ids) {
                   7629: # alias?
                   7630: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7631:               }
1.37      www      7632:               if ($ids) {
                   7633: # ------------------------------------------------------------------- Has ID(s)
                   7634:                  my @possibilities=split(/\,/,$ids);
1.39      www      7635:                  if ($#possibilities==0) {
                   7636: # ----------------------------------------------- There is only one possibility
1.37      www      7637: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7638: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7639: 						    $resid,$thisfn);
1.249     www      7640:                  } elsif (!$donotrecurse) {
1.39      www      7641: # ------------------------------------------ There is more than one possibility
                   7642:                      my $realpossible=0;
1.800     albertel 7643:                      foreach my $id (@possibilities) {
                   7644: 			 my $file=$bighash{'src_'.$id};
1.39      www      7645:                          if (&allowed('bre',$file)) {
1.800     albertel 7646:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7647:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7648: 				$realpossible++;
1.626     albertel 7649:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7650: 						    $resid,$thisfn);
1.39      www      7651:                             }
                   7652: 			 }
1.191     harris41 7653:                      }
1.39      www      7654: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7655:                  } else {
                   7656:                      $syval='';
1.37      www      7657:                  }
                   7658: 	      }
                   7659:               untie(%bighash)
1.481     raeburn  7660:            }
1.31      www      7661:         }
1.62      www      7662:         if ($syval) {
1.620     albertel 7663: 	    return $env{$cache_str}=$syval;
1.62      www      7664:         }
1.31      www      7665:     }
1.949     raeburn  7666:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7667:     return $env{$cache_str}='';
1.31      www      7668: }
                   7669: 
                   7670: # ---------------------------------------------------------- Return random seed
                   7671: 
1.32      www      7672: sub numval {
                   7673:     my $txt=shift;
                   7674:     $txt=~tr/A-J/0-9/;
                   7675:     $txt=~tr/a-j/0-9/;
                   7676:     $txt=~tr/K-T/0-9/;
                   7677:     $txt=~tr/k-t/0-9/;
                   7678:     $txt=~tr/U-Z/0-5/;
                   7679:     $txt=~tr/u-z/0-5/;
                   7680:     $txt=~s/\D//g;
1.564     albertel 7681:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7682:     return int($txt);
1.368     albertel 7683: }
                   7684: 
1.484     albertel 7685: sub numval2 {
                   7686:     my $txt=shift;
                   7687:     $txt=~tr/A-J/0-9/;
                   7688:     $txt=~tr/a-j/0-9/;
                   7689:     $txt=~tr/K-T/0-9/;
                   7690:     $txt=~tr/k-t/0-9/;
                   7691:     $txt=~tr/U-Z/0-5/;
                   7692:     $txt=~tr/u-z/0-5/;
                   7693:     $txt=~s/\D//g;
                   7694:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7695:     my $total;
                   7696:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7697:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7698:     return int($total);
                   7699: }
                   7700: 
1.575     albertel 7701: sub numval3 {
                   7702:     use integer;
                   7703:     my $txt=shift;
                   7704:     $txt=~tr/A-J/0-9/;
                   7705:     $txt=~tr/a-j/0-9/;
                   7706:     $txt=~tr/K-T/0-9/;
                   7707:     $txt=~tr/k-t/0-9/;
                   7708:     $txt=~tr/U-Z/0-5/;
                   7709:     $txt=~tr/u-z/0-5/;
                   7710:     $txt=~s/\D//g;
                   7711:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7712:     my $total;
                   7713:     foreach my $val (@txts) { $total+=$val; }
                   7714:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7715:     return $total;
                   7716: }
                   7717: 
1.675     albertel 7718: sub digest {
                   7719:     my ($data)=@_;
                   7720:     my $digest=&Digest::MD5::md5($data);
                   7721:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7722:     my ($e,$f);
                   7723:     {
                   7724:         use integer;
                   7725:         $e=($a+$b);
                   7726:         $f=($c+$d);
                   7727:         if ($_64bit) {
                   7728:             $e=(($e<<32)>>32);
                   7729:             $f=(($f<<32)>>32);
                   7730:         }
                   7731:     }
                   7732:     if (wantarray) {
                   7733: 	return ($e,$f);
                   7734:     } else {
                   7735: 	my $g;
                   7736: 	{
                   7737: 	    use integer;
                   7738: 	    $g=($e+$f);
                   7739: 	    if ($_64bit) {
                   7740: 		$g=(($g<<32)>>32);
                   7741: 	    }
                   7742: 	}
                   7743: 	return $g;
                   7744:     }
                   7745: }
                   7746: 
1.368     albertel 7747: sub latest_rnd_algorithm_id {
1.675     albertel 7748:     return '64bit5';
1.366     albertel 7749: }
1.32      www      7750: 
1.503     albertel 7751: sub get_rand_alg {
                   7752:     my ($courseid)=@_;
1.790     albertel 7753:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7754:     if ($courseid) {
1.620     albertel 7755: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7756:     }
                   7757:     return &latest_rnd_algorithm_id();
                   7758: }
                   7759: 
1.562     albertel 7760: sub validCODE {
                   7761:     my ($CODE)=@_;
                   7762:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7763:     return 0;
                   7764: }
                   7765: 
1.491     albertel 7766: sub getCODE {
1.620     albertel 7767:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7768:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7769: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7770: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7771: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7772:     }
                   7773:     return undef;
                   7774: }
                   7775: 
1.31      www      7776: sub rndseed {
1.155     albertel 7777:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7778:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7779:     if (!defined($symb)) {
1.366     albertel 7780: 	unless ($symb=$wsymb) { return time; }
                   7781:     }
                   7782:     if (!$courseid) { $courseid=$wcourseid; }
                   7783:     if (!$domain) { $domain=$wdomain; }
                   7784:     if (!$username) { $username=$wusername }
1.503     albertel 7785:     my $which=&get_rand_alg();
1.803     albertel 7786: 
1.491     albertel 7787:     if (defined(&getCODE())) {
1.675     albertel 7788: 	if ($which eq '64bit5') {
                   7789: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7790: 	} elsif ($which eq '64bit4') {
1.575     albertel 7791: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7792: 	} else {
                   7793: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7794: 	}
1.675     albertel 7795:     } elsif ($which eq '64bit5') {
                   7796: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7797:     } elsif ($which eq '64bit4') {
                   7798: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7799:     } elsif ($which eq '64bit3') {
                   7800: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7801:     } elsif ($which eq '64bit2') {
                   7802: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7803:     } elsif ($which eq '64bit') {
                   7804: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7805:     }
                   7806:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7807: }
                   7808: 
                   7809: sub rndseed_32bit {
                   7810:     my ($symb,$courseid,$domain,$username)=@_;
                   7811:     {
                   7812: 	use integer;
                   7813: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7814: 	my $symbseed=numval($symb) << 22;
                   7815: 	my $namechck=unpack("%32C*",$username) << 17;
                   7816: 	my $nameseed=numval($username) << 12;
                   7817: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7818: 	my $courseseed=unpack("%32C*",$courseid);
                   7819: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7820: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7821: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7822: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7823: 	return $num;
                   7824:     }
                   7825: }
                   7826: 
                   7827: sub rndseed_64bit {
                   7828:     my ($symb,$courseid,$domain,$username)=@_;
                   7829:     {
                   7830: 	use integer;
                   7831: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7832: 	my $symbseed=numval($symb) << 10;
                   7833: 	my $namechck=unpack("%32S*",$username);
                   7834: 	
                   7835: 	my $nameseed=numval($username) << 21;
                   7836: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7837: 	my $courseseed=unpack("%32S*",$courseid);
                   7838: 	
                   7839: 	my $num1=$symbchck+$symbseed+$namechck;
                   7840: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7841: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7842: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7843: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7844: 	return "$num1,$num2";
1.155     albertel 7845:     }
1.366     albertel 7846: }
                   7847: 
1.443     albertel 7848: sub rndseed_64bit2 {
                   7849:     my ($symb,$courseid,$domain,$username)=@_;
                   7850:     {
                   7851: 	use integer;
                   7852: 	# strings need to be an even # of cahracters long, it it is odd the
                   7853:         # last characters gets thrown away
                   7854: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7855: 	my $symbseed=numval($symb) << 10;
                   7856: 	my $namechck=unpack("%32S*",$username.' ');
                   7857: 	
                   7858: 	my $nameseed=numval($username) << 21;
1.501     albertel 7859: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7860: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7861: 	
                   7862: 	my $num1=$symbchck+$symbseed+$namechck;
                   7863: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7864: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7865: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7866: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7867: 	return "$num1,$num2";
                   7868:     }
                   7869: }
                   7870: 
                   7871: sub rndseed_64bit3 {
                   7872:     my ($symb,$courseid,$domain,$username)=@_;
                   7873:     {
                   7874: 	use integer;
                   7875: 	# strings need to be an even # of cahracters long, it it is odd the
                   7876:         # last characters gets thrown away
                   7877: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7878: 	my $symbseed=numval2($symb) << 10;
                   7879: 	my $namechck=unpack("%32S*",$username.' ');
                   7880: 	
                   7881: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7882: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7883: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7884: 	
                   7885: 	my $num1=$symbchck+$symbseed+$namechck;
                   7886: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7887: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7888: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7889: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7890: 	
1.503     albertel 7891: 	return "$num1:$num2";
1.443     albertel 7892:     }
                   7893: }
                   7894: 
1.575     albertel 7895: sub rndseed_64bit4 {
                   7896:     my ($symb,$courseid,$domain,$username)=@_;
                   7897:     {
                   7898: 	use integer;
                   7899: 	# strings need to be an even # of cahracters long, it it is odd the
                   7900:         # last characters gets thrown away
                   7901: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7902: 	my $symbseed=numval3($symb) << 10;
                   7903: 	my $namechck=unpack("%32S*",$username.' ');
                   7904: 	
                   7905: 	my $nameseed=numval3($username) << 21;
                   7906: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7907: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7908: 	
                   7909: 	my $num1=$symbchck+$symbseed+$namechck;
                   7910: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7911: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7912: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7913: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7914: 	
                   7915: 	return "$num1:$num2";
                   7916:     }
                   7917: }
                   7918: 
1.675     albertel 7919: sub rndseed_64bit5 {
                   7920:     my ($symb,$courseid,$domain,$username)=@_;
                   7921:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7922:     return "$num1:$num2";
                   7923: }
                   7924: 
1.366     albertel 7925: sub rndseed_CODE_64bit {
                   7926:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7927:     {
1.366     albertel 7928: 	use integer;
1.443     albertel 7929: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7930: 	my $symbseed=numval2($symb);
1.491     albertel 7931: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7932: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7933: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7934: 	my $num1=$symbseed+$CODEchck;
                   7935: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7936: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7937: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7938: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7939: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7940: 	return "$num1:$num2";
1.366     albertel 7941:     }
                   7942: }
                   7943: 
1.575     albertel 7944: sub rndseed_CODE_64bit4 {
                   7945:     my ($symb,$courseid,$domain,$username)=@_;
                   7946:     {
                   7947: 	use integer;
                   7948: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7949: 	my $symbseed=numval3($symb);
                   7950: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7951: 	my $CODEseed=numval3(&getCODE());
                   7952: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7953: 	my $num1=$symbseed+$CODEchck;
                   7954: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7955: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7956: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7957: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7958: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7959: 	return "$num1:$num2";
                   7960:     }
                   7961: }
                   7962: 
1.675     albertel 7963: sub rndseed_CODE_64bit5 {
                   7964:     my ($symb,$courseid,$domain,$username)=@_;
                   7965:     my $code = &getCODE();
                   7966:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7967:     return "$num1:$num2";
                   7968: }
                   7969: 
1.366     albertel 7970: sub setup_random_from_rndseed {
                   7971:     my ($rndseed)=@_;
1.503     albertel 7972:     if ($rndseed =~/([,:])/) {
                   7973: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7974: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7975:     } else {
                   7976: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7977:     }
1.36      albertel 7978: }
                   7979: 
1.474     albertel 7980: sub latest_receipt_algorithm_id {
1.835     albertel 7981:     return 'receipt3';
1.474     albertel 7982: }
                   7983: 
1.480     www      7984: sub recunique {
                   7985:     my $fucourseid=shift;
                   7986:     my $unique;
1.835     albertel 7987:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7988: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7989: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7990:     } else {
                   7991: 	$unique=$perlvar{'lonReceipt'};
                   7992:     }
                   7993:     return unpack("%32C*",$unique);
                   7994: }
                   7995: 
                   7996: sub recprefix {
                   7997:     my $fucourseid=shift;
                   7998:     my $prefix;
1.835     albertel 7999:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8000: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8001: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8002:     } else {
                   8003: 	$prefix=$perlvar{'lonHostID'};
                   8004:     }
                   8005:     return unpack("%32C*",$prefix);
                   8006: }
                   8007: 
1.76      www      8008: sub ireceipt {
1.474     albertel 8009:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8010: 
                   8011:     my $return =&recprefix($fucourseid).'-';
                   8012: 
                   8013:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8014: 	$env{'request.state'} eq 'construct') {
                   8015: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8016: 	return $return;
                   8017:     }
                   8018: 
1.76      www      8019:     my $cuname=unpack("%32C*",$funame);
                   8020:     my $cudom=unpack("%32C*",$fudom);
                   8021:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8022:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8023:     my $cunique=&recunique($fucourseid);
1.474     albertel 8024:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8025:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8026: 
1.790     albertel 8027: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8028: 			       
                   8029: 	$return.= ($cunique%$cuname+
                   8030: 		   $cunique%$cudom+
                   8031: 		   $cusymb%$cuname+
                   8032: 		   $cusymb%$cudom+
                   8033: 		   $cucourseid%$cuname+
                   8034: 		   $cucourseid%$cudom+
                   8035: 		   $cpart%$cuname+
                   8036: 		   $cpart%$cudom);
                   8037:     } else {
                   8038: 	$return.= ($cunique%$cuname+
                   8039: 		   $cunique%$cudom+
                   8040: 		   $cusymb%$cuname+
                   8041: 		   $cusymb%$cudom+
                   8042: 		   $cucourseid%$cuname+
                   8043: 		   $cucourseid%$cudom);
                   8044:     }
                   8045:     return $return;
1.76      www      8046: }
                   8047: 
                   8048: sub receipt {
1.474     albertel 8049:     my ($part)=@_;
1.790     albertel 8050:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8051:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8052: }
1.260     ng       8053: 
1.790     albertel 8054: sub whichuser {
                   8055:     my ($passedsymb)=@_;
                   8056:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8057:     if (defined($env{'form.grade_symb'})) {
                   8058: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8059: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8060: 	if (!$allowed &&
                   8061: 	    exists($env{'request.course.sec'}) &&
                   8062: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8063: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8064: 			      '/'.$env{'request.course.sec'});
                   8065: 	}
                   8066: 	if ($allowed) {
                   8067: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8068: 	    $courseid=$tmp_courseid;
                   8069: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8070: 	    ($name)=&get_env_multiple('form.grade_username');
                   8071: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8072: 	}
                   8073:     }
                   8074:     if (!$passedsymb) {
                   8075: 	$symb=&symbread();
                   8076:     } else {
                   8077: 	$symb=$passedsymb;
                   8078:     }
                   8079:     $courseid=$env{'request.course.id'};
                   8080:     $domain=$env{'user.domain'};
                   8081:     $name=$env{'user.name'};
                   8082:     if ($name eq 'public' && $domain eq 'public') {
                   8083: 	if (!defined($env{'form.username'})) {
                   8084: 	    $env{'form.username'}.=time.rand(10000000);
                   8085: 	}
                   8086: 	$name.=$env{'form.username'};
                   8087:     }
                   8088:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8089: 
                   8090: }
                   8091: 
1.36      albertel 8092: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8093: # returns either the contents of the file or 
                   8094: # -1 if the file doesn't exist
1.481     raeburn  8095: #
                   8096: # if the target is a file that was uploaded via DOCS, 
                   8097: # a check will be made to see if a current copy exists on the local server,
                   8098: # if it does this will be served, otherwise a copy will be retrieved from
                   8099: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8100: # the local server.   
1.472     albertel 8101: 
1.36      albertel 8102: sub getfile {
1.538     albertel 8103:     my ($file) = @_;
1.609     banghart 8104:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8105:     &repcopy($file);
                   8106:     return &readfile($file);
                   8107: }
                   8108: 
                   8109: sub repcopy_userfile {
                   8110:     my ($file)=@_;
1.609     banghart 8111:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8112:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8113:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8114: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8115:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8116:     if (-e "$file") {
1.828     www      8117: # we already have a local copy, check it out
1.538     albertel 8118: 	my @fileinfo = stat($file);
1.828     www      8119: 	my $rtncode;
                   8120: 	my $info;
1.538     albertel 8121: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8122: 	if ($lwpresp ne 'ok') {
1.828     www      8123: # there is no such file anymore, even though we had a local copy
1.482     albertel 8124: 	    if ($rtncode eq '404') {
1.538     albertel 8125: 		unlink($file);
1.482     albertel 8126: 	    }
                   8127: 	    return -1;
                   8128: 	}
                   8129: 	if ($info < $fileinfo[9]) {
1.828     www      8130: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8131: 	    return 'ok';
1.828     www      8132: 	} else {
                   8133: # the file is outdated, get rid of it
                   8134: 	    unlink($file);
1.482     albertel 8135: 	}
1.828     www      8136:     }
                   8137: # one way or the other, at this point, we don't have the file
                   8138: # construct the correct path for the file
                   8139:     my @parts = ($cdom,$cnum); 
                   8140:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8141: 	push @parts, split(/\//,$1);
                   8142:     }
                   8143:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8144:     foreach my $part (@parts) {
                   8145: 	$path .= '/'.$part;
                   8146: 	if (!-e $path) {
                   8147: 	    mkdir($path,0770);
1.482     albertel 8148: 	}
                   8149:     }
1.828     www      8150: # now the path exists for sure
                   8151: # get a user agent
                   8152:     my $ua=new LWP::UserAgent;
                   8153:     my $transferfile=$file.'.in.transfer';
                   8154: # FIXME: this should flock
                   8155:     if (-e $transferfile) { return 'ok'; }
                   8156:     my $request;
                   8157:     $uri=~s/^\///;
1.838     albertel 8158:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8159:     my $response=$ua->request($request,$transferfile);
                   8160: # did it work?
                   8161:     if ($response->is_error()) {
                   8162: 	unlink($transferfile);
                   8163: 	&logthis("Userfile repcopy failed for $uri");
                   8164: 	return -1;
                   8165:     }
                   8166: # worked, rename the transfer file
                   8167:     rename($transferfile,$file);
1.607     raeburn  8168:     return 'ok';
1.481     raeburn  8169: }
                   8170: 
1.517     albertel 8171: sub tokenwrapper {
                   8172:     my $uri=shift;
1.552     albertel 8173:     $uri=~s|^http\://([^/]+)||;
                   8174:     $uri=~s|^/||;
1.620     albertel 8175:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8176:     my $token=$1;
1.552     albertel 8177:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8178:     if ($udom && $uname && $file) {
                   8179: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8180:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8181:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8182:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8183:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8184:     } else {
                   8185:         return '/adm/notfound.html';
                   8186:     }
                   8187: }
                   8188: 
1.828     www      8189: # call with reqtype HEAD: get last modification time
                   8190: # call with reqtype GET: get the file contents
                   8191: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8192: #
1.481     raeburn  8193: sub getuploaded {
                   8194:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8195:     $uri=~s/^\///;
1.838     albertel 8196:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8197:     my $ua=new LWP::UserAgent;
                   8198:     my $request=new HTTP::Request($reqtype,$uri);
                   8199:     my $response=$ua->request($request);
                   8200:     $$rtncode = $response->code;
1.482     albertel 8201:     if (! $response->is_success()) {
                   8202: 	return 'failed';
                   8203:     }      
                   8204:     if ($reqtype eq 'HEAD') {
1.486     www      8205: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8206:     } elsif ($reqtype eq 'GET') {
                   8207: 	$$info = $response->content;
1.472     albertel 8208:     }
1.482     albertel 8209:     return 'ok';
1.36      albertel 8210: }
                   8211: 
1.481     raeburn  8212: sub readfile {
                   8213:     my $file = shift;
                   8214:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8215:     my $fh;
                   8216:     open($fh,"<$file");
                   8217:     my $a='';
1.800     albertel 8218:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8219:     return $a;
                   8220: }
                   8221: 
1.36      albertel 8222: sub filelocation {
1.590     banghart 8223:     my ($dir,$file) = @_;
                   8224:     my $location;
                   8225:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8226: 
                   8227:     if ($file =~ m-^/adm/-) {
                   8228: 	$file=~s-^/adm/wrapper/-/-;
                   8229: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8230:     }
1.882     albertel 8231: 
1.590     banghart 8232:     if ($file=~m:^/~:) { # is a contruction space reference
                   8233:         $location = $file;
                   8234:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8235:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8236: 	# is a correct contruction space reference
                   8237:         $location = $file;
1.956     raeburn  8238:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8239:         $location = $file;
1.609     banghart 8240:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8241:         my ($udom,$uname,$filename)=
1.811     albertel 8242:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8243:         my $home=&homeserver($uname,$udom);
                   8244:         my $is_me=0;
                   8245:         my @ids=&current_machine_ids();
                   8246:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8247:         if ($is_me) {
1.955     raeburn  8248:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8249:         } else {
                   8250:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8251:   	      $udom.'/'.$uname.'/'.$filename;
                   8252:         }
1.882     albertel 8253:     } elsif ($file =~ m-^/adm/-) {
                   8254: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8255:     } else {
                   8256:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8257:         $file=~s:^/res/:/:;
                   8258:         if ( !( $file =~ m:^/:) ) {
                   8259:             $location = $dir. '/'.$file;
                   8260:         } else {
                   8261:             $location = '/home/httpd/html/res'.$file;
                   8262:         }
1.59      albertel 8263:     }
1.590     banghart 8264:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8265:     while ($location=~m{/\.\./}) {
                   8266: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8267: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8268: 	} else {
                   8269: 	    $location=~ s{/\.\./}{/}g;
                   8270: 	}
                   8271:     } #remove dir/..
1.590     banghart 8272:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8273:     return $location;
1.46      www      8274: }
1.36      albertel 8275: 
1.46      www      8276: sub hreflocation {
                   8277:     my ($dir,$file)=@_;
1.460     albertel 8278:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8279: 	$file=filelocation($dir,$file);
1.700     albertel 8280:     } elsif ($file=~m-^/adm/-) {
                   8281: 	$file=~s-^/adm/wrapper/-/-;
                   8282: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8283:     }
                   8284:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8285: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8286:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8287: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8288:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8289: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8290: 	    -/uploaded/$1/$2/-x;
1.46      www      8291:     }
1.913     albertel 8292:     if ($file=~ m{^/userfiles/}) {
                   8293: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8294:     }
1.462     albertel 8295:     return $file;
1.465     albertel 8296: }
                   8297: 
                   8298: sub current_machine_domains {
1.853     albertel 8299:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8300: }
                   8301: 
                   8302: sub machine_domains {
                   8303:     my ($hostname) = @_;
1.465     albertel 8304:     my @domains;
1.838     albertel 8305:     my %hostname = &all_hostnames();
1.465     albertel 8306:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8307: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8308: 	if ($hostname eq $name) {
1.844     albertel 8309: 	    push(@domains,&host_domain($id));
1.465     albertel 8310: 	}
                   8311:     }
                   8312:     return @domains;
                   8313: }
                   8314: 
                   8315: sub current_machine_ids {
1.853     albertel 8316:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8317: }
                   8318: 
                   8319: sub machine_ids {
                   8320:     my ($hostname) = @_;
                   8321:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8322:     my @ids;
1.888     albertel 8323:     my %name_to_host = &all_names();
1.889     albertel 8324:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8325: 	return @{ $name_to_host{$hostname} };
                   8326:     }
                   8327:     return;
1.31      www      8328: }
                   8329: 
1.824     raeburn  8330: sub additional_machine_domains {
                   8331:     my @domains;
                   8332:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8333:     while( my $line = <$fh>) {
                   8334:         $line =~ s/\s//g;
                   8335:         push(@domains,$line);
                   8336:     }
                   8337:     return @domains;
                   8338: }
                   8339: 
                   8340: sub default_login_domain {
                   8341:     my $domain = $perlvar{'lonDefDomain'};
                   8342:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8343:     foreach my $posdom (&current_machine_domains(),
                   8344:                         &additional_machine_domains()) {
                   8345:         if (lc($posdom) eq lc($testdomain)) {
                   8346:             $domain=$posdom;
                   8347:             last;
                   8348:         }
                   8349:     }
                   8350:     return $domain;
                   8351: }
                   8352: 
1.31      www      8353: # ------------------------------------------------------------- Declutters URLs
                   8354: 
                   8355: sub declutter {
                   8356:     my $thisfn=shift;
1.569     albertel 8357:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8358:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8359:     $thisfn=~s/^\///;
1.697     albertel 8360:     $thisfn=~s|^adm/wrapper/||;
                   8361:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8362:     $thisfn=~s/^res\///;
1.235     www      8363:     $thisfn=~s/\?.+$//;
1.268     www      8364:     return $thisfn;
                   8365: }
                   8366: 
                   8367: # ------------------------------------------------------------- Clutter up URLs
                   8368: 
                   8369: sub clutter {
                   8370:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8371:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8372: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8373:        $thisfn='/res'.$thisfn; 
                   8374:     }
1.694     albertel 8375:     if ($thisfn !~m|/adm|) {
1.695     albertel 8376: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8377: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8378: 	} else {
                   8379: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8380: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8381: 	    if ($embstyle eq 'ssi'
                   8382: 		|| ($embstyle eq 'hdn')
                   8383: 		|| ($embstyle eq 'rat')
                   8384: 		|| ($embstyle eq 'prv')
                   8385: 		|| ($embstyle eq 'ign')) {
                   8386: 		#do nothing with these
                   8387: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8388: 		|| ($embstyle eq 'emb')
                   8389: 		|| ($embstyle eq 'wrp')) {
                   8390: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8391: 	    } elsif ($embstyle eq 'unk'
                   8392: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8393: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8394: 	    } else {
1.718     www      8395: #		&logthis("Got a blank emb style");
1.695     albertel 8396: 	    }
1.694     albertel 8397: 	}
                   8398:     }
1.31      www      8399:     return $thisfn;
1.12      www      8400: }
                   8401: 
1.787     albertel 8402: sub clutter_with_no_wrapper {
                   8403:     my $uri = &clutter(shift);
                   8404:     if ($uri =~ m-^/adm/-) {
                   8405: 	$uri =~ s-^/adm/wrapper/-/-;
                   8406: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8407:     }
                   8408:     return $uri;
                   8409: }
                   8410: 
1.557     albertel 8411: sub freeze_escape {
                   8412:     my ($value)=@_;
                   8413:     if (ref($value)) {
                   8414: 	$value=&nfreeze($value);
                   8415: 	return '__FROZEN__'.&escape($value);
                   8416:     }
                   8417:     return &escape($value);
                   8418: }
                   8419: 
1.11      www      8420: 
1.557     albertel 8421: sub thaw_unescape {
                   8422:     my ($value)=@_;
                   8423:     if ($value =~ /^__FROZEN__/) {
                   8424: 	substr($value,0,10,undef);
                   8425: 	$value=&unescape($value);
                   8426: 	return &thaw($value);
                   8427:     }
                   8428:     return &unescape($value);
                   8429: }
                   8430: 
1.436     albertel 8431: sub correct_line_ends {
                   8432:     my ($result)=@_;
                   8433:     $$result =~s/\r\n/\n/mg;
                   8434:     $$result =~s/\r/\n/mg;
1.415     albertel 8435: }
1.1       albertel 8436: # ================================================================ Main Program
                   8437: 
1.184     www      8438: sub goodbye {
1.204     albertel 8439:    &logthis("Starting Shut down");
1.443     albertel 8440: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8441:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8442: #converted
1.599     albertel 8443: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8444:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8445: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8446: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8447: #1.1 only
1.870     albertel 8448: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8449: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8450: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8451: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8452:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8453:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8454:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8455:    &flushcourselogs();
                   8456:    &logthis("Shutting down");
                   8457: }
                   8458: 
1.852     albertel 8459: sub get_dns {
1.869     albertel 8460:     my ($url,$func,$ignore_cache) = @_;
                   8461:     if (!$ignore_cache) {
                   8462: 	my ($content,$cached)=
                   8463: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8464: 	if ($cached) {
                   8465: 	    &$func($content);
                   8466: 	    return;
                   8467: 	}
                   8468:     }
                   8469: 
                   8470:     my %alldns;
1.852     albertel 8471:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8472:     foreach my $dns (<$config>) {
                   8473: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8474: 	$alldns{$1} = 1;
                   8475:     }
                   8476:     while (%alldns) {
                   8477: 	my ($dns) = keys(%alldns);
                   8478: 	delete($alldns{$dns});
1.852     albertel 8479: 	my $ua=new LWP::UserAgent;
                   8480: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8481: 	my $response=$ua->request($request);
                   8482: 	next if ($response->is_error());
                   8483: 	my @content = split("\n",$response->content);
1.869     albertel 8484: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8485: 	&$func(\@content);
1.869     albertel 8486: 	return;
1.852     albertel 8487:     }
                   8488:     close($config);
1.871     albertel 8489:     my $which = (split('/',$url))[3];
                   8490:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8491:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8492:     my @content = <$config>;
                   8493:     &$func(\@content);
                   8494:     return;
1.852     albertel 8495: }
1.327     albertel 8496: # ------------------------------------------------------------ Read domain file
                   8497: {
1.852     albertel 8498:     my $loaded;
1.846     albertel 8499:     my %domain;
                   8500: 
1.852     albertel 8501:     sub parse_domain_tab {
                   8502: 	my ($lines) = @_;
                   8503: 	foreach my $line (@$lines) {
                   8504: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8505: 
1.846     albertel 8506: 	    chomp($line);
1.852     albertel 8507: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8508: 	    my %this_domain;
                   8509: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8510: 			       'lang_def', 'city', 'longi', 'lati',
                   8511: 			       'primary') {
                   8512: 		$this_domain{$field} = shift(@elements);
                   8513: 	    }
                   8514: 	    $domain{$name} = \%this_domain;
1.852     albertel 8515: 	}
                   8516:     }
1.864     albertel 8517: 
                   8518:     sub reset_domain_info {
                   8519: 	undef($loaded);
                   8520: 	undef(%domain);
                   8521:     }
                   8522: 
1.852     albertel 8523:     sub load_domain_tab {
1.869     albertel 8524: 	my ($ignore_cache) = @_;
                   8525: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8526: 	my $fh;
                   8527: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8528: 	    my @lines = <$fh>;
                   8529: 	    &parse_domain_tab(\@lines);
1.448     albertel 8530: 	}
1.852     albertel 8531: 	close($fh);
                   8532: 	$loaded = 1;
1.327     albertel 8533:     }
1.846     albertel 8534: 
                   8535:     sub domain {
1.852     albertel 8536: 	&load_domain_tab() if (!$loaded);
                   8537: 
1.846     albertel 8538: 	my ($name,$what) = @_;
                   8539: 	return if ( !exists($domain{$name}) );
                   8540: 
                   8541: 	if (!$what) {
                   8542: 	    return $domain{$name}{'description'};
                   8543: 	}
                   8544: 	return $domain{$name}{$what};
                   8545:     }
1.327     albertel 8546: }
                   8547: 
                   8548: 
1.1       albertel 8549: # ------------------------------------------------------------- Read hosts file
                   8550: {
1.838     albertel 8551:     my %hostname;
1.844     albertel 8552:     my %hostdom;
1.845     albertel 8553:     my %libserv;
1.852     albertel 8554:     my $loaded;
1.888     albertel 8555:     my %name_to_host;
1.852     albertel 8556: 
                   8557:     sub parse_hosts_tab {
                   8558: 	my ($file) = @_;
                   8559: 	foreach my $configline (@$file) {
                   8560: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8561: 	    next if ($configline =~ /^\^/);
                   8562: 	    chomp($configline);
1.968     raeburn  8563: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8564: 	    $name=~s/\s//g;
                   8565: 	    if ($id && $domain && $role && $name) {
                   8566: 		$hostname{$id}=$name;
1.888     albertel 8567: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8568: 		$hostdom{$id}=$domain;
                   8569: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8570:                 if (defined($protocol)) {
                   8571:                     if ($protocol eq 'https') {
                   8572:                         $protocol{$id} = $protocol;
                   8573:                     } else {
                   8574:                         $protocol{$id} = 'http'; 
                   8575:                     }
1.968     raeburn  8576:                 } else {
1.969     raeburn  8577:                     $protocol{$id} = 'http';
1.968     raeburn  8578:                 }
1.852     albertel 8579: 	    }
                   8580: 	}
                   8581:     }
1.864     albertel 8582:     
                   8583:     sub reset_hosts_info {
1.897     albertel 8584: 	&purge_remembered();
1.864     albertel 8585: 	&reset_domain_info();
                   8586: 	&reset_hosts_ip_info();
1.892     albertel 8587: 	undef(%name_to_host);
1.864     albertel 8588: 	undef(%hostname);
                   8589: 	undef(%hostdom);
                   8590: 	undef(%libserv);
                   8591: 	undef($loaded);
                   8592:     }
1.1       albertel 8593: 
1.852     albertel 8594:     sub load_hosts_tab {
1.869     albertel 8595: 	my ($ignore_cache) = @_;
                   8596: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8597: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8598: 	my @config = <$config>;
                   8599: 	&parse_hosts_tab(\@config);
                   8600: 	close($config);
                   8601: 	$loaded=1;
1.1       albertel 8602:     }
1.852     albertel 8603: 
1.838     albertel 8604:     sub hostname {
1.852     albertel 8605: 	&load_hosts_tab() if (!$loaded);
                   8606: 
1.838     albertel 8607: 	my ($lonid) = @_;
                   8608: 	return $hostname{$lonid};
                   8609:     }
1.845     albertel 8610: 
1.838     albertel 8611:     sub all_hostnames {
1.852     albertel 8612: 	&load_hosts_tab() if (!$loaded);
                   8613: 
1.838     albertel 8614: 	return %hostname;
                   8615:     }
1.845     albertel 8616: 
1.888     albertel 8617:     sub all_names {
                   8618: 	&load_hosts_tab() if (!$loaded);
                   8619: 
                   8620: 	return %name_to_host;
                   8621:     }
                   8622: 
1.845     albertel 8623:     sub is_library {
1.852     albertel 8624: 	&load_hosts_tab() if (!$loaded);
                   8625: 
1.845     albertel 8626: 	return exists($libserv{$_[0]});
                   8627:     }
                   8628: 
                   8629:     sub all_library {
1.852     albertel 8630: 	&load_hosts_tab() if (!$loaded);
                   8631: 
1.845     albertel 8632: 	return %libserv;
                   8633:     }
                   8634: 
1.841     albertel 8635:     sub get_servers {
1.852     albertel 8636: 	&load_hosts_tab() if (!$loaded);
                   8637: 
1.841     albertel 8638: 	my ($domain,$type) = @_;
                   8639: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8640: 	                                          : %hostname;
                   8641: 	my %result;
1.842     albertel 8642: 	if (ref($domain) eq 'ARRAY') {
                   8643: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8644: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8645: 		    $result{$host} = $hostname;
                   8646: 		}
                   8647: 	    }
                   8648: 	} else {
                   8649: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8650: 		if ($hostdom{$host} eq $domain) {
                   8651: 		    $result{$host} = $hostname;
                   8652: 		}
1.841     albertel 8653: 	    }
                   8654: 	}
                   8655: 	return %result;
                   8656:     }
1.845     albertel 8657: 
1.844     albertel 8658:     sub host_domain {
1.852     albertel 8659: 	&load_hosts_tab() if (!$loaded);
                   8660: 
1.844     albertel 8661: 	my ($lonid) = @_;
                   8662: 	return $hostdom{$lonid};
                   8663:     }
                   8664: 
1.841     albertel 8665:     sub all_domains {
1.852     albertel 8666: 	&load_hosts_tab() if (!$loaded);
                   8667: 
1.841     albertel 8668: 	my %seen;
                   8669: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8670: 	return @uniq;
                   8671:     }
1.1       albertel 8672: }
                   8673: 
1.847     albertel 8674: { 
                   8675:     my %iphost;
1.856     albertel 8676:     my %name_to_ip;
                   8677:     my %lonid_to_ip;
1.869     albertel 8678: 
1.847     albertel 8679:     sub get_hosts_from_ip {
                   8680: 	my ($ip) = @_;
                   8681: 	my %iphosts = &get_iphost();
                   8682: 	if (ref($iphosts{$ip})) {
                   8683: 	    return @{$iphosts{$ip}};
                   8684: 	}
                   8685: 	return;
1.839     albertel 8686:     }
1.864     albertel 8687:     
                   8688:     sub reset_hosts_ip_info {
                   8689: 	undef(%iphost);
                   8690: 	undef(%name_to_ip);
                   8691: 	undef(%lonid_to_ip);
                   8692:     }
1.856     albertel 8693: 
                   8694:     sub get_host_ip {
                   8695: 	my ($lonid) = @_;
                   8696: 	if (exists($lonid_to_ip{$lonid})) {
                   8697: 	    return $lonid_to_ip{$lonid};
                   8698: 	}
                   8699: 	my $name=&hostname($lonid);
                   8700:    	my $ip = gethostbyname($name);
                   8701: 	return if (!$ip || length($ip) ne 4);
                   8702: 	$ip=inet_ntoa($ip);
                   8703: 	$name_to_ip{$name}   = $ip;
                   8704: 	$lonid_to_ip{$lonid} = $ip;
                   8705: 	return $ip;
                   8706:     }
1.847     albertel 8707:     
                   8708:     sub get_iphost {
1.869     albertel 8709: 	my ($ignore_cache) = @_;
1.894     albertel 8710: 
1.869     albertel 8711: 	if (!$ignore_cache) {
                   8712: 	    if (%iphost) {
                   8713: 		return %iphost;
                   8714: 	    }
                   8715: 	    my ($ip_info,$cached)=
                   8716: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8717: 	    if ($cached) {
                   8718: 		%iphost      = %{$ip_info->[0]};
                   8719: 		%name_to_ip  = %{$ip_info->[1]};
                   8720: 		%lonid_to_ip = %{$ip_info->[2]};
                   8721: 		return %iphost;
                   8722: 	    }
                   8723: 	}
1.894     albertel 8724: 
                   8725: 	# get yesterday's info for fallback
                   8726: 	my %old_name_to_ip;
                   8727: 	my ($ip_info,$cached)=
                   8728: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8729: 	if ($cached) {
                   8730: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8731: 	}
                   8732: 
1.888     albertel 8733: 	my %name_to_host = &all_names();
                   8734: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8735: 	    my $ip;
                   8736: 	    if (!exists($name_to_ip{$name})) {
                   8737: 		$ip = gethostbyname($name);
                   8738: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8739: 		    if (defined($old_name_to_ip{$name})) {
                   8740: 			$ip = $old_name_to_ip{$name};
                   8741: 			&logthis("Can't find $name defaulting to old $ip");
                   8742: 		    } else {
                   8743: 			&logthis("Name $name no IP found");
                   8744: 			next;
                   8745: 		    }
                   8746: 		} else {
                   8747: 		    $ip=inet_ntoa($ip);
1.847     albertel 8748: 		}
                   8749: 		$name_to_ip{$name} = $ip;
                   8750: 	    } else {
                   8751: 		$ip = $name_to_ip{$name};
1.653     albertel 8752: 	    }
1.888     albertel 8753: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8754: 		$lonid_to_ip{$id} = $ip;
                   8755: 	    }
                   8756: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8757: 	}
1.869     albertel 8758: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8759: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8760: 				      48*60*60);
1.869     albertel 8761: 
1.847     albertel 8762: 	return %iphost;
1.598     albertel 8763:     }
                   8764: }
                   8765: 
1.862     albertel 8766: BEGIN {
                   8767: 
                   8768: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8769:     unless ($readit) {
                   8770: {
                   8771:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8772:     %perlvar = (%perlvar,%{$configvars});
                   8773: }
                   8774: 
                   8775: 
1.1       albertel 8776: # ------------------------------------------------------ Read spare server file
                   8777: {
1.448     albertel 8778:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8779: 
                   8780:     while (my $configline=<$config>) {
                   8781:        chomp($configline);
1.284     matthew  8782:        if ($configline) {
1.784     albertel 8783: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8784: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8785: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8786:        }
                   8787:     }
1.448     albertel 8788:     close($config);
1.1       albertel 8789: }
1.11      www      8790: # ------------------------------------------------------------ Read permissions
                   8791: {
1.448     albertel 8792:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8793: 
                   8794:     while (my $configline=<$config>) {
1.448     albertel 8795: 	chomp($configline);
                   8796: 	if ($configline) {
                   8797: 	    my ($role,$perm)=split(/ /,$configline);
                   8798: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8799: 	}
1.11      www      8800:     }
1.448     albertel 8801:     close($config);
1.11      www      8802: }
                   8803: 
                   8804: # -------------------------------------------- Read plain texts for permissions
                   8805: {
1.448     albertel 8806:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8807: 
                   8808:     while (my $configline=<$config>) {
1.448     albertel 8809: 	chomp($configline);
                   8810: 	if ($configline) {
1.742     raeburn  8811: 	    my ($short,@plain)=split(/:/,$configline);
                   8812:             %{$prp{$short}} = ();
                   8813: 	    if (@plain > 0) {
                   8814:                 $prp{$short}{'std'} = $plain[0];
                   8815:                 for (my $i=1; $i<@plain; $i++) {
                   8816:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8817:                 }
                   8818:             }
1.448     albertel 8819: 	}
1.135     www      8820:     }
1.448     albertel 8821:     close($config);
1.135     www      8822: }
                   8823: 
                   8824: # ---------------------------------------------------------- Read package table
                   8825: {
1.448     albertel 8826:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8827: 
                   8828:     while (my $configline=<$config>) {
1.483     albertel 8829: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8830: 	chomp($configline);
                   8831: 	my ($short,$plain)=split(/:/,$configline);
                   8832: 	my ($pack,$name)=split(/\&/,$short);
                   8833: 	if ($plain ne '') {
                   8834: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8835: 	    $packagetab{$short}=$plain; 
                   8836: 	}
1.11      www      8837:     }
1.448     albertel 8838:     close($config);
1.329     matthew  8839: }
                   8840: 
                   8841: # ------------- set up temporary directory
                   8842: {
                   8843:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8844: 
1.11      www      8845: }
                   8846: 
1.794     albertel 8847: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8848: 				'compress_threshold'=> 20_000,
                   8849:  			        });
1.185     www      8850: 
1.281     www      8851: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8852: $dumpcount=0;
1.958     www      8853: $locknum=0;
1.22      www      8854: 
1.163     harris41 8855: &logtouch();
1.672     albertel 8856: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8857: $readit=1;
1.564     albertel 8858:     {
                   8859: 	use integer;
                   8860: 	my $test=(2**32)+1;
1.568     albertel 8861: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8862: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8863:     }
1.195     www      8864: }
1.1       albertel 8865: }
1.179     www      8866: 
1.1       albertel 8867: 1;
1.191     harris41 8868: __END__
                   8869: 
1.243     albertel 8870: =pod
                   8871: 
1.191     harris41 8872: =head1 NAME
                   8873: 
1.243     albertel 8874: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8875: 
                   8876: =head1 SYNOPSIS
                   8877: 
1.243     albertel 8878: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8879: 
                   8880:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8881: 
1.243     albertel 8882: Common parameters:
                   8883: 
                   8884: =over 4
                   8885: 
                   8886: =item *
                   8887: 
                   8888: $uname : an internal username (if $cname expecting a course Id specifically)
                   8889: 
                   8890: =item *
                   8891: 
                   8892: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8893: 
                   8894: =item *
                   8895: 
                   8896: $symb : a resource instance identifier
                   8897: 
                   8898: =item *
                   8899: 
                   8900: $namespace : the name of a .db file that contains the data needed or
                   8901: being set.
                   8902: 
                   8903: =back
                   8904: 
1.394     bowersj2 8905: =head1 OVERVIEW
1.191     harris41 8906: 
1.394     bowersj2 8907: lonnet provides subroutines which interact with the
                   8908: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8909: about classes, users, and resources.
1.243     albertel 8910: 
                   8911: For many of these objects you can also use this to store data about
                   8912: them or modify them in various ways.
1.191     harris41 8913: 
1.394     bowersj2 8914: =head2 Symbs
1.191     harris41 8915: 
1.394     bowersj2 8916: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8917: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8918: map, the resource number of the resource in the map, and the URL of
                   8919: the resource itself. The latter is somewhat redundant, but might help
                   8920: if maps change.
                   8921: 
                   8922: An example is
                   8923: 
                   8924:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8925: 
                   8926: The respective map entry is
                   8927: 
                   8928:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8929:   title="Problem 2">
                   8930:  </resource>
                   8931: 
                   8932: Symbs are used by the random number generator, as well as to store and
                   8933: restore data specific to a certain instance of for example a problem.
                   8934: 
                   8935: =head2 Storing And Retrieving Data
                   8936: 
                   8937: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8938: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8939: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8940: is is the non-critical message twin of cstore. These functions are for
                   8941: handlers to store a perl hash to a user's permanent data space in an
                   8942: easy manner, and to retrieve it again on another call. It is expected
                   8943: that a handler would use this once at the beginning to retrieve data,
                   8944: and then again once at the end to send only the new data back.
                   8945: 
                   8946: The data is stored in the user's data directory on the user's
                   8947: homeserver under the ID of the course.
                   8948: 
                   8949: The hash that is returned by restore will have all of the previous
                   8950: value for all of the elements of the hash.
                   8951: 
                   8952: Example:
                   8953: 
                   8954:  #creating a hash
                   8955:  my %hash;
                   8956:  $hash{'foo'}='bar';
                   8957: 
                   8958:  #storing it
                   8959:  &Apache::lonnet::cstore(\%hash);
                   8960: 
                   8961:  #changing a value
                   8962:  $hash{'foo'}='notbar';
                   8963: 
                   8964:  #adding a new value
                   8965:  $hash{'bar'}='foo';
                   8966:  &Apache::lonnet::cstore(\%hash);
                   8967: 
                   8968:  #retrieving the hash
                   8969:  my %history=&Apache::lonnet::restore();
                   8970: 
                   8971:  #print the hash
                   8972:  foreach my $key (sort(keys(%history))) {
                   8973:    print("\%history{$key} = $history{$key}");
                   8974:  }
                   8975: 
                   8976: Will print out:
1.191     harris41 8977: 
1.394     bowersj2 8978:  %history{1:foo} = bar
                   8979:  %history{1:keys} = foo:timestamp
                   8980:  %history{1:timestamp} = 990455579
                   8981:  %history{2:bar} = foo
                   8982:  %history{2:foo} = notbar
                   8983:  %history{2:keys} = foo:bar:timestamp
                   8984:  %history{2:timestamp} = 990455580
                   8985:  %history{bar} = foo
                   8986:  %history{foo} = notbar
                   8987:  %history{timestamp} = 990455580
                   8988:  %history{version} = 2
                   8989: 
                   8990: Note that the special hash entries C<keys>, C<version> and
                   8991: C<timestamp> were added to the hash. C<version> will be equal to the
                   8992: total number of versions of the data that have been stored. The
                   8993: C<timestamp> attribute will be the UNIX time the hash was
                   8994: stored. C<keys> is available in every historical section to list which
                   8995: keys were added or changed at a specific historical revision of a
                   8996: hash.
                   8997: 
                   8998: B<Warning>: do not store the hash that restore returns directly. This
                   8999: will cause a mess since it will restore the historical keys as if the
                   9000: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9001: 
1.394     bowersj2 9002: Calling convention:
1.191     harris41 9003: 
1.394     bowersj2 9004:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9005:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9006: 
1.394     bowersj2 9007: For more detailed information, see lonnet specific documentation.
1.191     harris41 9008: 
1.394     bowersj2 9009: =head1 RETURN MESSAGES
1.191     harris41 9010: 
1.394     bowersj2 9011: =over 4
1.191     harris41 9012: 
1.394     bowersj2 9013: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9014: 
1.394     bowersj2 9015: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9016: when the connection is brought back up
1.191     harris41 9017: 
1.394     bowersj2 9018: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9019: for later delivery
1.191     harris41 9020: 
1.967     bisitz   9021: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9022: 
1.394     bowersj2 9023: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9024: that was requested
1.191     harris41 9025: 
1.243     albertel 9026: =back
1.191     harris41 9027: 
1.243     albertel 9028: =head1 PUBLIC SUBROUTINES
1.191     harris41 9029: 
1.243     albertel 9030: =head2 Session Environment Functions
1.191     harris41 9031: 
1.243     albertel 9032: =over 4
1.191     harris41 9033: 
1.394     bowersj2 9034: =item * 
                   9035: X<appenv()>
1.949     raeburn  9036: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9037: the user envirnoment file, and will be restored for each access this
1.620     albertel 9038: user makes during this session, also modifies the %env for the current
1.949     raeburn  9039: process. Optional rolesarrayref - if defined contains a reference to an array
                   9040: of roles which are exempt from the restriction on modifying user.role entries 
                   9041: in the user's environment.db and in %env.    
1.191     harris41 9042: 
                   9043: =item *
1.394     bowersj2 9044: X<delenv()>
                   9045: B<delenv($regexp)>: removes all items from the session
                   9046: environment file that matches the regular expression in $regexp. The
1.620     albertel 9047: values are also delted from the current processes %env.
1.191     harris41 9048: 
1.795     albertel 9049: =item * get_env_multiple($name) 
                   9050: 
                   9051: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9052: values may be defined and end up as an array ref.
                   9053: 
                   9054: returns an array of values
                   9055: 
1.243     albertel 9056: =back
                   9057: 
                   9058: =head2 User Information
1.191     harris41 9059: 
1.243     albertel 9060: =over 4
1.191     harris41 9061: 
                   9062: =item *
1.394     bowersj2 9063: X<queryauthenticate()>
                   9064: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9065: authentication scheme
                   9066: 
                   9067: =item *
1.394     bowersj2 9068: X<authenticate()>
                   9069: B<authenticate($uname,$upass,$udom)>: try to
                   9070: authenticate user from domain's lib servers (first use the current
                   9071: one). C<$upass> should be the users password.
1.191     harris41 9072: 
                   9073: =item *
1.394     bowersj2 9074: X<homeserver()>
                   9075: B<homeserver($uname,$udom)>: find the server which has
                   9076: the user's directory and files (there must be only one), this caches
                   9077: the answer, and also caches if there is a borken connection.
1.191     harris41 9078: 
                   9079: =item *
1.394     bowersj2 9080: X<idget()>
                   9081: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9082: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9083: username, and only 1 username per ID in a specific domain) (returns
                   9084: hash: id=>name,id=>name)
1.191     harris41 9085: 
                   9086: =item *
1.394     bowersj2 9087: X<idrget()>
                   9088: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9089: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9090: 
                   9091: =item *
1.394     bowersj2 9092: X<idput()>
                   9093: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9094: 
                   9095: =item *
1.394     bowersj2 9096: X<rolesinit()>
                   9097: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9098: 
                   9099: =item *
1.551     albertel 9100: X<getsection()>
                   9101: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9102: course $cname, return section name/number or '' for "not in course"
                   9103: and '-1' for "no section"
                   9104: 
                   9105: =item *
1.394     bowersj2 9106: X<userenvironment()>
                   9107: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9108: passed in @what from the requested user's environment, returns a hash
                   9109: 
1.858     raeburn  9110: =item * 
                   9111: X<userlog_query()>
1.859     albertel 9112: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9113: activity.log file. %filters defines filters applied when parsing the
                   9114: log file. These can be start or end timestamps, or the type of action
                   9115: - log to look for Login or Logout events, check for Checkin or
                   9116: Checkout, role for role selection. The response is in the form
                   9117: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9118: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9119: 
1.243     albertel 9120: =back
                   9121: 
                   9122: =head2 User Roles
                   9123: 
                   9124: =over 4
                   9125: 
                   9126: =item *
                   9127: 
1.810     raeburn  9128: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9129:  F: full access
                   9130:  U,I,K: authentication modes (cxx only)
                   9131:  '': forbidden
                   9132:  1: user needs to choose course
                   9133:  2: browse allowed
1.766     albertel 9134:  A: passphrase authentication needed
1.243     albertel 9135: 
                   9136: =item *
                   9137: 
                   9138: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9139: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9140: and course level
                   9141: 
                   9142: =item *
                   9143: 
                   9144: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9145: explanation of a user role term
                   9146: 
1.832     raeburn  9147: =item *
                   9148: 
1.935     raeburn  9149: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9150: All arguments are optional. Returns a hash of a roles, either for
                   9151: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9152: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9153: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9154: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9155: For each key, value is set to colon-separated start and end times for
                   9156: the role.  If no username and domain are specified, will default to
1.934     raeburn  9157: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9158: of role statuses (active, future or previous), roles 
                   9159: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9160: to restrict the list of roles reported. If no array ref is 
                   9161: provided for types, will default to return only active roles.
1.834     albertel 9162: 
1.243     albertel 9163: =back
                   9164: 
                   9165: =head2 User Modification
                   9166: 
                   9167: =over 4
                   9168: 
                   9169: =item *
                   9170: 
1.957     raeburn  9171: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9172: user for the level given by URL.  Optional start and end dates (leave empty
                   9173: string or zero for "no date")
1.191     harris41 9174: 
                   9175: =item *
                   9176: 
1.243     albertel 9177: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9178: change a users, password, possible return values are: ok,
                   9179: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9180: refused
1.191     harris41 9181: 
                   9182: =item *
                   9183: 
1.243     albertel 9184: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9185: 
                   9186: =item *
                   9187: 
1.963     raeburn  9188: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9189:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9190: modify user
1.191     harris41 9191: 
                   9192: =item *
                   9193: 
1.286     matthew  9194: modifystudent
                   9195: 
1.957     raeburn  9196: modify a student's enrollment and identification information.
1.286     matthew  9197: The course id is resolved based on the current users environment.  
                   9198: This means the envoking user must be a course coordinator or otherwise
                   9199: associated with a course.
                   9200: 
1.297     matthew  9201: This call is essentially a wrapper for lonnet::modifyuser and
                   9202: lonnet::modify_student_enrollment
1.286     matthew  9203: 
                   9204: Inputs: 
                   9205: 
                   9206: =over 4
                   9207: 
1.957     raeburn  9208: =item B<$udom> Student's loncapa domain
1.286     matthew  9209: 
1.957     raeburn  9210: =item B<$uname> Student's loncapa login name
1.286     matthew  9211: 
1.964     bisitz   9212: =item B<$uid> Student/Employee ID
1.286     matthew  9213: 
1.957     raeburn  9214: =item B<$umode> Student's authentication mode
1.286     matthew  9215: 
1.957     raeburn  9216: =item B<$upass> Student's password
1.286     matthew  9217: 
1.957     raeburn  9218: =item B<$first> Student's first name
1.286     matthew  9219: 
1.957     raeburn  9220: =item B<$middle> Student's middle name
1.286     matthew  9221: 
1.957     raeburn  9222: =item B<$last> Student's last name
1.286     matthew  9223: 
1.957     raeburn  9224: =item B<$gene> Student's generation
1.286     matthew  9225: 
1.957     raeburn  9226: =item B<$usec> Student's section in course
1.286     matthew  9227: 
                   9228: =item B<$end> Unix time of the roles expiration
                   9229: 
                   9230: =item B<$start> Unix time of the roles start date
                   9231: 
                   9232: =item B<$forceid> If defined, allow $uid to be changed
                   9233: 
                   9234: =item B<$desiredhome> server to use as home server for student
                   9235: 
1.957     raeburn  9236: =item B<$email> Student's permanent e-mail address
                   9237: 
                   9238: =item B<$type> Type of enrollment (auto or manual)
                   9239: 
1.963     raeburn  9240: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9241: 
                   9242: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9243: 
1.963     raeburn  9244: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9245: 
1.963     raeburn  9246: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9247: 
1.963     raeburn  9248: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9249: 
1.286     matthew  9250: =back
1.297     matthew  9251: 
                   9252: =item *
                   9253: 
                   9254: modify_student_enrollment
                   9255: 
                   9256: Change a students enrollment status in a class.  The environment variable
                   9257: 'role.request.course' must be defined for this function to proceed.
                   9258: 
                   9259: Inputs:
                   9260: 
                   9261: =over 4
                   9262: 
                   9263: =item $udom, students domain
                   9264: 
                   9265: =item $uname, students name
                   9266: 
                   9267: =item $uid, students user id
                   9268: 
                   9269: =item $first, students first name
                   9270: 
                   9271: =item $middle
                   9272: 
                   9273: =item $last
                   9274: 
                   9275: =item $gene
                   9276: 
                   9277: =item $usec
                   9278: 
                   9279: =item $end
                   9280: 
                   9281: =item $start
                   9282: 
1.957     raeburn  9283: =item $type
                   9284: 
                   9285: =item $locktype
                   9286: 
                   9287: =item $cid
                   9288: 
                   9289: =item $selfenroll
                   9290: 
                   9291: =item $context
                   9292: 
1.297     matthew  9293: =back
                   9294: 
1.191     harris41 9295: 
                   9296: =item *
                   9297: 
1.243     albertel 9298: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9299: custom role; give a custom role to a user for the level given by URL.  Specify
                   9300: name and domain of role author, and role name
1.191     harris41 9301: 
                   9302: =item *
                   9303: 
1.243     albertel 9304: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9305: 
                   9306: =item *
                   9307: 
1.243     albertel 9308: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9309: 
                   9310: =back
                   9311: 
                   9312: =head2 Course Infomation
                   9313: 
                   9314: =over 4
1.191     harris41 9315: 
                   9316: =item *
                   9317: 
1.631     albertel 9318: coursedescription($courseid) : returns a hash of information about the
                   9319: specified course id, including all environment settings for the
                   9320: course, the description of the course will be in the hash under the
                   9321: key 'description'
1.191     harris41 9322: 
                   9323: =item *
                   9324: 
1.624     albertel 9325: resdata($name,$domain,$type,@which) : request for current parameter
                   9326: setting for a specific $type, where $type is either 'course' or 'user',
                   9327: @what should be a list of parameters to ask about. This routine caches
                   9328: answers for 5 minutes.
1.243     albertel 9329: 
1.877     foxr     9330: =item *
                   9331: 
                   9332: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9333: data base, returning a hash that is keyed by the resource name and has
                   9334: values that are the resource value.  I believe that the timestamps and
                   9335: versions are also returned.
                   9336: 
                   9337: 
1.243     albertel 9338: =back
                   9339: 
                   9340: =head2 Course Modification
                   9341: 
                   9342: =over 4
1.191     harris41 9343: 
                   9344: =item *
                   9345: 
1.243     albertel 9346: writecoursepref($courseid,%prefs) : write preferences (environment
                   9347: database) for a course
1.191     harris41 9348: 
                   9349: =item *
                   9350: 
1.243     albertel 9351: createcourse($udom,$description,$url) : make/modify course
                   9352: 
                   9353: =back
                   9354: 
                   9355: =head2 Resource Subroutines
                   9356: 
                   9357: =over 4
1.191     harris41 9358: 
                   9359: =item *
                   9360: 
1.243     albertel 9361: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9362: 
                   9363: =item *
                   9364: 
1.243     albertel 9365: repcopy($filename) : subscribes to the requested file, and attempts to
                   9366: replicate from the owning library server, Might return
1.607     raeburn  9367: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9368: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9369: resource. Expects the local filesystem pathname
                   9370: (/home/httpd/html/res/....)
                   9371: 
                   9372: =back
                   9373: 
                   9374: =head2 Resource Information
                   9375: 
                   9376: =over 4
1.191     harris41 9377: 
                   9378: =item *
                   9379: 
1.243     albertel 9380: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9381: a vairety of different possible values, $varname should be a request
                   9382: string, and the other parameters can be used to specify who and what
                   9383: one is asking about.
                   9384: 
                   9385: Possible values for $varname are environment.lastname (or other item
                   9386: from the envirnment hash), user.name (or someother aspect about the
                   9387: user), resource.0.maxtries (or some other part and parameter of a
                   9388: resource)
1.204     albertel 9389: 
                   9390: =item *
                   9391: 
1.243     albertel 9392: directcondval($number) : get current value of a condition; reads from a state
                   9393: string
1.204     albertel 9394: 
                   9395: =item *
                   9396: 
1.243     albertel 9397: condval($condidx) : value of condition index based on state
1.204     albertel 9398: 
                   9399: =item *
                   9400: 
1.243     albertel 9401: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9402: resource's metadata, $what should be either a specific key, or either
                   9403: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9404: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9405: 
                   9406: this function automatically caches all requests
1.191     harris41 9407: 
                   9408: =item *
                   9409: 
1.243     albertel 9410: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9411: network of library servers; returns file handle of where SQL and regex results
                   9412: will be stored for query
1.191     harris41 9413: 
                   9414: =item *
                   9415: 
1.243     albertel 9416: symbread($filename) : return symbolic list entry (filename argument optional);
                   9417: returns the data handle
1.191     harris41 9418: 
                   9419: =item *
                   9420: 
1.243     albertel 9421: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9422: a possible symb for the URL in $thisfn, and if is an encryypted
                   9423: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9424: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9425: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9426: 
1.191     harris41 9427: 
                   9428: =item *
                   9429: 
1.243     albertel 9430: symbclean($symb) : removes versions numbers from a symb, returns the
                   9431: cleaned symb
1.191     harris41 9432: 
                   9433: =item *
                   9434: 
1.243     albertel 9435: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9436: course map, user must be in a course for it to work.
1.191     harris41 9437: 
                   9438: =item *
                   9439: 
1.243     albertel 9440: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9441: 
                   9442: =item *
                   9443: 
1.243     albertel 9444: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9445: a random seed, all arguments are optional, if they aren't sent it uses the
                   9446: environment to derive them. Note: if symb isn't sent and it can't get one
                   9447: from &symbread it will use the current time as its return value
1.191     harris41 9448: 
                   9449: =item *
                   9450: 
1.243     albertel 9451: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9452: unfakeable, receipt
1.191     harris41 9453: 
                   9454: =item *
                   9455: 
1.620     albertel 9456: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9461: 
                   9462: =item *
                   9463: 
1.243     albertel 9464: 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 9465: 
                   9466: =item *
                   9467: 
1.243     albertel 9468: 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 9469: 
                   9470: =item *
                   9471: 
1.243     albertel 9472: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9473: 
                   9474: =item *
                   9475: 
1.243     albertel 9476: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9477: forcing spreadsheet to reevaluate the resource scores next time.
                   9478: 
                   9479: =back
                   9480: 
                   9481: =head2 Storing/Retreiving Data
                   9482: 
                   9483: =over 4
1.191     harris41 9484: 
                   9485: =item *
                   9486: 
1.243     albertel 9487: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9488: for this url; hashref needs to be given and should be a \%hashname; the
                   9489: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9490: be derived from the env
1.191     harris41 9491: 
                   9492: =item *
                   9493: 
1.243     albertel 9494: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9495: uses critical subroutine
1.191     harris41 9496: 
                   9497: =item *
                   9498: 
1.243     albertel 9499: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9500: all args are optional
1.191     harris41 9501: 
                   9502: =item *
                   9503: 
1.717     albertel 9504: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9505: dumps the complete (or key matching regexp) namespace into a hash
                   9506: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9507: normally &store()ed into
                   9508: 
                   9509: $range should be either an integer '100' (give me the first 100
                   9510:                                            matching records)
                   9511:               or be  two integers sperated by a - with no spaces
                   9512:                  '30-50' (give me the 30th through the 50th matching
                   9513:                           records)
                   9514: 
                   9515: 
                   9516: =item *
                   9517: 
                   9518: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9519: replaces a &store() version of data with a replacement set of data
                   9520: for a particular resource in a namespace passed in the $storehash hash 
                   9521: reference
                   9522: 
                   9523: =item *
                   9524: 
1.243     albertel 9525: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9526: works very similar to store/cstore, but all data is stored in a
                   9527: temporary location and can be reset using tmpreset, $storehash should
                   9528: be a hash reference, returns nothing on success
1.191     harris41 9529: 
                   9530: =item *
                   9531: 
1.243     albertel 9532: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9533: similar to restore, but all data is stored in a temporary location and
                   9534: can be reset using tmpreset. Returns a hash of values on success,
                   9535: error string otherwise.
1.191     harris41 9536: 
                   9537: =item *
                   9538: 
1.243     albertel 9539: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9540: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9541: 
                   9542: =item *
                   9543: 
1.243     albertel 9544: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9545: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9546: 
                   9547: =item *
                   9548: 
1.243     albertel 9549: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9550: namesp ($udom and $uname are optional)
1.191     harris41 9551: 
                   9552: =item *
                   9553: 
1.702     albertel 9554: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9555: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9556: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9557: 
1.702     albertel 9558: $range should be either an integer '100' (give me the first 100
                   9559:                                            matching records)
                   9560:               or be  two integers sperated by a - with no spaces
                   9561:                  '30-50' (give me the 30th through the 50th matching
                   9562:                           records)
1.449     matthew  9563: =item *
                   9564: 
                   9565: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9566: $store can be a scalar, an array reference, or if the amount to be 
                   9567: incremented is > 1, a hash reference.
                   9568: 
                   9569: ($udom and $uname are optional)
1.191     harris41 9570: 
                   9571: =item *
                   9572: 
1.243     albertel 9573: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9574: ($udom and $uname are optional)
1.191     harris41 9575: 
                   9576: =item *
                   9577: 
1.243     albertel 9578: cput($namespace,$storehash,$udom,$uname) : critical put
                   9579: ($udom and $uname are optional)
1.191     harris41 9580: 
                   9581: =item *
                   9582: 
1.748     albertel 9583: newput($namespace,$storehash,$udom,$uname) :
                   9584: 
                   9585: Attempts to store the items in the $storehash, but only if they don't
                   9586: currently exist, if this succeeds you can be certain that you have 
                   9587: successfully created a new key value pair in the $namespace db.
                   9588: 
                   9589: 
                   9590: Args:
                   9591:  $namespace: name of database to store values to
                   9592:  $storehash: hashref to store to the db
                   9593:  $udom: (optional) domain of user containing the db
                   9594:  $uname: (optional) name of user caontaining the db
                   9595: 
                   9596: Returns:
                   9597:  'ok' -> succeeded in storing all keys of $storehash
                   9598:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9599:                         least <key> already existed in the db (other
                   9600:                         requested keys may also already exist)
1.967     bisitz   9601:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9602:  'con_lost' -> unable to contact request server
                   9603:  'refused' -> action was not allowed by remote machine
                   9604: 
                   9605: 
                   9606: =item *
                   9607: 
1.243     albertel 9608: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9609: reference filled in from namesp (encrypts the return communication)
                   9610: ($udom and $uname are optional)
1.191     harris41 9611: 
                   9612: =item *
                   9613: 
1.243     albertel 9614: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9615: critical subroutine
                   9616: 
1.806     raeburn  9617: =item *
                   9618: 
1.860     raeburn  9619: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9620: array reference filled in from namespace found in domain level on either
                   9621: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9622: 
                   9623: =item *
                   9624: 
1.860     raeburn  9625: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9626: domain level either on specified domain server ($uhome) or primary domain 
                   9627: server ($udom and $uhome are optional)
1.806     raeburn  9628: 
1.943     raeburn  9629: =item * 
                   9630: 
                   9631: get_domain_defaults($target_domain) : returns hash with defaults for
                   9632: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9633: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9634: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9635: Values are retrieved from cache (if current), or from domain's configuration.db
                   9636: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9637: or lonTabs/domain.tab. 
                   9638: 
                   9639: %domdefaults = &get_auth_defaults($target_domain);
                   9640: 
1.243     albertel 9641: =back
                   9642: 
                   9643: =head2 Network Status Functions
                   9644: 
                   9645: =over 4
1.191     harris41 9646: 
                   9647: =item *
                   9648: 
                   9649: dirlist($uri) : return directory list based on URI
                   9650: 
                   9651: =item *
                   9652: 
1.243     albertel 9653: spareserver() : find server with least workload from spare.tab
                   9654: 
                   9655: =back
                   9656: 
                   9657: =head2 Apache Request
                   9658: 
                   9659: =over 4
1.191     harris41 9660: 
                   9661: =item *
                   9662: 
1.243     albertel 9663: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9664: localhost, posts hash
                   9665: 
                   9666: =back
                   9667: 
                   9668: =head2 Data to String to Data
                   9669: 
                   9670: =over 4
1.191     harris41 9671: 
                   9672: =item *
                   9673: 
1.243     albertel 9674: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9675: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9676: 
                   9677: =item *
                   9678: 
1.243     albertel 9679: hashref2str($hashref) : convert a hashref into a string complete with
                   9680: escaping and '=' and '&' separators, supports elements that are
                   9681: arrayrefs and hashrefs
1.191     harris41 9682: 
                   9683: =item *
                   9684: 
1.243     albertel 9685: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9686: with escaping and '&' separators, supports elements that are arrayrefs
                   9687: and hashrefs
1.191     harris41 9688: 
                   9689: =item *
                   9690: 
1.243     albertel 9691: str2hash($string) : convert string to hash using unescaping and
                   9692: splitting on '=' and '&', supports elements that are arrayrefs and
                   9693: hashrefs
1.191     harris41 9694: 
                   9695: =item *
                   9696: 
1.243     albertel 9697: str2array($string) : convert string to hash using unescaping and
                   9698: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9699: 
                   9700: =back
                   9701: 
                   9702: =head2 Logging Routines
                   9703: 
                   9704: =over 4
                   9705: 
                   9706: These routines allow one to make log messages in the lonnet.log and
                   9707: lonnet.perm logfiles.
1.191     harris41 9708: 
                   9709: =item *
                   9710: 
1.243     albertel 9711: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9712: 
                   9713: =item *
                   9714: 
1.243     albertel 9715: logthis() : append message to the normal lonnet.log file, it gets
                   9716: preiodically rolled over and deleted.
1.191     harris41 9717: 
                   9718: =item *
                   9719: 
1.243     albertel 9720: logperm() : append a permanent message to lonnet.perm.log, this log
                   9721: file never gets deleted by any automated portion of the system, only
                   9722: messages of critical importance should go in here.
                   9723: 
                   9724: =back
                   9725: 
                   9726: =head2 General File Helper Routines
                   9727: 
                   9728: =over 4
1.191     harris41 9729: 
                   9730: =item *
                   9731: 
1.481     raeburn  9732: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9733: (a) files in /uploaded
                   9734:   (i) If a local copy of the file exists - 
                   9735:       compares modification date of local copy with last-modified date for 
                   9736:       definitive version stored on home server for course. If local copy is 
                   9737:       stale, requests a new version from the home server and stores it. 
                   9738:       If the original has been removed from the home server, then local copy 
                   9739:       is unlinked.
                   9740:   (ii) If local copy does not exist -
                   9741:       requests the file from the home server and stores it. 
                   9742:   
                   9743:   If $caller is 'uploadrep':  
                   9744:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9745:     for request for files originally uploaded via DOCS. 
                   9746:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9747:   
                   9748:   Otherwise:
                   9749:      This indicates a call from the content generation phase of the request.
                   9750:      -  returns the entire contents of the file or -1.
                   9751:      
                   9752: (b) files in /res
                   9753:    - returns the entire contents of a file or -1; 
                   9754:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9755: 
1.712     albertel 9756: 
                   9757: =item *
                   9758: 
                   9759: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9760:                   reference
                   9761: 
                   9762: returns either a stat() list of data about the file or an empty list
                   9763: if the file doesn't exist or couldn't find out about it (connection
                   9764: problems or user unknown)
                   9765: 
1.191     harris41 9766: =item *
                   9767: 
1.243     albertel 9768: filelocation($dir,$file) : returns file system location of a file
                   9769: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9770: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9771: and a file of ../bob will become /a/bob)
1.191     harris41 9772: 
                   9773: =item *
                   9774: 
                   9775: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9776: filelocation except for hrefs
                   9777: 
                   9778: =item *
                   9779: 
                   9780: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9781: 
1.243     albertel 9782: =back
                   9783: 
1.608     albertel 9784: =head2 Usererfile file routines (/uploaded*)
                   9785: 
                   9786: =over 4
                   9787: 
                   9788: =item *
                   9789: 
                   9790: userfileupload(): main rotine for putting a file in a user or course's
                   9791:                   filespace, arguments are,
                   9792: 
1.620     albertel 9793:  formname - required - this is the name of the element in $env where the
1.608     albertel 9794:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9795:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9796:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9797:  coursedoc - if true, store the file in the course of the active role
                   9798:              of the current user
                   9799:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9800:          if undefined, it will be placed in "unknown"
                   9801: 
                   9802:  (This routine calls clean_filename() to remove any dangerous
                   9803:  characters from the filename, and then calls finuserfileupload() to
                   9804:  complete the transaction)
                   9805: 
                   9806:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9807:  and /adm/notfound.html if unsuccessful
                   9808: 
                   9809: =item *
                   9810: 
                   9811: clean_filename(): routine for cleaing a filename up for storage in
                   9812:                  userfile space, argument is:
                   9813: 
                   9814:  filename - proposed filename
                   9815: 
                   9816: returns: the new clean filename
                   9817: 
                   9818: =item *
                   9819: 
                   9820: finishuserfileupload(): routine that creaes and sends the file to
                   9821: userspace, probably shouldn't be called directly
                   9822: 
                   9823:   docuname: username or courseid of destination for the file
                   9824:   docudom: domain of user/course of destination for the file
                   9825:   formname: same as for userfileupload()
                   9826:   fname: filename (inculding subdirectories) for the file
                   9827: 
                   9828:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9829:  and /adm/notfound.html if unsuccessful
                   9830: 
                   9831: =item *
                   9832: 
                   9833: renameuserfile(): renames an existing userfile to a new name
                   9834: 
                   9835:   Args:
                   9836:    docuname: username or courseid of destination for the file
                   9837:    docudom: domain of user/course of destination for the file
                   9838:    old: current file name (including any subdirs under userfiles)
                   9839:    new: desired file name (including any subdirs under userfiles)
                   9840: 
                   9841: =item *
                   9842: 
                   9843: mkdiruserfile(): creates a directory is a userfiles dir
                   9844: 
                   9845:   Args:
                   9846:    docuname: username or courseid of destination for the file
                   9847:    docudom: domain of user/course of destination for the file
                   9848:    dir: dir to create (including any subdirs under userfiles)
                   9849: 
                   9850: =item *
                   9851: 
                   9852: removeuserfile(): removes a file that exists in userfiles
                   9853: 
                   9854:   Args:
                   9855:    docuname: username or courseid of destination for the file
                   9856:    docudom: domain of user/course of destination for the file
                   9857:    fname: filname to delete (including any subdirs under userfiles)
                   9858: 
                   9859: =item *
                   9860: 
                   9861: removeuploadedurl(): convience function for removeuserfile()
                   9862: 
                   9863:   Args:
                   9864:    url:  a full /uploaded/... url to delete
                   9865: 
1.747     albertel 9866: =item * 
                   9867: 
                   9868: get_portfile_permissions():
                   9869:   Args:
                   9870:     domain: domain of user or course contain the portfolio files
                   9871:     user: name of user or num of course contain the portfolio files
                   9872:   Returns:
                   9873:     hashref of a dump of the proper file_permissions.db
                   9874:    
                   9875: 
                   9876: =item * 
                   9877: 
                   9878: get_access_controls():
                   9879: 
                   9880: Args:
                   9881:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9882:   group: (optional) the group you want the files associated with
                   9883:   file: (optional) the file you want access info on
                   9884: 
                   9885: Returns:
1.749     raeburn  9886:     a hash (keys are file names) of hashes containing
                   9887:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9888:         values are XML containing access control settings (see below) 
1.747     albertel 9889: 
                   9890: Internal notes:
                   9891: 
1.749     raeburn  9892:  access controls are stored in file_permissions.db as key=value pairs.
                   9893:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9894:         where scope -> public,guest,course,group,domains or users.
                   9895:               end -> UNIX time for end of access (0 -> no end date)
                   9896:               start -> UNIX time for start of access
                   9897: 
                   9898:     value -> XML description of access control
                   9899:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9900:             <start></start>
                   9901:             <end></end>
                   9902: 
                   9903:             <password></password>  for scope type = guest
                   9904: 
                   9905:             <domain></domain>     for scope type = course or group
                   9906:             <number></number>
                   9907:             <roles id="">
                   9908:              <role></role>
                   9909:              <access></access>
                   9910:              <section></section>
                   9911:              <group></group>
                   9912:             </roles>
                   9913: 
                   9914:             <dom></dom>         for scope type = domains
                   9915: 
                   9916:             <users>             for scope type = users
                   9917:              <user>
                   9918:               <uname></uname>
                   9919:               <udom></udom>
                   9920:              </user>
                   9921:             </users>
                   9922:            </scope> 
                   9923:               
                   9924:  Access data is also aggregated for each file in an additional key=value pair:
                   9925:  key -> path to file/file_name\0accesscontrol 
                   9926:  value -> reference to hash
                   9927:           hash contains key = value pairs
                   9928:           where key = uniqueID:scope_end_start
                   9929:                 value = UNIX time record was last updated
                   9930: 
                   9931:           Used to improve speed of look-ups of access controls for each file.  
                   9932:  
                   9933:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9934: 
                   9935: modify_access_controls():
                   9936: 
                   9937: Modifies access controls for a portfolio file
                   9938: Args
                   9939: 1. file name
                   9940: 2. reference to hash of required changes,
                   9941: 3. domain
                   9942: 4. username
                   9943:   where domain,username are the domain of the portfolio owner 
                   9944:   (either a user or a course) 
                   9945: 
                   9946: Returns:
                   9947: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9948: 2. result of deletions ('ok' or 'error', with error message).
                   9949: 3. reference to hash of any new or updated access controls.
                   9950: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9951:    key = integer (inbound ID)
                   9952:    value = uniqueID  
1.747     albertel 9953: 
1.608     albertel 9954: =back
                   9955: 
1.243     albertel 9956: =head2 HTTP Helper Routines
                   9957: 
                   9958: =over 4
                   9959: 
1.191     harris41 9960: =item *
                   9961: 
                   9962: escape() : unpack non-word characters into CGI-compatible hex codes
                   9963: 
                   9964: =item *
                   9965: 
                   9966: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9967: 
1.243     albertel 9968: =back
                   9969: 
                   9970: =head1 PRIVATE SUBROUTINES
                   9971: 
                   9972: =head2 Underlying communication routines (Shouldn't call)
                   9973: 
                   9974: =over 4
                   9975: 
                   9976: =item *
                   9977: 
                   9978: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9979: 
                   9980: =item *
                   9981: 
                   9982: reply() : uses subreply to send a message to remote machine, logs all failures
                   9983: 
                   9984: =item *
                   9985: 
                   9986: critical() : passes a critical message to another server; if cannot
                   9987: get through then place message in connection buffer directory and
                   9988: returns con_delayed, if incapable of saving message, returns
                   9989: con_failed
                   9990: 
                   9991: =item *
                   9992: 
                   9993: reconlonc() : tries to reconnect lonc client processes.
                   9994: 
                   9995: =back
                   9996: 
                   9997: =head2 Resource Access Logging
                   9998: 
                   9999: =over 4
                   10000: 
                   10001: =item *
                   10002: 
                   10003: flushcourselogs() : flush (save) buffer logs and access logs
                   10004: 
                   10005: =item *
                   10006: 
                   10007: courselog($what) : save message for course in hash
                   10008: 
                   10009: =item *
                   10010: 
                   10011: courseacclog($what) : save message for course using &courselog().  Perform
                   10012: special processing for specific resource types (problems, exams, quizzes, etc).
                   10013: 
1.191     harris41 10014: =item *
                   10015: 
                   10016: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10017: as a PerlChildExitHandler
1.243     albertel 10018: 
                   10019: =back
                   10020: 
                   10021: =head2 Other
                   10022: 
                   10023: =over 4
                   10024: 
                   10025: =item *
                   10026: 
                   10027: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10028: 
                   10029: =back
                   10030: 
                   10031: =cut
1.877     foxr     10032: 

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