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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.975   ! raeburn     4: # $Id: lonnet.pm,v 1.974 2008/11/29 09:57:43 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
                     76: # use Date::Parse;
1.871     albertel   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    78:             $_64bit %env %protocol);
1.871     albertel   79: 
                     80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        83:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        84: 
1.1       albertel   85: use IO::Socket;
1.31      www        86: use GDBM_File;
1.208     albertel   87: use HTML::LCParser;
1.88      www        88: use Fcntl qw(:flock);
1.870     albertel   89: use Storable qw(thaw nfreeze);
1.539     albertel   90: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   91: use Cache::Memcached;
1.676     albertel   92: use Digest::MD5;
1.790     albertel   93: use Math::Random;
1.807     albertel   94: use LONCAPA qw(:DEFAULT :match);
1.740     www        95: use LONCAPA::Configuration;
1.676     albertel   96: 
1.195     www        97: my $readit;
1.550     foxr       98: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   99: 
1.619     albertel  100: require Exporter;
                    101: 
                    102: our @ISA = qw (Exporter);
                    103: our @EXPORT = qw(%env);
                    104: 
1.449     matthew   105: 
1.1       albertel  106: # --------------------------------------------------------------------- Logging
1.729     www       107: {
                    108:     my $logid;
                    109:     sub instructor_log {
1.957     raeburn   110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    111:         if (($cnum eq '') || ($cdom eq '')) {
                    112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    114:         }
1.729     www       115: 	$logid++;
1.957     raeburn   116:         my $now = time();
                    117: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       119: 				    { $id => {
                    120: 					'exe_uname' => $env{'user.name'},
                    121: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   122: 					'exe_time'  => $now,
1.730     www       123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    124: 					'delflag'   => $delflag,
                    125: 					'logentry'  => $storehash,
                    126: 					'uname'     => $uname,
                    127: 					'udom'      => $udom,
                    128: 				    }
1.957     raeburn   129: 				  },$cdom,$cnum);
1.729     www       130:     }
                    131: }
1.1       albertel  132: 
1.163     harris41  133: sub logtouch {
                    134:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  135:     unless (-e "$execdir/logs/lonnet.log") {	
                    136: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  137: 	close $fh;
                    138:     }
                    139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    141: }
                    142: 
1.1       albertel  143: sub logthis {
                    144:     my $message=shift;
                    145:     my $execdir=$perlvar{'lonDaemons'};
                    146:     my $now=time;
                    147:     my $local=localtime($now);
1.448     albertel  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    149: 	print $fh "$local ($$): $message\n";
                    150: 	close($fh);
                    151:     }
1.1       albertel  152:     return 1;
                    153: }
                    154: 
                    155: sub logperm {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.448     albertel  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    161: 	print $fh "$now:$message:$local\n";
                    162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
1.850     albertel  167: sub create_connection {
1.853     albertel  168:     my ($hostname,$lonid) = @_;
1.851     albertel  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  170: 				     Type    => SOCK_STREAM,
                    171: 				     Timeout => 10);
                    172:     return 0 if (!$client);
1.890     albertel  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  174:     my $result = <$client>;
                    175:     chomp($result);
                    176:     return 1 if ($result eq 'done');
                    177:     return 0;
                    178: }
                    179: 
                    180: 
1.1       albertel  181: # -------------------------------------------------- Non-critical communication
                    182: sub subreply {
                    183:     my ($cmd,$server)=@_;
1.838     albertel  184:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      185:     #
                    186:     #  With loncnew process trimming, there's a timing hole between lonc server
                    187:     #  process exit and the master server picking up the listen on the AF_UNIX
                    188:     #  socket.  In that time interval, a lock file will exist:
                    189: 
                    190:     my $lockfile=$peerfile.".lock";
                    191:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    192: 	sleep(1);
                    193:     }
                    194:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      195:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      196:     #
1.550     foxr      197:     #   We'll give the connection a few tries before abandoning it.  If
                    198:     #   connection is not possible, we'll con_lost back to the client.
                    199:     #   
                    200:     my $client;
                    201:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    202: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    203: 				      Type    => SOCK_STREAM,
                    204: 				      Timeout => 10);
1.869     albertel  205: 	if ($client) {
1.550     foxr      206: 	    last;		# Connected!
1.850     albertel  207: 	} else {
1.853     albertel  208: 	    &create_connection(&hostname($server),$server);
1.550     foxr      209: 	}
1.850     albertel  210:         sleep(1);		# Try again later if failed connection.
1.550     foxr      211:     }
                    212:     my $answer;
                    213:     if ($client) {
1.704     albertel  214: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      215: 	$answer=<$client>;
                    216: 	if (!$answer) { $answer="con_lost"; }
                    217: 	chomp($answer);
                    218:     } else {
                    219: 	$answer = 'con_lost';	# Failed connection.
                    220:     }
1.1       albertel  221:     return $answer;
                    222: }
                    223: 
                    224: sub reply {
                    225:     my ($cmd,$server)=@_;
1.838     albertel  226:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  227:     my $answer=subreply($cmd,$server);
1.65      www       228:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  229:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       230:                 " $cmd to $server returned $answer</font>");
                    231:     }
1.1       albertel  232:     return $answer;
                    233: }
                    234: 
                    235: # ----------------------------------------------------------- Send USR1 to lonc
                    236: 
                    237: sub reconlonc {
1.891     albertel  238:     my ($lonid) = @_;
                    239:     my $hostname = &hostname($lonid);
                    240:     if ($lonid) {
                    241: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    242: 	if ($hostname && -e $peerfile) {
                    243: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    244: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    245: 					     Type    => SOCK_STREAM,
                    246: 					     Timeout => 10);
                    247: 	    if ($client) {
                    248: 		print $client ("reset_retries\n");
                    249: 		my $answer=<$client>;
                    250: 		#reset just this one.
                    251: 	    }
                    252: 	}
                    253: 	return;
                    254:     }
                    255: 
1.836     www       256:     &logthis("Trying to reconnect lonc");
1.1       albertel  257:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  258:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  259: 	my $loncpid=<$fh>;
                    260:         chomp($loncpid);
                    261:         if (kill 0 => $loncpid) {
                    262: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    263:             kill USR1 => $loncpid;
                    264:             sleep 1;
1.836     www       265:          } else {
1.12      www       266: 	    &logthis(
1.672     albertel  267:                "<font color=\"blue\">WARNING:".
1.12      www       268:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  269:         }
                    270:     } else {
1.836     www       271: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  272:     }
                    273: }
                    274: 
                    275: # ------------------------------------------------------ Critical communication
1.12      www       276: 
1.1       albertel  277: sub critical {
                    278:     my ($cmd,$server)=@_;
1.838     albertel  279:     unless (&hostname($server)) {
1.672     albertel  280:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       281:                " Critical message to unknown server ($server)</font>");
                    282:         return 'no_such_host';
                    283:     }
1.1       albertel  284:     my $answer=reply($cmd,$server);
                    285:     if ($answer eq 'con_lost') {
                    286: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  287: 	my $answer=reply($cmd,$server);
1.1       albertel  288:         if ($answer eq 'con_lost') {
                    289:             my $now=time;
                    290:             my $middlename=$cmd;
1.5       www       291:             $middlename=substr($middlename,0,16);
1.1       albertel  292:             $middlename=~s/\W//g;
                    293:             my $dfilename=
1.305     www       294:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    295:             $dumpcount++;
1.1       albertel  296:             {
1.448     albertel  297: 		my $dfh;
                    298: 		if (open($dfh,">$dfilename")) {
                    299: 		    print $dfh "$cmd\n"; 
                    300: 		    close($dfh);
                    301: 		}
1.1       albertel  302:             }
                    303:             sleep 2;
                    304:             my $wcmd='';
                    305:             {
1.448     albertel  306: 		my $dfh;
                    307: 		if (open($dfh,"<$dfilename")) {
                    308: 		    $wcmd=<$dfh>; 
                    309: 		    close($dfh);
                    310: 		}
1.1       albertel  311:             }
                    312:             chomp($wcmd);
1.7       www       313:             if ($wcmd eq $cmd) {
1.672     albertel  314: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       315:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  316:                 &logperm("D:$server:$cmd");
                    317: 	        return 'con_delayed';
                    318:             } else {
1.672     albertel  319:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       320:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  321:                 &logperm("F:$server:$cmd");
                    322:                 return 'con_failed';
                    323:             }
                    324:         }
                    325:     }
                    326:     return $answer;
1.405     albertel  327: }
                    328: 
1.755     albertel  329: # ------------------------------------------- check if return value is an error
                    330: 
                    331: sub error {
                    332:     my ($result) = @_;
1.756     albertel  333:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  334: 	if ($2 == 2) { return undef; }
                    335: 	return $1;
                    336:     }
                    337:     return undef;
                    338: }
                    339: 
1.783     albertel  340: sub convert_and_load_session_env {
                    341:     my ($lonidsdir,$handle)=@_;
                    342:     my @profile;
                    343:     {
1.917     albertel  344: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    345: 	if (!$opened) {
1.915     albertel  346: 	    return 0;
                    347: 	}
1.783     albertel  348: 	flock($idf,LOCK_SH);
                    349: 	@profile=<$idf>;
                    350: 	close($idf);
                    351:     }
                    352:     my %temp_env;
                    353:     foreach my $line (@profile) {
1.786     albertel  354: 	if ($line !~ m/=/) {
                    355: 	    return 0;
                    356: 	}
1.783     albertel  357: 	chomp($line);
                    358: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    359: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    360:     }
                    361:     unlink("$lonidsdir/$handle.id");
                    362:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    363: 	    0640)) {
                    364: 	%disk_env = %temp_env;
                    365: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    366: 	untie(%disk_env);
                    367:     }
1.786     albertel  368:     return 1;
1.783     albertel  369: }
                    370: 
1.374     www       371: # ------------------------------------------- Transfer profile into environment
1.780     albertel  372: my $env_loaded;
                    373: sub transfer_profile_to_env {
1.788     albertel  374:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    375:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       376: 
1.720     albertel  377:     if (!defined($lonidsdir)) {
                    378: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    379:     }
                    380:     if (!defined($handle)) {
                    381:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    382:     }
                    383: 
1.786     albertel  384:     my $convert;
                    385:     {
1.917     albertel  386:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    387: 	if (!$opened) {
1.915     albertel  388: 	    return;
                    389: 	}
1.786     albertel  390: 	flock($idf,LOCK_SH);
                    391: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    392: 		&GDBM_READER(),0640)) {
                    393: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    394: 	    untie(%disk_env);
                    395: 	} else {
                    396: 	    $convert = 1;
                    397: 	}
                    398:     }
                    399:     if ($convert) {
                    400: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    401: 	    &logthis("Failed to load session, or convert session.");
                    402: 	}
1.374     www       403:     }
1.783     albertel  404: 
1.786     albertel  405:     my %remove;
1.783     albertel  406:     while ( my $envname = each(%env) ) {
1.433     matthew   407:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    408:             if ($time < time-300) {
1.783     albertel  409:                 $remove{$key}++;
1.433     matthew   410:             }
                    411:         }
                    412:     }
1.783     albertel  413: 
1.619     albertel  414:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  415:     $env_loaded=1;
1.783     albertel  416:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   417:         &delenv($expired_key);
1.374     www       418:     }
1.1       albertel  419: }
                    420: 
1.916     albertel  421: # ---------------------------------------------------- Check for valid session 
                    422: sub check_for_valid_session {
                    423:     my ($r) = @_;
                    424:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    425:     my $lonid=$cookies{'lonID'};
                    426:     return undef if (!$lonid);
                    427: 
                    428:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    429:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    430:     return undef if (!-e "$lonidsdir/$handle.id");
                    431: 
1.917     albertel  432:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    433:     return undef if (!$opened);
1.916     albertel  434: 
                    435:     flock($idf,LOCK_SH);
                    436:     my %disk_env;
                    437:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    438: 	    &GDBM_READER(),0640)) {
                    439: 	return undef;	
                    440:     }
                    441: 
                    442:     if (!defined($disk_env{'user.name'})
                    443: 	|| !defined($disk_env{'user.domain'})) {
                    444: 	return undef;
                    445:     }
                    446:     return $handle;
                    447: }
                    448: 
1.830     albertel  449: sub timed_flock {
                    450:     my ($file,$lock_type) = @_;
                    451:     my $failed=0;
                    452:     eval {
                    453: 	local $SIG{__DIE__}='DEFAULT';
                    454: 	local $SIG{ALRM}=sub {
                    455: 	    $failed=1;
                    456: 	    die("failed lock");
                    457: 	};
                    458: 	alarm(13);
                    459: 	flock($file,$lock_type);
                    460: 	alarm(0);
                    461:     };
                    462:     if ($failed) {
                    463: 	return undef;
                    464:     } else {
                    465: 	return 1;
                    466:     }
                    467: }
                    468: 
1.5       www       469: # ---------------------------------------------------------- Append Environment
                    470: 
                    471: sub appenv {
1.949     raeburn   472:     my ($newenv,$roles) = @_;
                    473:     if (ref($newenv) eq 'HASH') {
                    474:         foreach my $key (keys(%{$newenv})) {
                    475:             my $refused = 0;
                    476: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    477:                 $refused = 1;
                    478:                 if (ref($roles) eq 'ARRAY') {
                    479:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    480:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    481:                         $refused = 0;
                    482:                     }
                    483:                 }
                    484:             }
                    485:             if ($refused) {
                    486:                 &logthis("<font color=\"blue\">WARNING: ".
                    487:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    488:                          .'</font>');
                    489: 	        delete($newenv->{$key});
                    490:             } else {
                    491:                 $env{$key}=$newenv->{$key};
                    492:             }
                    493:         }
                    494:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    495:         if ($opened
                    496: 	    && &timed_flock($env_file,LOCK_EX)
                    497: 	    &&
                    498: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    499: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    500: 	    while (my ($key,$value) = each(%{$newenv})) {
                    501: 	        $disk_env{$key} = $value;
                    502: 	    }
                    503: 	    untie(%disk_env);
1.35      www       504:         }
1.191     harris41  505:     }
1.56      www       506:     return 'ok';
                    507: }
                    508: # ----------------------------------------------------- Delete from Environment
                    509: 
                    510: sub delenv {
                    511:     my $delthis=shift;
                    512:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  513:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       514:                 "Attempt to delete from environment ".$delthis);
                    515:         return 'error';
                    516:     }
1.917     albertel  517:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    518:     if ($opened
1.915     albertel  519: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  520: 	&&
                    521: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    522: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  523: 	foreach my $key (keys(%disk_env)) {
                    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\.(.*)/) {
1.975   ! raeburn  2492:                 my $formitem = $1;
        !          2493:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
        !          2494:                     $what.=':'.$formitem.'='.$env{$key};
        !          2495:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
        !          2496:                     $what.=':'.$formitem.'='.$env{$key};
        !          2497:                 }
1.158     www      2498:             }
1.191     harris41 2499:         }
1.583     matthew  2500:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2501:         # FIXME: We should not be depending on a form parameter that someone
                   2502:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2503:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2504:             $what.= ':POST';
                   2505:             # FIXME: Probably ought to escape things....
                   2506:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2507:                                  'crsdiscuss') {
1.620     albertel 2508:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2509:             }
                   2510:         }
1.158     www      2511:     }
                   2512:     &courselog($what);
1.149     www      2513: }
                   2514: 
1.185     www      2515: sub countacc {
                   2516:     my $url=&declutter(shift);
1.458     matthew  2517:     return if (! defined($url) || $url eq '');
1.620     albertel 2518:     unless ($env{'request.course.id'}) { return ''; }
                   2519:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2520:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2521:     $accesshash{$key}++;
1.185     www      2522: }
1.349     www      2523: 
1.361     www      2524: sub linklog {
                   2525:     my ($from,$to)=@_;
                   2526:     $from=&declutter($from);
                   2527:     $to=&declutter($to);
                   2528:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2529:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2530: }
                   2531:   
1.349     www      2532: sub userrolelog {
                   2533:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2534:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2535:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2536:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2537:         ($trole=~/^ta/)) {
1.350     www      2538:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2539:        $userrolehash
                   2540:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2541:                     =$tend.':'.$tstart;
1.662     raeburn  2542:     }
1.898     albertel 2543:     if (($env{'request.role'} =~ /dc\./) &&
                   2544: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2545: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2546: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2547:        $userrolehash
                   2548:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2549:                     =$tend.':'.$tstart;
                   2550:     }
1.662     raeburn  2551:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2552:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2553:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2554:         ($trole=~/^sc/)) {
                   2555:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2556:        $domainrolehash
                   2557:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2558:                     = $tend.':'.$tstart;
                   2559:     }
1.351     www      2560: }
                   2561: 
1.957     raeburn  2562: sub courserolelog {
                   2563:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2564:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2565:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2566:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2567:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2568:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2569:             my $cdom = $1;
                   2570:             my $cnum = $2;
                   2571:             my $sec = $3;
                   2572:             my $namespace = 'rolelog';
                   2573:             my %storehash = (
                   2574:                                role    => $trole,
                   2575:                                start   => $tstart,
                   2576:                                end     => $tend,
                   2577:                                selfenroll => $selfenroll,
                   2578:                                context    => $context,
                   2579:                             );
                   2580:             if ($trole eq 'gr') {
                   2581:                 $namespace = 'groupslog';
                   2582:                 $storehash{'group'} = $sec;
                   2583:             } else {
                   2584:                 $storehash{'section'} = $sec;
                   2585:             }
                   2586:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2587:         }
                   2588:     }
                   2589:     return;
                   2590: }
                   2591: 
1.351     www      2592: sub get_course_adv_roles {
1.948     raeburn  2593:     my ($cid,$codes) = @_;
1.620     albertel 2594:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2595:     my %coursehash=&coursedescription($cid);
1.470     www      2596:     my %nothide=();
1.800     albertel 2597:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2598:         if ($user !~ /:/) {
                   2599: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2600:         } else {
                   2601:             $nothide{$user}=1;
                   2602:         }
1.470     www      2603:     }
1.351     www      2604:     my %returnhash=();
                   2605:     my %dumphash=
                   2606:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2607:     my $now=time;
1.800     albertel 2608:     foreach my $entry (keys %dumphash) {
                   2609: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2610:         if (($tstart) && ($tstart<0)) { next; }
                   2611:         if (($tend) && ($tend<$now)) { next; }
                   2612:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2613:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2614: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2615: 	if ((&privileged($username,$domain)) && 
                   2616: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2617: 	if ($role eq 'cr') { next; }
1.948     raeburn  2618:         if ($codes) {
                   2619:             if ($section) { $role .= ':'.$section; }
                   2620:             if ($returnhash{$role}) {
                   2621:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2622:             } else {
                   2623:                 $returnhash{$role}=$username.':'.$domain;
                   2624:             }
1.351     www      2625:         } else {
1.948     raeburn  2626:             my $key=&plaintext($role);
1.973     bisitz   2627:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2628:             if ($returnhash{$key}) {
                   2629: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2630:             } else {
                   2631:                 $returnhash{$key}=$username.':'.$domain;
                   2632:             }
1.351     www      2633:         }
1.948     raeburn  2634:     }
1.400     www      2635:     return %returnhash;
                   2636: }
                   2637: 
                   2638: sub get_my_roles {
1.937     raeburn  2639:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2640:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2641:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2642:     my (%dumphash,%nothide);
1.858     raeburn  2643:     if ($context eq 'userroles') { 
                   2644:         %dumphash = &dump('roles',$udom,$uname);
                   2645:     } else {
                   2646:         %dumphash=
1.400     www      2647:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2648:         if ($hidepriv) {
                   2649:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2650:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2651:                 if ($user !~ /:/) {
                   2652:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2653:                 } else {
                   2654:                     $nothide{$user} = 1;
                   2655:                 }
                   2656:             }
                   2657:         }
1.858     raeburn  2658:     }
1.400     www      2659:     my %returnhash=();
                   2660:     my $now=time;
1.800     albertel 2661:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2662:         my ($role,$tend,$tstart);
                   2663:         if ($context eq 'userroles') {
                   2664: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2665:         } else {
                   2666:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2667:         }
1.400     www      2668:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2669:         my $status = 'active';
1.939     raeburn  2670:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2671:             $status = 'previous';
                   2672:         } 
                   2673:         if (($tstart) && ($now<$tstart)) {
                   2674:             $status = 'future';
                   2675:         }
                   2676:         if (ref($types) eq 'ARRAY') {
                   2677:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2678:                 next;
                   2679:             } 
                   2680:         } else {
                   2681:             if ($status ne 'active') {
                   2682:                 next;
                   2683:             }
                   2684:         }
1.867     raeburn  2685:         my ($rolecode,$username,$domain,$section,$area);
                   2686:         if ($context eq 'userroles') {
                   2687:             ($area,$rolecode) = split(/_/,$entry);
                   2688:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2689:         } else {
                   2690:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2691:         }
1.832     raeburn  2692:         if (ref($roledoms) eq 'ARRAY') {
                   2693:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2694:                 next;
                   2695:             }
                   2696:         }
                   2697:         if (ref($roles) eq 'ARRAY') {
                   2698:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2699:                 if ($role =~ /^cr\//) {
                   2700:                     if (!grep(/^cr$/,@{$roles})) {
                   2701:                         next;
                   2702:                     }
                   2703:                 } else {
                   2704:                     next;
                   2705:                 }
1.832     raeburn  2706:             }
1.867     raeburn  2707:         }
1.937     raeburn  2708:         if ($hidepriv) {
                   2709:             if ((&privileged($username,$domain)) &&
                   2710:                 (!$nothide{$username.':'.$domain})) { 
                   2711:                 next;
                   2712:             }
                   2713:         }
1.933     raeburn  2714:         if ($withsec) {
                   2715:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2716:                 $tstart.':'.$tend;
                   2717:         } else {
                   2718:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2719:         }
1.832     raeburn  2720:     }
1.373     www      2721:     return %returnhash;
1.399     www      2722: }
                   2723: 
                   2724: # ----------------------------------------------------- Frontpage Announcements
                   2725: #
                   2726: #
                   2727: 
                   2728: sub postannounce {
                   2729:     my ($server,$text)=@_;
1.844     albertel 2730:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2731:     unless ($text=~/\w/) { $text=''; }
                   2732:     return &reply('setannounce:'.&escape($text),$server);
                   2733: }
                   2734: 
                   2735: sub getannounce {
1.448     albertel 2736: 
                   2737:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2738: 	my $announcement='';
1.800     albertel 2739: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2740: 	close($fh);
1.399     www      2741: 	if ($announcement=~/\w/) { 
                   2742: 	    return 
                   2743:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2744:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2745: 	} else {
                   2746: 	    return '';
                   2747: 	}
                   2748:     } else {
                   2749: 	return '';
                   2750:     }
1.351     www      2751: }
1.353     www      2752: 
                   2753: # ---------------------------------------------------------- Course ID routines
                   2754: # Deal with domain's nohist_courseid.db files
                   2755: #
                   2756: 
                   2757: sub courseidput {
1.921     raeburn  2758:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2759:     my $outcome;
                   2760:     if ($caller eq 'timeonly') {
                   2761:         my $cids = '';
                   2762:         foreach my $item (keys(%$storehash)) {
                   2763:             $cids.=&escape($item).'&';
                   2764:         }
                   2765:         $cids=~s/\&$//;
                   2766:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2767:                           $coursehome);       
                   2768:     } else {
                   2769:         my $items = '';
                   2770:         foreach my $item (keys(%$storehash)) {
                   2771:             $items.= &escape($item).'='.
                   2772:                      &freeze_escape($$storehash{$item}).'&';
                   2773:         }
                   2774:         $items=~s/\&$//;
                   2775:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2776:                           $coursehome);
1.918     raeburn  2777:     }
                   2778:     if ($outcome eq 'unknown_cmd') {
                   2779:         my $what;
                   2780:         foreach my $cid (keys(%$storehash)) {
                   2781:             $what .= &escape($cid).'=';
1.921     raeburn  2782:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2783:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2784:             }
                   2785:             $what =~ s/\:$/&/;
                   2786:         }
                   2787:         $what =~ s/\&$//;  
                   2788:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2789:     } else {
                   2790:         return $outcome;
                   2791:     }
1.353     www      2792: }
                   2793: 
                   2794: sub courseiddump {
1.921     raeburn  2795:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2796:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2797:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2798:     my $as_hash = 1;
                   2799:     my %returnhash;
                   2800:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2801:     my %libserv = &all_library();
                   2802:     foreach my $tryserver (keys(%libserv)) {
                   2803:         if ( (  $hostidflag == 1 
                   2804: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2805: 	     || (!defined($hostidflag)) ) {
                   2806: 
1.918     raeburn  2807: 	    if (($domfilter eq '') ||
                   2808: 		(&host_domain($tryserver) eq $domfilter)) {
                   2809:                 my $rep = 
                   2810:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2811:                          $sincefilter.':'.&escape($descfilter).':'.
                   2812:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2813:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2814:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2815:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2816:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2817:                 my @pairs=split(/\&/,$rep);
                   2818:                 foreach my $item (@pairs) {
                   2819:                     my ($key,$value)=split(/\=/,$item,2);
                   2820:                     $key = &unescape($key);
                   2821:                     next if ($key =~ /^error: 2 /);
                   2822:                     my $result = &thaw_unescape($value);
                   2823:                     if (ref($result) eq 'HASH') {
                   2824:                         $returnhash{$key}=$result;
                   2825:                     } else {
1.921     raeburn  2826:                         my @responses = split(/:/,$value);
                   2827:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2828:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2829:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2830:                         }
                   2831:                     } 
1.353     www      2832:                 }
                   2833:             }
                   2834:         }
                   2835:     }
                   2836:     return %returnhash;
                   2837: }
                   2838: 
1.658     raeburn  2839: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2840: 
                   2841: sub dcmailput {
1.685     raeburn  2842:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2843:     my $status = &Apache::lonnet::critical(
1.740     www      2844:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2845:        &escape($message),$server);
1.662     raeburn  2846:     return $status;
                   2847: }
                   2848: 
1.658     raeburn  2849: sub dcmaildump {
                   2850:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2851:     my %returnhash=();
1.846     albertel 2852: 
                   2853:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2854:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2855:                                                          &escape($enddate).':';
                   2856: 	my @esc_senders=map { &escape($_)} @$senders;
                   2857: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2858: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2859:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2860:             if (($key) && ($value)) {
                   2861:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2862:             }
                   2863:         }
                   2864:     }
                   2865:     return %returnhash;
                   2866: }
1.662     raeburn  2867: # ---------------------------------------------------------- Domain roles
                   2868: 
                   2869: sub get_domain_roles {
                   2870:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2871:     if (undef($startdate) || $startdate eq '') {
                   2872:         $startdate = '.';
                   2873:     }
                   2874:     if (undef($enddate) || $enddate eq '') {
                   2875:         $enddate = '.';
                   2876:     }
1.922     raeburn  2877:     my $rolelist;
                   2878:     if (ref($roles) eq 'ARRAY') {
                   2879:         $rolelist = join(':',@{$roles});
                   2880:     }
1.662     raeburn  2881:     my %personnel = ();
1.841     albertel 2882: 
                   2883:     my %servers = &get_servers($dom,'library');
                   2884:     foreach my $tryserver (keys(%servers)) {
                   2885: 	%{$personnel{$tryserver}}=();
                   2886: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2887: 					    &escape($startdate).':'.
                   2888: 					    &escape($enddate).':'.
                   2889: 					    &escape($rolelist), $tryserver))) {
                   2890: 	    my ($key,$value) = split(/\=/,$line,2);
                   2891: 	    if (($key) && ($value)) {
                   2892: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2893: 	    }
                   2894: 	}
1.662     raeburn  2895:     }
                   2896:     return %personnel;
                   2897: }
1.658     raeburn  2898: 
1.149     www      2899: # ----------------------------------------------------------- Check out an item
                   2900: 
1.504     albertel 2901: sub get_first_access {
                   2902:     my ($type,$argsymb)=@_;
1.790     albertel 2903:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2904:     if ($argsymb) { $symb=$argsymb; }
                   2905:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2906:     if ($type eq 'course') {
                   2907: 	$res='course';
                   2908:     } elsif ($type eq 'map') {
1.588     albertel 2909: 	$res=&symbread($map);
                   2910:     } else {
                   2911: 	$res=$symb;
                   2912:     }
                   2913:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2914:     return $times{"$courseid\0$res"};
1.504     albertel 2915: }
                   2916: 
                   2917: sub set_first_access {
                   2918:     my ($type)=@_;
1.790     albertel 2919:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2920:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2921:     if ($type eq 'course') {
                   2922: 	$res='course';
                   2923:     } elsif ($type eq 'map') {
1.588     albertel 2924: 	$res=&symbread($map);
                   2925:     } else {
                   2926: 	$res=$symb;
                   2927:     }
                   2928:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2929:     if (!$firstaccess) {
1.588     albertel 2930: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2931:     }
                   2932:     return 'already_set';
1.504     albertel 2933: }
                   2934: 
1.149     www      2935: sub checkout {
                   2936:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2937:     my $now=time;
                   2938:     my $lonhost=$perlvar{'lonHostID'};
                   2939:     my $infostr=&escape(
1.234     www      2940:                  'CHECKOUTTOKEN&'.
1.149     www      2941:                  $tuname.'&'.
                   2942:                  $tudom.'&'.
                   2943:                  $tcrsid.'&'.
                   2944:                  $symb.'&'.
                   2945: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2946:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2947:     if ($token=~/^error\:/) { 
1.672     albertel 2948:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2949:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2950:                  "</font>");
                   2951:         return ''; 
                   2952:     }
                   2953: 
1.149     www      2954:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2955:     $token=~tr/a-z/A-Z/;
                   2956: 
1.153     www      2957:     my %infohash=('resource.0.outtoken' => $token,
                   2958:                   'resource.0.checkouttime' => $now,
                   2959:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2960: 
                   2961:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2962:        return '';
1.151     www      2963:     } else {
1.672     albertel 2964:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2965:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2966:                  "</font>");
1.149     www      2967:     }    
                   2968: 
                   2969:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2970:                          &escape('Checkout '.$infostr.' - '.
                   2971:                                                  $token)) ne 'ok') {
                   2972: 	return '';
1.151     www      2973:     } else {
1.672     albertel 2974:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2975:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2976:                  "</font>");
1.149     www      2977:     }
1.151     www      2978:     return $token;
1.149     www      2979: }
                   2980: 
                   2981: # ------------------------------------------------------------ Check in an item
                   2982: 
                   2983: sub checkin {
                   2984:     my $token=shift;
1.150     www      2985:     my $now=time;
                   2986:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2987:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2988:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2989:     $dtoken=~s/\W/\_/g;
1.234     www      2990:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2991:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2992: 
1.154     www      2993:     unless (($tuname) && ($tudom)) {
                   2994:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2995:         return '';
                   2996:     }
                   2997:     
                   2998:     unless (&allowed('mgr',$tcrsid)) {
                   2999:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3000:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3001:         return '';
                   3002:     }
                   3003: 
1.153     www      3004:     my %infohash=('resource.0.intoken' => $token,
                   3005:                   'resource.0.checkintime' => $now,
                   3006:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3007: 
                   3008:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3009:        return '';
                   3010:     }    
                   3011: 
                   3012:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3013:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3014: 	return '';
                   3015:     }
                   3016: 
                   3017:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3018: }
                   3019: 
                   3020: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3021: 
                   3022: sub expirespread {
                   3023:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3024:     my $cid=$env{'request.course.id'}; 
1.110     www      3025:     if ($cid) {
                   3026:        my $now=time;
                   3027:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3028:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3029:                             $env{'course.'.$cid.'.num'}.
1.110     www      3030: 	        	    ':nohist_expirationdates:'.
                   3031:                             &escape($key).'='.$now,
1.620     albertel 3032:                             $env{'course.'.$cid.'.home'})
1.110     www      3033:     }
                   3034:     return 'ok';
1.14      www      3035: }
                   3036: 
1.109     www      3037: # ----------------------------------------------------- Devalidate Spreadsheets
                   3038: 
                   3039: sub devalidate {
1.325     www      3040:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3041:     my $cid=$env{'request.course.id'}; 
1.109     www      3042:     if ($cid) {
1.391     matthew  3043:         # delete the stored spreadsheets for
                   3044:         # - the student level sheet of this user in course's homespace
                   3045:         # - the assessment level sheet for this resource 
                   3046:         #   for this user in user's homespace
1.553     albertel 3047: 	# - current conditional state info
1.325     www      3048: 	my $key=$uname.':'.$udom.':';
1.109     www      3049:         my $status=
1.299     matthew  3050: 	    &del('nohist_calculatedsheets',
1.391     matthew  3051: 		 [$key.'studentcalc:'],
1.620     albertel 3052: 		 $env{'course.'.$cid.'.domain'},
                   3053: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3054: 		.' '.
                   3055: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3056: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3057:         unless ($status eq 'ok ok') {
                   3058:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3059:                     $uname.' at '.$udom.' for '.
1.109     www      3060: 		    $symb.': '.$status);
1.133     albertel 3061:         }
1.553     albertel 3062: 	&delenv('user.state.'.$cid);
1.109     www      3063:     }
                   3064: }
                   3065: 
1.265     albertel 3066: sub get_scalar {
                   3067:     my ($string,$end) = @_;
                   3068:     my $value;
                   3069:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3070: 	$value = $1;
                   3071:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3072: 	$value = $1;
                   3073:     }
                   3074:     return &unescape($value);
                   3075: }
                   3076: 
                   3077: sub array2str {
                   3078:   my (@array) = @_;
                   3079:   my $result=&arrayref2str(\@array);
                   3080:   $result=~s/^__ARRAY_REF__//;
                   3081:   $result=~s/__END_ARRAY_REF__$//;
                   3082:   return $result;
                   3083: }
                   3084: 
1.204     albertel 3085: sub arrayref2str {
                   3086:   my ($arrayref) = @_;
1.265     albertel 3087:   my $result='__ARRAY_REF__';
1.204     albertel 3088:   foreach my $elem (@$arrayref) {
1.265     albertel 3089:     if(ref($elem) eq 'ARRAY') {
                   3090:       $result.=&arrayref2str($elem).'&';
                   3091:     } elsif(ref($elem) eq 'HASH') {
                   3092:       $result.=&hashref2str($elem).'&';
                   3093:     } elsif(ref($elem)) {
                   3094:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3095:     } else {
                   3096:       $result.=&escape($elem).'&';
                   3097:     }
                   3098:   }
                   3099:   $result=~s/\&$//;
1.265     albertel 3100:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3101:   return $result;
                   3102: }
                   3103: 
1.168     albertel 3104: sub hash2str {
1.204     albertel 3105:   my (%hash) = @_;
                   3106:   my $result=&hashref2str(\%hash);
1.265     albertel 3107:   $result=~s/^__HASH_REF__//;
                   3108:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3109:   return $result;
                   3110: }
                   3111: 
                   3112: sub hashref2str {
                   3113:   my ($hashref)=@_;
1.265     albertel 3114:   my $result='__HASH_REF__';
1.800     albertel 3115:   foreach my $key (sort(keys(%$hashref))) {
                   3116:     if (ref($key) eq 'ARRAY') {
                   3117:       $result.=&arrayref2str($key).'=';
                   3118:     } elsif (ref($key) eq 'HASH') {
                   3119:       $result.=&hashref2str($key).'=';
                   3120:     } elsif (ref($key)) {
1.265     albertel 3121:       $result.='=';
1.800     albertel 3122:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3123:     } else {
1.800     albertel 3124: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3125:     }
                   3126: 
1.800     albertel 3127:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3128:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3129:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3130:       $result.=&hashref2str($hashref->{$key}).'&';
                   3131:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3132:        $result.='&';
1.800     albertel 3133:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3134:     } else {
1.800     albertel 3135:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3136:     }
                   3137:   }
1.168     albertel 3138:   $result=~s/\&$//;
1.265     albertel 3139:   $result .= '__END_HASH_REF__';
1.168     albertel 3140:   return $result;
                   3141: }
                   3142: 
                   3143: sub str2hash {
1.265     albertel 3144:     my ($string)=@_;
                   3145:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3146:     return %$hash;
                   3147: }
                   3148: 
                   3149: sub str2hashref {
1.168     albertel 3150:   my ($string) = @_;
1.265     albertel 3151: 
                   3152:   my %hash;
                   3153: 
                   3154:   if($string !~ /^__HASH_REF__/) {
                   3155:       if (! ($string eq '' || !defined($string))) {
                   3156: 	  $hash{'error'}='Not hash reference';
                   3157:       }
                   3158:       return (\%hash, $string);
                   3159:   }
                   3160: 
                   3161:   $string =~ s/^__HASH_REF__//;
                   3162: 
                   3163:   while($string !~ /^__END_HASH_REF__/) {
                   3164:       #key
                   3165:       my $key='';
                   3166:       if($string =~ /^__HASH_REF__/) {
                   3167:           ($key, $string)=&str2hashref($string);
                   3168:           if(defined($key->{'error'})) {
                   3169:               $hash{'error'}='Bad data';
                   3170:               return (\%hash, $string);
                   3171:           }
                   3172:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3173:           ($key, $string)=&str2arrayref($string);
                   3174:           if($key->[0] eq 'Array reference error') {
                   3175:               $hash{'error'}='Bad data';
                   3176:               return (\%hash, $string);
                   3177:           }
                   3178:       } else {
                   3179:           $string =~ s/^(.*?)=//;
1.267     albertel 3180: 	  $key=&unescape($1);
1.265     albertel 3181:       }
                   3182:       $string =~ s/^=//;
                   3183: 
                   3184:       #value
                   3185:       my $value='';
                   3186:       if($string =~ /^__HASH_REF__/) {
                   3187:           ($value, $string)=&str2hashref($string);
                   3188:           if(defined($value->{'error'})) {
                   3189:               $hash{'error'}='Bad data';
                   3190:               return (\%hash, $string);
                   3191:           }
                   3192:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3193:           ($value, $string)=&str2arrayref($string);
                   3194:           if($value->[0] eq 'Array reference error') {
                   3195:               $hash{'error'}='Bad data';
                   3196:               return (\%hash, $string);
                   3197:           }
                   3198:       } else {
                   3199: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3200:       }
                   3201:       $string =~ s/^&//;
                   3202: 
                   3203:       $hash{$key}=$value;
1.204     albertel 3204:   }
1.265     albertel 3205: 
                   3206:   $string =~ s/^__END_HASH_REF__//;
                   3207: 
                   3208:   return (\%hash, $string);
1.204     albertel 3209: }
                   3210: 
                   3211: sub str2array {
1.265     albertel 3212:     my ($string)=@_;
                   3213:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3214:     return @$array;
                   3215: }
                   3216: 
                   3217: sub str2arrayref {
1.204     albertel 3218:   my ($string) = @_;
1.265     albertel 3219:   my @array;
                   3220: 
                   3221:   if($string !~ /^__ARRAY_REF__/) {
                   3222:       if (! ($string eq '' || !defined($string))) {
                   3223: 	  $array[0]='Array reference error';
                   3224:       }
                   3225:       return (\@array, $string);
                   3226:   }
                   3227: 
                   3228:   $string =~ s/^__ARRAY_REF__//;
                   3229: 
                   3230:   while($string !~ /^__END_ARRAY_REF__/) {
                   3231:       my $value='';
                   3232:       if($string =~ /^__HASH_REF__/) {
                   3233:           ($value, $string)=&str2hashref($string);
                   3234:           if(defined($value->{'error'})) {
                   3235:               $array[0] ='Array reference error';
                   3236:               return (\@array, $string);
                   3237:           }
                   3238:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3239:           ($value, $string)=&str2arrayref($string);
                   3240:           if($value->[0] eq 'Array reference error') {
                   3241:               $array[0] ='Array reference error';
                   3242:               return (\@array, $string);
                   3243:           }
                   3244:       } else {
                   3245: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3246:       }
                   3247:       $string =~ s/^&//;
                   3248: 
                   3249:       push(@array, $value);
1.191     harris41 3250:   }
1.265     albertel 3251: 
                   3252:   $string =~ s/^__END_ARRAY_REF__//;
                   3253: 
                   3254:   return (\@array, $string);
1.168     albertel 3255: }
                   3256: 
1.167     albertel 3257: # -------------------------------------------------------------------Temp Store
                   3258: 
1.168     albertel 3259: sub tmpreset {
                   3260:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3261:   if (!$symb) {
                   3262:     $symb=&symbread();
1.620     albertel 3263:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3264:   }
                   3265:   $symb=escape($symb);
                   3266: 
1.620     albertel 3267:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3268:   $namespace=~s/\//\_/g;
                   3269:   $namespace=~s/\W//g;
                   3270: 
1.620     albertel 3271:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3272:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3273:   if ($domain eq 'public' && $stuname eq 'public') {
                   3274:       $stuname=$ENV{'REMOTE_ADDR'};
                   3275:   }
1.168     albertel 3276:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3277:   my %hash;
                   3278:   if (tie(%hash,'GDBM_File',
                   3279: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3280: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3281:     foreach my $key (keys %hash) {
1.180     albertel 3282:       if ($key=~ /:$symb/) {
1.168     albertel 3283: 	delete($hash{$key});
                   3284:       }
                   3285:     }
                   3286:   }
                   3287: }
                   3288: 
1.167     albertel 3289: sub tmpstore {
1.168     albertel 3290:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3291: 
                   3292:   if (!$symb) {
                   3293:     $symb=&symbread();
1.620     albertel 3294:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3295:   }
                   3296:   $symb=escape($symb);
                   3297: 
                   3298:   if (!$namespace) {
                   3299:     # I don't think we would ever want to store this for a course.
                   3300:     # it seems this will only be used if we don't have a course.
1.620     albertel 3301:     #$namespace=$env{'request.course.id'};
1.168     albertel 3302:     #if (!$namespace) {
1.620     albertel 3303:       $namespace=$env{'request.state'};
1.168     albertel 3304:     #}
                   3305:   }
                   3306:   $namespace=~s/\//\_/g;
                   3307:   $namespace=~s/\W//g;
1.620     albertel 3308:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3309:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3310:   if ($domain eq 'public' && $stuname eq 'public') {
                   3311:       $stuname=$ENV{'REMOTE_ADDR'};
                   3312:   }
1.168     albertel 3313:   my $now=time;
                   3314:   my %hash;
                   3315:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3316:   if (tie(%hash,'GDBM_File',
                   3317: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3318: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3319:     $hash{"version:$symb"}++;
                   3320:     my $version=$hash{"version:$symb"};
                   3321:     my $allkeys=''; 
                   3322:     foreach my $key (keys(%$storehash)) {
                   3323:       $allkeys.=$key.':';
1.591     albertel 3324:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3325:     }
                   3326:     $hash{"$version:$symb:timestamp"}=$now;
                   3327:     $allkeys.='timestamp';
                   3328:     $hash{"$version:keys:$symb"}=$allkeys;
                   3329:     if (untie(%hash)) {
                   3330:       return 'ok';
                   3331:     } else {
                   3332:       return "error:$!";
                   3333:     }
                   3334:   } else {
                   3335:     return "error:$!";
                   3336:   }
                   3337: }
1.167     albertel 3338: 
1.168     albertel 3339: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3340: 
1.168     albertel 3341: sub tmprestore {
                   3342:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3343: 
1.168     albertel 3344:   if (!$symb) {
                   3345:     $symb=&symbread();
1.620     albertel 3346:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3347:   }
                   3348:   $symb=escape($symb);
                   3349: 
1.620     albertel 3350:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3351: 
1.620     albertel 3352:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3353:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3354:   if ($domain eq 'public' && $stuname eq 'public') {
                   3355:       $stuname=$ENV{'REMOTE_ADDR'};
                   3356:   }
1.168     albertel 3357:   my %returnhash;
                   3358:   $namespace=~s/\//\_/g;
                   3359:   $namespace=~s/\W//g;
                   3360:   my %hash;
                   3361:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3362:   if (tie(%hash,'GDBM_File',
                   3363: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3364: 	  &GDBM_READER(),0640)) {
1.168     albertel 3365:     my $version=$hash{"version:$symb"};
                   3366:     $returnhash{'version'}=$version;
                   3367:     my $scope;
                   3368:     for ($scope=1;$scope<=$version;$scope++) {
                   3369:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3370:       my @keys=split(/:/,$vkeys);
                   3371:       my $key;
                   3372:       $returnhash{"$scope:keys"}=$vkeys;
                   3373:       foreach $key (@keys) {
1.591     albertel 3374: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3375: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3376:       }
                   3377:     }
1.168     albertel 3378:     if (!(untie(%hash))) {
                   3379:       return "error:$!";
                   3380:     }
                   3381:   } else {
                   3382:     return "error:$!";
                   3383:   }
                   3384:   return %returnhash;
1.167     albertel 3385: }
                   3386: 
1.9       www      3387: # ----------------------------------------------------------------------- Store
                   3388: 
                   3389: sub store {
1.124     www      3390:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3391:     my $home='';
                   3392: 
1.168     albertel 3393:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3394: 
1.213     www      3395:     $symb=&symbclean($symb);
1.122     albertel 3396:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3397: 
1.620     albertel 3398:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3399:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3400: 
                   3401:     &devalidate($symb,$stuname,$domain);
1.109     www      3402: 
                   3403:     $symb=escape($symb);
1.187     www      3404:     if (!$namespace) { 
1.620     albertel 3405:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3406:           return ''; 
                   3407:        } 
                   3408:     }
1.620     albertel 3409:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3410: 
                   3411:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3412:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3413: 
1.12      www      3414:     my $namevalue='';
1.800     albertel 3415:     foreach my $key (keys(%$storehash)) {
                   3416:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3417:     }
1.12      www      3418:     $namevalue=~s/\&$//;
1.187     www      3419:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3420:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3421: }
                   3422: 
1.47      www      3423: # -------------------------------------------------------------- Critical Store
                   3424: 
                   3425: sub cstore {
1.124     www      3426:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3427:     my $home='';
                   3428: 
1.168     albertel 3429:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3430: 
1.213     www      3431:     $symb=&symbclean($symb);
1.122     albertel 3432:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3433: 
1.620     albertel 3434:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3435:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3436: 
                   3437:     &devalidate($symb,$stuname,$domain);
1.109     www      3438: 
                   3439:     $symb=escape($symb);
1.187     www      3440:     if (!$namespace) { 
1.620     albertel 3441:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3442:           return ''; 
                   3443:        } 
                   3444:     }
1.620     albertel 3445:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3446: 
                   3447:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3448:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3449: 
1.47      www      3450:     my $namevalue='';
1.800     albertel 3451:     foreach my $key (keys(%$storehash)) {
                   3452:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3453:     }
1.47      www      3454:     $namevalue=~s/\&$//;
1.187     www      3455:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3456:     return critical
                   3457:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3458: }
                   3459: 
1.9       www      3460: # --------------------------------------------------------------------- Restore
                   3461: 
                   3462: sub restore {
1.124     www      3463:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3464:     my $home='';
                   3465: 
1.168     albertel 3466:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3467: 
1.122     albertel 3468:     if (!$symb) {
                   3469:       unless ($symb=escape(&symbread())) { return ''; }
                   3470:     } else {
1.213     www      3471:       $symb=&escape(&symbclean($symb));
1.122     albertel 3472:     }
1.188     www      3473:     if (!$namespace) { 
1.620     albertel 3474:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3475:           return ''; 
                   3476:        } 
                   3477:     }
1.620     albertel 3478:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3479:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3480:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3481:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3482: 
1.12      www      3483:     my %returnhash=();
1.800     albertel 3484:     foreach my $line (split(/\&/,$answer)) {
                   3485: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3486:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3487:     }
1.75      www      3488:     my $version;
                   3489:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3490:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3491:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3492:        }
1.75      www      3493:     }
1.13      www      3494:     return %returnhash;
1.34      www      3495: }
                   3496: 
                   3497: # ---------------------------------------------------------- Course Description
                   3498: 
                   3499: sub coursedescription {
1.731     albertel 3500:     my ($courseid,$args)=@_;
1.34      www      3501:     $courseid=~s/^\///;
1.49      www      3502:     $courseid=~s/\_/\//g;
1.34      www      3503:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3504:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3505:     my $normalid=$cdomain.'_'.$cnum;
                   3506:     # need to always cache even if we get errors otherwise we keep 
                   3507:     # trying and trying and trying to get the course description.
                   3508:     my %envhash=();
                   3509:     my %returnhash=();
1.731     albertel 3510:     
                   3511:     my $expiretime=600;
                   3512:     if ($env{'request.course.id'} eq $normalid) {
                   3513: 	$expiretime=120;
                   3514:     }
                   3515: 
                   3516:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3517:     if (!$args->{'freshen_cache'}
                   3518: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3519: 	foreach my $key (keys(%env)) {
                   3520: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3521: 	    my ($setting) = $1;
                   3522: 	    $returnhash{$setting} = $env{$key};
                   3523: 	}
                   3524: 	return %returnhash;
                   3525:     }
                   3526: 
                   3527:     # get the data agin
                   3528:     if (!$args->{'one_time'}) {
                   3529: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3530:     }
1.811     albertel 3531: 
1.34      www      3532:     if ($chome ne 'no_host') {
1.302     albertel 3533:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3534:        if (!exists($returnhash{'con_lost'})) {
                   3535:            $returnhash{'home'}= $chome;
                   3536: 	   $returnhash{'domain'} = $cdomain;
                   3537: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3538:            if (!defined($returnhash{'type'})) {
                   3539:                $returnhash{'type'} = 'Course';
                   3540:            }
1.130     albertel 3541:            while (my ($name,$value) = each %returnhash) {
1.53      www      3542:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3543:            }
1.270     www      3544:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3545:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3546: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3547:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3548:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3549:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3550:        }
                   3551:     }
1.731     albertel 3552:     if (!$args->{'one_time'}) {
1.949     raeburn  3553: 	&appenv(\%envhash);
1.731     albertel 3554:     }
1.302     albertel 3555:     return %returnhash;
1.461     www      3556: }
                   3557: 
                   3558: # -------------------------------------------------See if a user is privileged
                   3559: 
                   3560: sub privileged {
                   3561:     my ($username,$domain)=@_;
                   3562:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3563: 			&homeserver($username,$domain));
                   3564:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3565:     my $now=time;
                   3566:     if ($rolesdump ne '') {
1.800     albertel 3567:         foreach my $entry (split(/&/,$rolesdump)) {
                   3568: 	    if ($entry!~/^rolesdef_/) {
                   3569: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3570: 		$area=~s/\_\w\w$//;
                   3571: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3572: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3573: 		    my $active=1;
                   3574: 		    if ($tend) {
                   3575: 			if ($tend<$now) { $active=0; }
                   3576: 		    }
                   3577: 		    if ($tstart) {
                   3578: 			if ($tstart>$now) { $active=0; }
                   3579: 		    }
                   3580: 		    if ($active) { return 1; }
                   3581: 		}
                   3582: 	    }
                   3583: 	}
                   3584:     }
                   3585:     return 0;
1.9       www      3586: }
1.1       albertel 3587: 
1.103     harris41 3588: # -------------------------------------------------------- Get user privileges
1.11      www      3589: 
                   3590: sub rolesinit {
                   3591:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3592:     my %userroles;
1.11      www      3593:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3594:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3595:     my %allroles=();
1.678     raeburn  3596:     my %allgroups=();   
1.11      www      3597:     my $now=time;
1.966     raeburn  3598:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3599:     my $group_privs;
1.11      www      3600: 
                   3601:     if ($rolesdump ne '') {
1.800     albertel 3602:         foreach my $entry (split(/&/,$rolesdump)) {
                   3603: 	  if ($entry!~/^rolesdef_/) {
                   3604:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3605: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3606:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3607: 	    if ($role=~/^cr/) { 
1.807     albertel 3608: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3609: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3610: 		    ($tend,$tstart)=split('_',$trest);
                   3611: 		} else {
                   3612: 		    $trole=$role;
                   3613: 		}
1.678     raeburn  3614:             } elsif ($role =~ m|^gr/|) {
                   3615:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3616:                 ($trole,$group_privs) = split(/\//,$trole);
                   3617:                 $group_privs = &unescape($group_privs);
1.587     albertel 3618: 	    } else {
                   3619: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3620: 	    }
1.743     albertel 3621: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3622: 					 $username);
                   3623: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3624:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3625:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3626:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3627: 		my $spec=$trole.'.'.$area;
                   3628: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3629: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3630:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3631:                 } elsif ($trole eq 'gr') {
                   3632:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3633: 		} else {
1.567     raeburn  3634:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3635: 		}
1.12      www      3636:             }
1.662     raeburn  3637:           }
1.191     harris41 3638:         }
1.743     albertel 3639:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3640:         $userroles{'user.adv'}    = $adv;
                   3641: 	$userroles{'user.author'} = $author;
1.620     albertel 3642:         $env{'user.adv'}=$adv;
1.11      www      3643:     }
1.743     albertel 3644:     return \%userroles;  
1.11      www      3645: }
                   3646: 
1.567     raeburn  3647: sub set_arearole {
                   3648:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3649: # log the associated role with the area
                   3650:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3651:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3652: }
                   3653: 
                   3654: sub custom_roleprivs {
                   3655:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3656:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3657:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3658:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3659:         my ($rdummy,$roledef)=
                   3660:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3661:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3662:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3663:             if (defined($syspriv)) {
                   3664:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3665:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3666:             }
                   3667:             if ($tdomain ne '') {
                   3668:                 if (defined($dompriv)) {
                   3669:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3670:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3671:                 }
                   3672:                 if (($trest ne '') && (defined($coursepriv))) {
                   3673:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3674:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3675:                 }
                   3676:             }
                   3677:         }
                   3678:     }
                   3679: }
                   3680: 
1.678     raeburn  3681: sub group_roleprivs {
                   3682:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3683:     my $access = 1;
                   3684:     my $now = time;
                   3685:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3686:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3687:     if ($access) {
1.811     albertel 3688:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3689:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3690:     }
                   3691: }
1.567     raeburn  3692: 
                   3693: sub standard_roleprivs {
                   3694:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3695:     if (defined($pr{$trole.':s'})) {
                   3696:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3697:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3698:     }
                   3699:     if ($tdomain ne '') {
                   3700:         if (defined($pr{$trole.':d'})) {
                   3701:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3702:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3703:         }
                   3704:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3705:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3706:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3707:         }
                   3708:     }
                   3709: }
                   3710: 
                   3711: sub set_userprivs {
1.678     raeburn  3712:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3713:     my $author=0;
                   3714:     my $adv=0;
1.678     raeburn  3715:     my %grouproles = ();
                   3716:     if (keys(%{$allgroups}) > 0) {
                   3717:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3718:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3719:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3720:                 $trole = $1;
                   3721:                 $area = $2;
1.681     raeburn  3722:                 $sec = $3;
                   3723:                 $extendedarea = $area.$sec;
                   3724:                 if (exists($$allgroups{$area})) {
                   3725:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3726:                         my $spec = $trole.'.'.$extendedarea;
                   3727:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3728:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3729:                     }
                   3730:                 }
                   3731:             }
                   3732:         }
                   3733:     }
1.800     albertel 3734:     foreach my $group (keys(%grouproles)) {
                   3735:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3736:     }
1.800     albertel 3737:     foreach my $role (keys(%{$allroles})) {
                   3738:         my %thesepriv;
1.941     raeburn  3739:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3740:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3741:             if ($item ne '') {
                   3742:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3743:                 if ($restrictions eq '') {
                   3744:                     $thesepriv{$privilege}='F';
                   3745:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3746:                     $thesepriv{$privilege}.=$restrictions;
                   3747:                 }
                   3748:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3749:             }
                   3750:         }
                   3751:         my $thesestr='';
1.800     albertel 3752:         foreach my $priv (keys(%thesepriv)) {
                   3753: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3754: 	}
                   3755:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3756:     }
                   3757:     return ($author,$adv);
                   3758: }
                   3759: 
1.12      www      3760: # --------------------------------------------------------------- get interface
                   3761: 
                   3762: sub get {
1.131     albertel 3763:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3764:    my $items='';
1.800     albertel 3765:    foreach my $item (@$storearr) {
                   3766:        $items.=&escape($item).'&';
1.191     harris41 3767:    }
1.12      www      3768:    $items=~s/\&$//;
1.620     albertel 3769:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3770:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3771:    my $uhome=&homeserver($uname,$udomain);
                   3772: 
1.133     albertel 3773:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3774:    my @pairs=split(/\&/,$rep);
1.273     albertel 3775:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3776:      return @pairs;
                   3777:    }
1.15      www      3778:    my %returnhash=();
1.42      www      3779:    my $i=0;
1.800     albertel 3780:    foreach my $item (@$storearr) {
                   3781:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3782:       $i++;
1.191     harris41 3783:    }
1.15      www      3784:    return %returnhash;
1.27      www      3785: }
                   3786: 
                   3787: # --------------------------------------------------------------- del interface
                   3788: 
                   3789: sub del {
1.133     albertel 3790:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3791:    my $items='';
1.800     albertel 3792:    foreach my $item (@$storearr) {
                   3793:        $items.=&escape($item).'&';
1.191     harris41 3794:    }
1.27      www      3795:    $items=~s/\&$//;
1.620     albertel 3796:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3797:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3798:    my $uhome=&homeserver($uname,$udomain);
                   3799: 
                   3800:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3801: }
                   3802: 
                   3803: # -------------------------------------------------------------- dump interface
                   3804: 
                   3805: sub dump {
1.755     albertel 3806:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3807:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3808:     if (!$uname) { $uname=$env{'user.name'}; }
                   3809:     my $uhome=&homeserver($uname,$udomain);
                   3810:     if ($regexp) {
                   3811: 	$regexp=&escape($regexp);
                   3812:     } else {
                   3813: 	$regexp='.';
                   3814:     }
                   3815:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3816:     my @pairs=split(/\&/,$rep);
                   3817:     my %returnhash=();
                   3818:     foreach my $item (@pairs) {
                   3819: 	my ($key,$value)=split(/=/,$item,2);
                   3820: 	$key = &unescape($key);
                   3821: 	next if ($key =~ /^error: 2 /);
                   3822: 	$returnhash{$key}=&thaw_unescape($value);
                   3823:     }
                   3824:     return %returnhash;
1.407     www      3825: }
                   3826: 
1.717     albertel 3827: # --------------------------------------------------------- dumpstore interface
                   3828: 
                   3829: sub dumpstore {
                   3830:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3831:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3832:    if (!$uname) { $uname=$env{'user.name'}; }
                   3833:    my $uhome=&homeserver($uname,$udomain);
                   3834:    if ($regexp) {
                   3835:        $regexp=&escape($regexp);
                   3836:    } else {
                   3837:        $regexp='.';
                   3838:    }
                   3839:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3840:    my @pairs=split(/\&/,$rep);
                   3841:    my %returnhash=();
                   3842:    foreach my $item (@pairs) {
                   3843:        my ($key,$value)=split(/=/,$item,2);
                   3844:        next if ($key =~ /^error: 2 /);
                   3845:        $returnhash{$key}=&thaw_unescape($value);
                   3846:    }
                   3847:    return %returnhash;
1.717     albertel 3848: }
                   3849: 
1.407     www      3850: # -------------------------------------------------------------- keys interface
                   3851: 
                   3852: sub getkeys {
                   3853:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3855:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3856:    my $uhome=&homeserver($uname,$udomain);
                   3857:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3858:    my @keyarray=();
1.800     albertel 3859:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3860:       next if ($key =~ /^error: 2 /);
1.800     albertel 3861:       push(@keyarray,&unescape($key));
1.407     www      3862:    }
                   3863:    return @keyarray;
1.318     matthew  3864: }
                   3865: 
1.319     matthew  3866: # --------------------------------------------------------------- currentdump
                   3867: sub currentdump {
1.328     matthew  3868:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3869:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3870:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3871:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3872:    my $uhome = &homeserver($sname,$sdom);
                   3873:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3874:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3875:    #
1.318     matthew  3876:    my %returnhash=();
1.319     matthew  3877:    #
                   3878:    if ($rep eq "unknown_cmd") { 
                   3879:        # an old lond will not know currentdump
                   3880:        # Do a dump and make it look like a currentdump
1.822     albertel 3881:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3882:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3883:        my %hash = @tmp;
                   3884:        @tmp=();
1.424     matthew  3885:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3886:    } else {
                   3887:        my @pairs=split(/\&/,$rep);
1.800     albertel 3888:        foreach my $pair (@pairs) {
                   3889:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3890:            my ($symb,$param) = split(/:/,$key);
                   3891:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3892:                                                         &thaw_unescape($value);
1.319     matthew  3893:        }
1.191     harris41 3894:    }
1.12      www      3895:    return %returnhash;
1.424     matthew  3896: }
                   3897: 
                   3898: sub convert_dump_to_currentdump{
                   3899:     my %hash = %{shift()};
                   3900:     my %returnhash;
                   3901:     # Code ripped from lond, essentially.  The only difference
                   3902:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3903:     # we might run in to problems with parameter names =~ /^v\./
                   3904:     while (my ($key,$value) = each(%hash)) {
                   3905:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3906: 	$symb  = &unescape($symb);
                   3907: 	$param = &unescape($param);
1.424     matthew  3908:         next if ($v eq 'version' || $symb eq 'keys');
                   3909:         next if (exists($returnhash{$symb}) &&
                   3910:                  exists($returnhash{$symb}->{$param}) &&
                   3911:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3912:         $returnhash{$symb}->{$param}=$value;
                   3913:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3914:     }
                   3915:     #
                   3916:     # Remove all of the keys in the hashes which keep track of
                   3917:     # the version of the parameter.
                   3918:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3919:         # use a foreach because we are going to delete from the hash.
                   3920:         foreach my $key (keys(%$param_hash)) {
                   3921:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3922:         }
                   3923:     }
                   3924:     return \%returnhash;
1.12      www      3925: }
                   3926: 
1.627     albertel 3927: # ------------------------------------------------------ critical inc interface
                   3928: 
                   3929: sub cinc {
                   3930:     return &inc(@_,'critical');
                   3931: }
                   3932: 
1.449     matthew  3933: # --------------------------------------------------------------- inc interface
                   3934: 
                   3935: sub inc {
1.627     albertel 3936:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3937:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3938:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3939:     my $uhome=&homeserver($uname,$udomain);
                   3940:     my $items='';
                   3941:     if (! ref($store)) {
                   3942:         # got a single value, so use that instead
                   3943:         $items = &escape($store).'=&';
                   3944:     } elsif (ref($store) eq 'SCALAR') {
                   3945:         $items = &escape($$store).'=&';        
                   3946:     } elsif (ref($store) eq 'ARRAY') {
                   3947:         $items = join('=&',map {&escape($_);} @{$store});
                   3948:     } elsif (ref($store) eq 'HASH') {
                   3949:         while (my($key,$value) = each(%{$store})) {
                   3950:             $items.= &escape($key).'='.&escape($value).'&';
                   3951:         }
                   3952:     }
                   3953:     $items=~s/\&$//;
1.627     albertel 3954:     if ($critical) {
                   3955: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3956:     } else {
                   3957: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3958:     }
1.449     matthew  3959: }
                   3960: 
1.12      www      3961: # --------------------------------------------------------------- put interface
                   3962: 
                   3963: sub put {
1.134     albertel 3964:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3965:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3966:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3967:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3968:    my $items='';
1.800     albertel 3969:    foreach my $item (keys(%$storehash)) {
                   3970:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3971:    }
1.12      www      3972:    $items=~s/\&$//;
1.134     albertel 3973:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3974: }
                   3975: 
1.631     albertel 3976: # ------------------------------------------------------------ newput interface
                   3977: 
                   3978: sub newput {
                   3979:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3980:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3981:    if (!$uname) { $uname=$env{'user.name'}; }
                   3982:    my $uhome=&homeserver($uname,$udomain);
                   3983:    my $items='';
                   3984:    foreach my $key (keys(%$storehash)) {
                   3985:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3986:    }
                   3987:    $items=~s/\&$//;
                   3988:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3989: }
                   3990: 
                   3991: # ---------------------------------------------------------  putstore interface
                   3992: 
1.524     raeburn  3993: sub putstore {
1.715     albertel 3994:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3995:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3996:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3997:    my $uhome=&homeserver($uname,$udomain);
                   3998:    my $items='';
1.715     albertel 3999:    foreach my $key (keys(%$storehash)) {
                   4000:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4001:    }
1.715     albertel 4002:    $items=~s/\&$//;
1.716     albertel 4003:    my $esc_symb=&escape($symb);
                   4004:    my $esc_v=&escape($version);
1.715     albertel 4005:    my $reply =
1.716     albertel 4006:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4007: 	      $uhome);
                   4008:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4009:        # gfall back to way things use to be done
1.715     albertel 4010:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4011: 			    $uname);
1.524     raeburn  4012:    }
1.715     albertel 4013:    return $reply;
                   4014: }
                   4015: 
                   4016: sub old_putstore {
1.716     albertel 4017:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4018:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4019:     if (!$uname) { $uname=$env{'user.name'}; }
                   4020:     my $uhome=&homeserver($uname,$udomain);
                   4021:     my %newstorehash;
1.800     albertel 4022:     foreach my $item (keys(%$storehash)) {
                   4023: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4024: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4025:     }
                   4026:     my $items='';
                   4027:     my %allitems = ();
1.800     albertel 4028:     foreach my $item (keys(%newstorehash)) {
                   4029: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4030: 	    my $key = $1.':keys:'.$2;
                   4031: 	    $allitems{$key} .= $3.':';
                   4032: 	}
1.800     albertel 4033: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4034:     }
1.800     albertel 4035:     foreach my $item (keys(%allitems)) {
                   4036: 	$allitems{$item} =~ s/\:$//;
                   4037: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4038:     }
                   4039:     $items=~s/\&$//;
                   4040:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4041: }
                   4042: 
1.47      www      4043: # ------------------------------------------------------ critical put interface
                   4044: 
                   4045: sub cput {
1.134     albertel 4046:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4047:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4048:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4049:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4050:    my $items='';
1.800     albertel 4051:    foreach my $item (keys(%$storehash)) {
                   4052:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4053:    }
1.47      www      4054:    $items=~s/\&$//;
1.134     albertel 4055:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4056: }
                   4057: 
                   4058: # -------------------------------------------------------------- eget interface
                   4059: 
                   4060: sub eget {
1.133     albertel 4061:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4062:    my $items='';
1.800     albertel 4063:    foreach my $item (@$storearr) {
                   4064:        $items.=&escape($item).'&';
1.191     harris41 4065:    }
1.12      www      4066:    $items=~s/\&$//;
1.620     albertel 4067:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4068:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4069:    my $uhome=&homeserver($uname,$udomain);
                   4070:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4071:    my @pairs=split(/\&/,$rep);
                   4072:    my %returnhash=();
1.42      www      4073:    my $i=0;
1.800     albertel 4074:    foreach my $item (@$storearr) {
                   4075:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4076:       $i++;
1.191     harris41 4077:    }
1.12      www      4078:    return %returnhash;
                   4079: }
                   4080: 
1.667     albertel 4081: # ------------------------------------------------------------ tmpput interface
                   4082: sub tmpput {
1.802     raeburn  4083:     my ($storehash,$server,$context)=@_;
1.667     albertel 4084:     my $items='';
1.800     albertel 4085:     foreach my $item (keys(%$storehash)) {
                   4086: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4087:     }
                   4088:     $items=~s/\&$//;
1.802     raeburn  4089:     if (defined($context)) {
                   4090:         $items .= ':'.&escape($context);
                   4091:     }
1.667     albertel 4092:     return &reply("tmpput:$items",$server);
                   4093: }
                   4094: 
                   4095: # ------------------------------------------------------------ tmpget interface
                   4096: sub tmpget {
1.688     albertel 4097:     my ($token,$server)=@_;
                   4098:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4099:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4100:     my %returnhash;
                   4101:     foreach my $item (split(/\&/,$rep)) {
                   4102: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4103:         next if ($key =~ /^error: 2 /);
1.667     albertel 4104: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4105:     }
                   4106:     return %returnhash;
                   4107: }
                   4108: 
1.688     albertel 4109: # ------------------------------------------------------------ tmpget interface
                   4110: sub tmpdel {
                   4111:     my ($token,$server)=@_;
                   4112:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4113:     return &reply("tmpdel:$token",$server);
                   4114: }
                   4115: 
1.765     albertel 4116: # -------------------------------------------------- portfolio access checking
                   4117: 
                   4118: sub portfolio_access {
1.766     albertel 4119:     my ($requrl) = @_;
1.765     albertel 4120:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4121:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4122:     if ($result) {
                   4123:         my %setters;
                   4124:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4125:             my ($startblock,$endblock) =
                   4126:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4127:             if ($startblock && $endblock) {
                   4128:                 return 'B';
                   4129:             }
                   4130:         } else {
                   4131:             my ($startblock,$endblock) =
                   4132:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4133:             if ($startblock && $endblock) {
                   4134:                 return 'B';
                   4135:             }
                   4136:         }
                   4137:     }
1.765     albertel 4138:     if ($result eq 'ok') {
1.766     albertel 4139:        return 'F';
1.765     albertel 4140:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4141:        return 'A';
1.765     albertel 4142:     }
1.766     albertel 4143:     return '';
1.765     albertel 4144: }
                   4145: 
                   4146: sub get_portfolio_access {
1.767     albertel 4147:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4148: 
                   4149:     if (!ref($access_hash)) {
                   4150: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4151: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4152: 						   $file_name);
                   4153: 	$access_hash = $access_controls{$file_name};
                   4154:     }
                   4155: 
1.765     albertel 4156:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4157:     my $now = time;
                   4158:     if (ref($access_hash) eq 'HASH') {
                   4159:         foreach my $key (keys(%{$access_hash})) {
                   4160:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4161:             if ($start > $now) {
                   4162:                 next;
                   4163:             }
                   4164:             if ($end && $end<$now) {
                   4165:                 next;
                   4166:             }
                   4167:             if ($scope eq 'public') {
                   4168:                 $public = $key;
                   4169:                 last;
                   4170:             } elsif ($scope eq 'guest') {
                   4171:                 $guest = $key;
                   4172:             } elsif ($scope eq 'domains') {
                   4173:                 push(@domains,$key);
                   4174:             } elsif ($scope eq 'users') {
                   4175:                 push(@users,$key);
                   4176:             } elsif ($scope eq 'course') {
                   4177:                 push(@courses,$key);
                   4178:             } elsif ($scope eq 'group') {
                   4179:                 push(@groups,$key);
                   4180:             }
                   4181:         }
                   4182:         if ($public) {
                   4183:             return 'ok';
                   4184:         }
                   4185:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4186:             if ($guest) {
                   4187:                 return $guest;
                   4188:             }
                   4189:         } else {
                   4190:             if (@domains > 0) {
                   4191:                 foreach my $domkey (@domains) {
                   4192:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4193:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4194:                             return 'ok';
                   4195:                         }
                   4196:                     }
                   4197:                 }
                   4198:             }
                   4199:             if (@users > 0) {
                   4200:                 foreach my $userkey (@users) {
1.865     raeburn  4201:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4202:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4203:                             if (ref($item) eq 'HASH') {
                   4204:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4205:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4206:                                     return 'ok';
                   4207:                                 }
                   4208:                             }
                   4209:                         }
                   4210:                     } 
1.765     albertel 4211:                 }
                   4212:             }
                   4213:             my %roleshash;
                   4214:             my @courses_and_groups = @courses;
                   4215:             push(@courses_and_groups,@groups); 
                   4216:             if (@courses_and_groups > 0) {
                   4217:                 my (%allgroups,%allroles); 
                   4218:                 my ($start,$end,$role,$sec,$group);
                   4219:                 foreach my $envkey (%env) {
1.811     albertel 4220:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4221:                         my $cid = $2.'_'.$3; 
                   4222:                         if ($1 eq 'gr') {
                   4223:                             $group = $4;
                   4224:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4225:                         } else {
                   4226:                             if ($4 eq '') {
                   4227:                                 $sec = 'none';
                   4228:                             } else {
                   4229:                                 $sec = $4;
                   4230:                             }
                   4231:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4232:                         }
1.811     albertel 4233:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4234:                         my $cid = $2.'_'.$3;
                   4235:                         if ($4 eq '') {
                   4236:                             $sec = 'none';
                   4237:                         } else {
                   4238:                             $sec = $4;
                   4239:                         }
                   4240:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4241:                     }
                   4242:                 }
                   4243:                 if (keys(%allroles) == 0) {
                   4244:                     return;
                   4245:                 }
                   4246:                 foreach my $key (@courses_and_groups) {
                   4247:                     my %content = %{$$access_hash{$key}};
                   4248:                     my $cnum = $content{'number'};
                   4249:                     my $cdom = $content{'domain'};
                   4250:                     my $cid = $cdom.'_'.$cnum;
                   4251:                     if (!exists($allroles{$cid})) {
                   4252:                         next;
                   4253:                     }    
                   4254:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4255:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4256:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4257:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4258:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4259:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4260:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4261:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4262:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4263:                                         if (grep/^all$/,@sections) {
                   4264:                                             return 'ok';
                   4265:                                         } else {
                   4266:                                             if (grep/^$sec$/,@sections) {
                   4267:                                                 return 'ok';
                   4268:                                             }
                   4269:                                         }
                   4270:                                     }
                   4271:                                 }
                   4272:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4273:                                     if (grep/^none$/,@groups) {
                   4274:                                         return 'ok';
                   4275:                                     }
                   4276:                                 } else {
                   4277:                                     if (grep/^all$/,@groups) {
                   4278:                                         return 'ok';
                   4279:                                     } 
                   4280:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4281:                                         if (grep/^$group$/,@groups) {
                   4282:                                             return 'ok';
                   4283:                                         }
                   4284:                                     }
                   4285:                                 } 
                   4286:                             }
                   4287:                         }
                   4288:                     }
                   4289:                 }
                   4290:             }
                   4291:             if ($guest) {
                   4292:                 return $guest;
                   4293:             }
                   4294:         }
                   4295:     }
                   4296:     return;
                   4297: }
                   4298: 
                   4299: sub course_group_datechecker {
                   4300:     my ($dates,$now,$status) = @_;
                   4301:     my ($start,$end) = split(/\./,$dates);
                   4302:     if (!$start && !$end) {
                   4303:         return 'ok';
                   4304:     }
                   4305:     if (grep/^active$/,@{$status}) {
                   4306:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4307:             return 'ok';
                   4308:         }
                   4309:     }
                   4310:     if (grep/^previous$/,@{$status}) {
                   4311:         if ($end > $now ) {
                   4312:             return 'ok';
                   4313:         }
                   4314:     }
                   4315:     if (grep/^future$/,@{$status}) {
                   4316:         if ($start > $now) {
                   4317:             return 'ok';
                   4318:         }
                   4319:     }
                   4320:     return; 
                   4321: }
                   4322: 
                   4323: sub parse_portfolio_url {
                   4324:     my ($url) = @_;
                   4325: 
                   4326:     my ($type,$udom,$unum,$group,$file_name);
                   4327:     
1.823     albertel 4328:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4329: 	$type = 1;
                   4330:         $udom = $1;
                   4331:         $unum = $2;
                   4332:         $file_name = $3;
1.823     albertel 4333:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4334: 	$type = 2;
                   4335:         $udom = $1;
                   4336:         $unum = $2;
                   4337:         $group = $3;
                   4338:         $file_name = $3.'/'.$4;
                   4339:     }
                   4340:     if (wantarray) {
                   4341: 	return ($type,$udom,$unum,$file_name,$group);
                   4342:     }
                   4343:     return $type;
                   4344: }
                   4345: 
                   4346: sub is_portfolio_url {
                   4347:     my ($url) = @_;
                   4348:     return scalar(&parse_portfolio_url($url));
                   4349: }
                   4350: 
1.798     raeburn  4351: sub is_portfolio_file {
                   4352:     my ($file) = @_;
1.820     raeburn  4353:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4354:         return 1;
                   4355:     }
                   4356:     return;
                   4357: }
                   4358: 
                   4359: 
1.341     www      4360: # ---------------------------------------------- Custom access rule evaluation
                   4361: 
                   4362: sub customaccess {
                   4363:     my ($priv,$uri)=@_;
1.807     albertel 4364:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4365:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4366:     $udom = &LONCAPA::clean_domain($udom);
                   4367:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4368:     my $access=0;
1.800     albertel 4369:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4370: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4371: 	if ($type eq 'user') {
                   4372: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4373: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4374: 		if ($tdom) {
                   4375: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4376: 		}
1.896     albertel 4377: 		if ($tuname) {
                   4378: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4379: 		}
                   4380: 		$access=($effect eq 'allow');
                   4381: 		last;
                   4382: 	    }
                   4383: 	} else {
                   4384: 	    if ($role) {
                   4385: 		if ($role ne $urole) { next; }
                   4386: 	    }
                   4387: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4388: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4389: 		if ($tdom) {
                   4390: 		    if ($tdom ne $udom) { next; }
                   4391: 		}
                   4392: 		if ($tcrs) {
                   4393: 		    if ($tcrs ne $ucrs) { next; }
                   4394: 		}
                   4395: 		if ($tsec) {
                   4396: 		    if ($tsec ne $usec) { next; }
                   4397: 		}
                   4398: 		$access=($effect eq 'allow');
                   4399: 		last;
                   4400: 	    }
                   4401: 	    if ($realm eq '' && $role eq '') {
                   4402: 		$access=($effect eq 'allow');
                   4403: 	    }
1.402     bowersj2 4404: 	}
1.341     www      4405:     }
                   4406:     return $access;
                   4407: }
                   4408: 
1.103     harris41 4409: # ------------------------------------------------- Check for a user privilege
1.12      www      4410: 
                   4411: sub allowed {
1.810     raeburn  4412:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4413:     my $ver_orguri=$uri;
1.439     www      4414:     $uri=&deversion($uri);
1.152     www      4415:     my $orguri=$uri;
1.52      www      4416:     $uri=&declutter($uri);
1.809     raeburn  4417: 
1.810     raeburn  4418:     if ($priv eq 'evb') {
                   4419: # Evade communication block restrictions for specified role in a course
                   4420:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4421:             return $1;
                   4422:         } else {
                   4423:             return;
                   4424:         }
                   4425:     }
                   4426: 
1.620     albertel 4427:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4428: # Free bre access to adm and meta resources
1.775     albertel 4429:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4430: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4431: 	&& ($priv eq 'bre')) {
1.14      www      4432: 	return 'F';
1.159     www      4433:     }
                   4434: 
1.545     banghart 4435: # Free bre access to user's own portfolio contents
1.714     raeburn  4436:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4437:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4438: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4439:         my %setters;
                   4440:         my ($startblock,$endblock) = 
                   4441:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4442:         if ($startblock && $endblock) {
                   4443:             return 'B';
                   4444:         } else {
                   4445:             return 'F';
                   4446:         }
1.545     banghart 4447:     }
                   4448: 
1.762     raeburn  4449: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4450:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4451:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4452:         if (exists($env{'request.course.id'})) {
                   4453:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4454:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4455:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4456:                 my $courseprivid=$env{'request.course.id'};
                   4457:                 $courseprivid=~s/\_/\//;
                   4458:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4459:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4460:                     return $1; 
1.762     raeburn  4461:                 } else {
                   4462:                     if ($env{'request.course.sec'}) {
                   4463:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4464:                     }
                   4465:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4466:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4467:                         return $2;
                   4468:                     }
1.714     raeburn  4469:                 }
                   4470:             }
                   4471:         }
                   4472:     }
                   4473: 
1.159     www      4474: # Free bre to public access
                   4475: 
                   4476:     if ($priv eq 'bre') {
1.238     www      4477:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4478: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4479:            return 'F'; 
                   4480:         }
1.238     www      4481:         if ($copyright eq 'priv') {
                   4482:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4483: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4484: 		return '';
                   4485:             }
                   4486:         }
                   4487:         if ($copyright eq 'domain') {
                   4488:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4489: 	    unless (($env{'user.domain'} eq $1) ||
                   4490:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4491: 		return '';
                   4492:             }
1.262     matthew  4493:         }
1.620     albertel 4494:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4495:             # Library role, so allow browsing of resources in this domain.
                   4496:             return 'F';
1.238     www      4497:         }
1.341     www      4498:         if ($copyright eq 'custom') {
                   4499: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4500:         }
1.14      www      4501:     }
1.264     matthew  4502:     # Domain coordinator is trying to create a course
1.620     albertel 4503:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4504:         # uri is the requested domain in this case.
                   4505:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4506:         # a role of dc for the domain in question.
1.620     albertel 4507:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4508:     }
1.29      www      4509: 
1.52      www      4510:     my $thisallowed='';
                   4511:     my $statecond=0;
                   4512:     my $courseprivid='';
                   4513: 
                   4514: # Course
                   4515: 
1.620     albertel 4516:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4517:        $thisallowed.=$1;
                   4518:     }
1.29      www      4519: 
1.52      www      4520: # Domain
                   4521: 
1.620     albertel 4522:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4523:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4524:        $thisallowed.=$1;
                   4525:     }
1.52      www      4526: 
                   4527: # Course: uri itself is a course
1.66      www      4528:     my $courseuri=$uri;
                   4529:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4530:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4531: 
1.620     albertel 4532:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4533:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4534:        $thisallowed.=$1;
                   4535:     }
1.29      www      4536: 
1.665     albertel 4537: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4538: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4539:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4540: 	$thisallowed='';
1.671     raeburn  4541:         my ($match)=&is_on_map($uri);
                   4542:         if ($match) {
                   4543:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4544:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4545:                 $thisallowed.=$1;
                   4546:             }
                   4547:         } else {
1.705     albertel 4548:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4549:             if ($refuri) {
                   4550:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4551:                     $thisallowed='F';
1.671     raeburn  4552:                 } else {
                   4553:                     $refuri=&declutter($refuri);
                   4554:                     my ($match) = &is_on_map($refuri);
                   4555:                     if ($match) {
                   4556:                         $thisallowed='F';
                   4557:                     }
1.669     raeburn  4558:                 }
1.671     raeburn  4559:             }
                   4560:         }
1.314     www      4561:     }
1.492     albertel 4562: 
1.766     albertel 4563:     if ($priv eq 'bre'
                   4564: 	&& $thisallowed ne 'F' 
                   4565: 	&& $thisallowed ne '2'
                   4566: 	&& &is_portfolio_url($uri)) {
                   4567: 	$thisallowed = &portfolio_access($uri);
                   4568:     }
                   4569:     
1.52      www      4570: # Full access at system, domain or course-wide level? Exit.
1.29      www      4571:     if ($thisallowed=~/F/) {
                   4572: 	return 'F';
                   4573:     }
                   4574: 
1.52      www      4575: # If this is generating or modifying users, exit with special codes
1.29      www      4576: 
1.643     www      4577:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4578: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4579: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4580: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4581: 	    unless ($auname) { return $thisallowed; }
                   4582: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4583: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4584: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4585: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4586: 	}
1.52      www      4587: 	return $thisallowed;
                   4588:     }
                   4589: #
1.103     harris41 4590: # Gathered so far: system, domain and course wide privileges
1.52      www      4591: #
                   4592: # Course: See if uri or referer is an individual resource that is part of 
                   4593: # the course
                   4594: 
1.620     albertel 4595:     if ($env{'request.course.id'}) {
1.232     www      4596: 
1.620     albertel 4597:        $courseprivid=$env{'request.course.id'};
                   4598:        if ($env{'request.course.sec'}) {
                   4599:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4600:        }
                   4601:        $courseprivid=~s/\_/\//;
                   4602:        my $checkreferer=1;
1.232     www      4603:        my ($match,$cond)=&is_on_map($uri);
                   4604:        if ($match) {
                   4605:            $statecond=$cond;
1.620     albertel 4606:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4607:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4608:                $thisallowed.=$1;
                   4609:                $checkreferer=0;
                   4610:            }
1.29      www      4611:        }
1.83      www      4612:        
1.148     www      4613:        if ($checkreferer) {
1.620     albertel 4614: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4615:             unless ($refuri) {
1.800     albertel 4616:                 foreach my $key (keys(%env)) {
                   4617: 		    if ($key=~/^httpref\..*\*/) {
                   4618: 			my $pattern=$key;
1.156     www      4619:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4620:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4621:                         $pattern=~s/\//\\\//g;
1.152     www      4622:                         if ($orguri=~/$pattern/) {
1.800     albertel 4623: 			    $refuri=$env{$key};
1.148     www      4624:                         }
                   4625:                     }
1.191     harris41 4626:                 }
1.148     www      4627:             }
1.232     www      4628: 
1.148     www      4629:          if ($refuri) { 
1.152     www      4630: 	  $refuri=&declutter($refuri);
1.232     www      4631:           my ($match,$cond)=&is_on_map($refuri);
                   4632:             if ($match) {
                   4633:               my $refstatecond=$cond;
1.620     albertel 4634:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4635:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4636:                   $thisallowed.=$1;
1.53      www      4637:                   $uri=$refuri;
                   4638:                   $statecond=$refstatecond;
1.52      www      4639:               }
                   4640:           }
1.148     www      4641:         }
1.29      www      4642:        }
1.52      www      4643:    }
1.29      www      4644: 
1.52      www      4645: #
1.103     harris41 4646: # Gathered now: all privileges that could apply, and condition number
1.52      www      4647: # 
                   4648: #
                   4649: # Full or no access?
                   4650: #
1.29      www      4651: 
1.52      www      4652:     if ($thisallowed=~/F/) {
                   4653: 	return 'F';
                   4654:     }
1.29      www      4655: 
1.52      www      4656:     unless ($thisallowed) {
                   4657:         return '';
                   4658:     }
1.29      www      4659: 
1.52      www      4660: # Restrictions exist, deal with them
                   4661: #
                   4662: #   C:according to course preferences
                   4663: #   R:according to resource settings
                   4664: #   L:unless locked
                   4665: #   X:according to user session state
                   4666: #
                   4667: 
                   4668: # Possibly locked functionality, check all courses
1.54      www      4669: # Locks might take effect only after 10 minutes cache expiration for other
                   4670: # courses, and 2 minutes for current course
1.52      www      4671: 
                   4672:     my $envkey;
                   4673:     if ($thisallowed=~/L/) {
1.620     albertel 4674:         foreach $envkey (keys %env) {
1.54      www      4675:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4676:                my $courseid=$2;
                   4677:                my $roleid=$1.'.'.$2;
1.92      www      4678:                $courseid=~s/^\///;
1.54      www      4679:                my $expiretime=600;
1.620     albertel 4680:                if ($env{'request.role'} eq $roleid) {
1.54      www      4681: 		  $expiretime=120;
                   4682:                }
                   4683: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4684:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4685:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4686: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4687:                }
1.620     albertel 4688:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4689:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4690: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4691:                        &log($env{'user.domain'},$env{'user.name'},
                   4692:                             $env{'user.home'},
1.57      www      4693:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4694:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4695:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4696: 		       return '';
                   4697:                    }
                   4698:                }
1.620     albertel 4699:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4700:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4701: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4702:                        &log($env{'user.domain'},$env{'user.name'},
                   4703:                             $env{'user.home'},
1.57      www      4704:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4705:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4706:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4707: 		       return '';
                   4708:                    }
                   4709:                }
                   4710: 	   }
1.29      www      4711:        }
1.52      www      4712:     }
                   4713:    
                   4714: #
                   4715: # Rest of the restrictions depend on selected course
                   4716: #
                   4717: 
1.620     albertel 4718:     unless ($env{'request.course.id'}) {
1.766     albertel 4719: 	if ($thisallowed eq 'A') {
                   4720: 	    return 'A';
1.814     raeburn  4721:         } elsif ($thisallowed eq 'B') {
                   4722:             return 'B';
1.766     albertel 4723: 	} else {
                   4724: 	    return '1';
                   4725: 	}
1.52      www      4726:     }
1.29      www      4727: 
1.52      www      4728: #
                   4729: # Now user is definitely in a course
                   4730: #
1.53      www      4731: 
                   4732: 
                   4733: # Course preferences
                   4734: 
                   4735:    if ($thisallowed=~/C/) {
1.620     albertel 4736:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4737:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4738:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4739: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4740: 	   if ($priv ne 'pch') { 
                   4741: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4742: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4743: 			$env{'request.course.id'});
                   4744: 	   }
1.237     www      4745:            return '';
                   4746:        }
                   4747: 
1.620     albertel 4748:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4749: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4750: 	   if ($priv ne 'pch') { 
                   4751: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4752: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4753: 			$env{'request.course.id'});
                   4754: 	   }
1.54      www      4755:            return '';
                   4756:        }
1.53      www      4757:    }
                   4758: 
                   4759: # Resource preferences
                   4760: 
                   4761:    if ($thisallowed=~/R/) {
1.620     albertel 4762:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4763:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4764: 	   if ($priv ne 'pch') { 
                   4765: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4766: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4767: 	   }
                   4768: 	   return '';
1.54      www      4769:        }
1.53      www      4770:    }
1.30      www      4771: 
1.246     www      4772: # Restricted by state or randomout?
1.30      www      4773: 
1.52      www      4774:    if ($thisallowed=~/X/) {
1.620     albertel 4775:       if ($env{'acc.randomout'}) {
1.579     albertel 4776: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4777:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4778:             return ''; 
                   4779:          }
1.247     www      4780:       }
                   4781:       if (&condval($statecond)) {
1.52      www      4782: 	 return '2';
                   4783:       } else {
                   4784:          return '';
                   4785:       }
                   4786:    }
1.30      www      4787: 
1.766     albertel 4788:     if ($thisallowed eq 'A') {
                   4789: 	return 'A';
1.814     raeburn  4790:     } elsif ($thisallowed eq 'B') {
                   4791:         return 'B';
1.766     albertel 4792:     }
1.52      www      4793:    return 'F';
1.232     www      4794: }
                   4795: 
1.710     albertel 4796: sub split_uri_for_cond {
                   4797:     my $uri=&deversion(&declutter(shift));
                   4798:     my @uriparts=split(/\//,$uri);
                   4799:     my $filename=pop(@uriparts);
                   4800:     my $pathname=join('/',@uriparts);
                   4801:     return ($pathname,$filename);
                   4802: }
1.232     www      4803: # --------------------------------------------------- Is a resource on the map?
                   4804: 
                   4805: sub is_on_map {
1.710     albertel 4806:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4807:     #Trying to find the conditional for the file
1.620     albertel 4808:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4809: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4810:     if ($match) {
1.289     bowersj2 4811: 	return (1,$1);
                   4812:     } else {
1.434     www      4813: 	return (0,0);
1.289     bowersj2 4814:     }
1.12      www      4815: }
                   4816: 
1.427     www      4817: # --------------------------------------------------------- Get symb from alias
                   4818: 
                   4819: sub get_symb_from_alias {
                   4820:     my $symb=shift;
                   4821:     my ($map,$resid,$url)=&decode_symb($symb);
                   4822: # Already is a symb
                   4823:     if ($url) { return $symb; }
                   4824: # Must be an alias
                   4825:     my $aliassymb='';
                   4826:     my %bighash;
1.620     albertel 4827:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4828:                             &GDBM_READER(),0640)) {
                   4829:         my $rid=$bighash{'mapalias_'.$symb};
                   4830: 	if ($rid) {
                   4831: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4832: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4833: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4834: 	}
                   4835:         untie %bighash;
                   4836:     }
                   4837:     return $aliassymb;
                   4838: }
                   4839: 
1.12      www      4840: # ----------------------------------------------------------------- Define Role
                   4841: 
                   4842: sub definerole {
                   4843:   if (allowed('mcr','/')) {
                   4844:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4845:     foreach my $role (split(':',$sysrole)) {
                   4846: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4847:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4848:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4849: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4850:                return "refused:s:$crole&$cqual"; 
                   4851:             }
                   4852:         }
1.191     harris41 4853:     }
1.800     albertel 4854:     foreach my $role (split(':',$domrole)) {
                   4855: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4856:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4857:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4858: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4859:                return "refused:d:$crole&$cqual"; 
                   4860:             }
                   4861:         }
1.191     harris41 4862:     }
1.800     albertel 4863:     foreach my $role (split(':',$courole)) {
                   4864: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4865:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4866:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4867: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4868:                return "refused:c:$crole&$cqual"; 
                   4869:             }
                   4870:         }
1.191     harris41 4871:     }
1.620     albertel 4872:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4873:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4874: 	        "rolesdef_$rolename=".
                   4875:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4876:     return reply($command,$env{'user.home'});
1.12      www      4877:   } else {
                   4878:     return 'refused';
                   4879:   }
1.105     harris41 4880: }
                   4881: 
                   4882: # ---------------- Make a metadata query against the network of library servers
                   4883: 
                   4884: sub metadata_query {
1.244     matthew  4885:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4886:     my %rhash;
1.845     albertel 4887:     my %libserv = &all_library();
1.244     matthew  4888:     my @server_list = (defined($server_array) ? @$server_array
                   4889:                                               : keys(%libserv) );
                   4890:     for my $server (@server_list) {
1.118     harris41 4891: 	unless ($custom or $customshow) {
                   4892: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4893: 	    $rhash{$server}=$reply;
                   4894: 	}
                   4895: 	else {
                   4896: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4897: 			     &escape($custom).':'.&escape($customshow),
                   4898: 			     $server);
                   4899: 	    $rhash{$server}=$reply;
                   4900: 	}
1.112     harris41 4901:     }
1.118     harris41 4902:     return \%rhash;
1.240     www      4903: }
                   4904: 
                   4905: # ----------------------------------------- Send log queries and wait for reply
                   4906: 
                   4907: sub log_query {
                   4908:     my ($uname,$udom,$query,%filters)=@_;
                   4909:     my $uhome=&homeserver($uname,$udom);
                   4910:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4911:     my $uhost=&hostname($uhome);
1.800     albertel 4912:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4913:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4914:                        $uhome);
1.479     albertel 4915:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4916:     return get_query_reply($queryid);
                   4917: }
                   4918: 
1.818     raeburn  4919: # -------------------------- Update MySQL table for portfolio file
                   4920: 
                   4921: sub update_portfolio_table {
1.821     raeburn  4922:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  4923:     if ($group ne '') {
                   4924:         $file_name =~s /^\Q$group\E//;
                   4925:     }
1.818     raeburn  4926:     my $homeserver = &homeserver($uname,$udom);
                   4927:     my $queryid=
1.821     raeburn  4928:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4929:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4930:     my $reply = &get_query_reply($queryid);
                   4931:     return $reply;
                   4932: }
                   4933: 
1.899     raeburn  4934: # -------------------------- Update MySQL allusers table
                   4935: 
                   4936: sub update_allusers_table {
                   4937:     my ($uname,$udom,$names) = @_;
                   4938:     my $homeserver = &homeserver($uname,$udom);
                   4939:     my $queryid=
                   4940:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4941:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4942:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4943:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4944:                'generation='.&escape($names->{'generation'}).'%%'.
                   4945:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4946:                'id='.&escape($names->{'id'}),$homeserver);
                   4947:     my $reply = &get_query_reply($queryid);
                   4948:     return $reply;
                   4949: }
                   4950: 
1.508     raeburn  4951: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4952: 
                   4953: sub fetch_enrollment_query {
1.511     raeburn  4954:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4955:     my $homeserver;
1.547     raeburn  4956:     my $maxtries = 1;
1.508     raeburn  4957:     if ($context eq 'automated') {
                   4958:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4959:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4960:     } else {
                   4961:         $homeserver = &homeserver($cnum,$dom);
                   4962:     }
1.838     albertel 4963:     my $host=&hostname($homeserver);
1.506     raeburn  4964:     my $cmd = '';
1.800     albertel 4965:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4966:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4967:     }
                   4968:     $cmd =~ s/%%$//;
                   4969:     $cmd = &escape($cmd);
                   4970:     my $query = 'fetchenrollment';
1.620     albertel 4971:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4972:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4973:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4974:         return 'error: '.$queryid;
                   4975:     }
1.506     raeburn  4976:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4977:     my $tries = 1;
                   4978:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4979:         $reply = &get_query_reply($queryid);
                   4980:         $tries ++;
                   4981:     }
1.526     raeburn  4982:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4983:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4984:     } else {
1.901     albertel 4985:         my @responses = split(/:/,$reply);
1.515     raeburn  4986:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4987:             foreach my $line (@responses) {
                   4988:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4989:                 $$replyref{$key} = $value;
                   4990:             }
                   4991:         } else {
1.506     raeburn  4992:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4993:             foreach my $line (@responses) {
                   4994:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4995:                 $$replyref{$key} = $value;
                   4996:                 if ($value > 0) {
1.800     albertel 4997:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4998:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4999:                         my $destname = $pathname.'/'.$filename;
                   5000:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5001:                         if ($xml_classlist =~ /^error/) {
                   5002:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5003:                         } else {
1.506     raeburn  5004:                             if ( open(FILE,">$destname") ) {
                   5005:                                 print FILE &unescape($xml_classlist);
                   5006:                                 close(FILE);
1.526     raeburn  5007:                             } else {
                   5008:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5009:                             }
                   5010:                         }
                   5011:                     }
                   5012:                 }
                   5013:             }
                   5014:         }
                   5015:         return 'ok';
                   5016:     }
                   5017:     return 'error';
                   5018: }
                   5019: 
1.242     www      5020: sub get_query_reply {
                   5021:     my $queryid=shift;
1.240     www      5022:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5023:     my $reply='';
                   5024:     for (1..100) {
                   5025: 	sleep 2;
                   5026:         if (-e $replyfile.'.end') {
1.448     albertel 5027: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5028: 		$reply = join('',<$fh>);
                   5029: 		close($fh);
1.240     www      5030: 	   } else { return 'error: reply_file_error'; }
1.242     www      5031:            return &unescape($reply);
                   5032: 	}
1.240     www      5033:     }
1.242     www      5034:     return 'timeout:'.$queryid;
1.240     www      5035: }
                   5036: 
                   5037: sub courselog_query {
1.241     www      5038: #
                   5039: # possible filters:
                   5040: # url: url or symb
                   5041: # username
                   5042: # domain
                   5043: # action: view, submit, grade
                   5044: # start: timestamp
                   5045: # end: timestamp
                   5046: #
1.240     www      5047:     my (%filters)=@_;
1.620     albertel 5048:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5049:     if ($filters{'url'}) {
                   5050: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5051:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5052:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5053:     }
1.620     albertel 5054:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5055:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5056:     return &log_query($cname,$cdom,'courselog',%filters);
                   5057: }
                   5058: 
                   5059: sub userlog_query {
1.858     raeburn  5060: #
                   5061: # possible filters:
                   5062: # action: log check role
                   5063: # start: timestamp
                   5064: # end: timestamp
                   5065: #
1.240     www      5066:     my ($uname,$udom,%filters)=@_;
                   5067:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5068: }
                   5069: 
1.506     raeburn  5070: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5071: 
                   5072: sub auto_run {
1.508     raeburn  5073:     my ($cnum,$cdom) = @_;
1.876     raeburn  5074:     my $response = 0;
                   5075:     my $settings;
                   5076:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5077:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5078:         $settings = $domconfig{'autoenroll'};
                   5079:         if ($settings->{'run'} eq '1') {
                   5080:             $response = 1;
                   5081:         }
                   5082:     } else {
1.934     raeburn  5083:         my $homeserver;
                   5084:         if (&is_course($cdom,$cnum)) {
                   5085:             $homeserver = &homeserver($cnum,$cdom);
                   5086:         } else {
                   5087:             $homeserver = &domain($cdom,'primary');
                   5088:         }
                   5089:         if ($homeserver ne 'no_host') {
                   5090:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5091:         }
1.876     raeburn  5092:     }
1.506     raeburn  5093:     return $response;
                   5094: }
1.776     albertel 5095: 
1.506     raeburn  5096: sub auto_get_sections {
1.508     raeburn  5097:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5098:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5099:     my @secs = ();
1.511     raeburn  5100:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5101:     unless ($response eq 'refused') {
1.901     albertel 5102:         @secs = split(/:/,$response);
1.506     raeburn  5103:     }
                   5104:     return @secs;
                   5105: }
1.776     albertel 5106: 
1.506     raeburn  5107: sub auto_new_course {
1.508     raeburn  5108:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5109:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5110:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5111:     return $response;
                   5112: }
1.776     albertel 5113: 
1.506     raeburn  5114: sub auto_validate_courseID {
1.508     raeburn  5115:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5116:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5117:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5118:     return $response;
                   5119: }
1.776     albertel 5120: 
1.506     raeburn  5121: sub auto_create_password {
1.873     raeburn  5122:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5123:     my ($homeserver,$response);
1.506     raeburn  5124:     my $create_passwd = 0;
                   5125:     my $authchk = '';
1.873     raeburn  5126:     if ($udom =~ /^$match_domain$/) {
                   5127:         $homeserver = &domain($udom,'primary');
                   5128:     }
                   5129:     if ($homeserver eq '') {
                   5130:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5131:             $homeserver = &homeserver($cnum,$cdom);
                   5132:         }
                   5133:     }
                   5134:     if ($homeserver eq '') {
                   5135:         $authchk = 'nodomain';
1.506     raeburn  5136:     } else {
1.873     raeburn  5137:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5138:         if ($response eq 'refused') {
                   5139:             $authchk = 'refused';
                   5140:         } else {
1.901     albertel 5141:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5142:         }
1.506     raeburn  5143:     }
                   5144:     return ($authparam,$create_passwd,$authchk);
                   5145: }
                   5146: 
1.706     raeburn  5147: sub auto_photo_permission {
                   5148:     my ($cnum,$cdom,$students) = @_;
                   5149:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5150:     my ($outcome,$perm_reqd,$conditions) = 
                   5151: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5152:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5153: 	return (undef,undef);
                   5154:     }
1.706     raeburn  5155:     return ($outcome,$perm_reqd,$conditions);
                   5156: }
                   5157: 
                   5158: sub auto_checkphotos {
                   5159:     my ($uname,$udom,$pid) = @_;
                   5160:     my $homeserver = &homeserver($uname,$udom);
                   5161:     my ($result,$resulttype);
                   5162:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5163: 				   &escape($uname).':'.&escape($pid),
                   5164: 				   $homeserver));
1.709     albertel 5165:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5166: 	return (undef,undef);
                   5167:     }
1.706     raeburn  5168:     if ($outcome) {
                   5169:         ($result,$resulttype) = split(/:/,$outcome);
                   5170:     } 
                   5171:     return ($result,$resulttype);
                   5172: }
                   5173: 
                   5174: sub auto_photochoice {
                   5175:     my ($cnum,$cdom) = @_;
                   5176:     my $homeserver = &homeserver($cnum,$cdom);
                   5177:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5178: 						       &escape($cdom),
                   5179: 						       $homeserver)));
1.709     albertel 5180:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5181: 	return (undef,undef);
                   5182:     }
1.706     raeburn  5183:     return ($update,$comment);
                   5184: }
                   5185: 
                   5186: sub auto_photoupdate {
                   5187:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5188:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5189:     my $host=&hostname($homeserver);
1.706     raeburn  5190:     my $cmd = '';
                   5191:     my $maxtries = 1;
1.800     albertel 5192:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5193:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5194:     }
                   5195:     $cmd =~ s/%%$//;
                   5196:     $cmd = &escape($cmd);
                   5197:     my $query = 'institutionalphotos';
                   5198:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5199:     unless ($queryid=~/^\Q$host\E\_/) {
                   5200:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5201:         return 'error: '.$queryid;
                   5202:     }
                   5203:     my $reply = &get_query_reply($queryid);
                   5204:     my $tries = 1;
                   5205:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5206:         $reply = &get_query_reply($queryid);
                   5207:         $tries ++;
                   5208:     }
                   5209:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5210:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5211:     } else {
                   5212:         my @responses = split(/:/,$reply);
                   5213:         my $outcome = shift(@responses); 
                   5214:         foreach my $item (@responses) {
                   5215:             my ($key,$value) = split(/=/,$item);
                   5216:             $$photo{$key} = $value;
                   5217:         }
                   5218:         return $outcome;
                   5219:     }
                   5220:     return 'error';
                   5221: }
                   5222: 
1.521     raeburn  5223: sub auto_instcode_format {
1.793     albertel 5224:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5225: 	$cat_order) = @_;
1.521     raeburn  5226:     my $courses = '';
1.772     raeburn  5227:     my @homeservers;
1.521     raeburn  5228:     if ($caller eq 'global') {
1.841     albertel 5229: 	my %servers = &get_servers($codedom,'library');
                   5230: 	foreach my $tryserver (keys(%servers)) {
                   5231: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5232: 		push(@homeservers,$tryserver);
                   5233: 	    }
1.584     raeburn  5234:         }
1.521     raeburn  5235:     } else {
1.772     raeburn  5236:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5237:     }
1.793     albertel 5238:     foreach my $code (keys(%{$instcodes})) {
                   5239:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5240:     }
                   5241:     chop($courses);
1.772     raeburn  5242:     my $ok_response = 0;
                   5243:     my $response;
                   5244:     while (@homeservers > 0 && $ok_response == 0) {
                   5245:         my $server = shift(@homeservers); 
                   5246:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5247:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5248:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5249: 		split(/:/,$response);
1.772     raeburn  5250:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5251:             push(@{$codetitles},&str2array($codetitles_str));
                   5252:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5253:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5254:             $ok_response = 1;
                   5255:         }
                   5256:     }
                   5257:     if ($ok_response) {
1.521     raeburn  5258:         return 'ok';
1.772     raeburn  5259:     } else {
                   5260:         return $response;
1.521     raeburn  5261:     }
                   5262: }
                   5263: 
1.792     raeburn  5264: sub auto_instcode_defaults {
                   5265:     my ($domain,$returnhash,$code_order) = @_;
                   5266:     my @homeservers;
1.841     albertel 5267: 
                   5268:     my %servers = &get_servers($domain,'library');
                   5269:     foreach my $tryserver (keys(%servers)) {
                   5270: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5271: 	    push(@homeservers,$tryserver);
                   5272: 	}
1.792     raeburn  5273:     }
1.841     albertel 5274: 
1.792     raeburn  5275:     my $response;
1.841     albertel 5276:     foreach my $server (@homeservers) {
1.792     raeburn  5277:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5278:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5279: 	
                   5280: 	foreach my $pair (split(/\&/,$response)) {
                   5281: 	    my ($name,$value)=split(/\=/,$pair);
                   5282: 	    if ($name eq 'code_order') {
                   5283: 		@{$code_order} = split(/\&/,&unescape($value));
                   5284: 	    } else {
                   5285: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5286: 	    }
                   5287: 	}
                   5288: 	return 'ok';
1.792     raeburn  5289:     }
1.841     albertel 5290: 
                   5291:     return $response;
1.792     raeburn  5292: } 
                   5293: 
1.777     albertel 5294: sub auto_validate_class_sec {
1.918     raeburn  5295:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5296:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5297:     my $ownerlist;
                   5298:     if (ref($owners) eq 'ARRAY') {
                   5299:         $ownerlist = join(',',@{$owners});
                   5300:     } else {
                   5301:         $ownerlist = $owners;
                   5302:     }
1.773     raeburn  5303:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5304:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5305:     return $response;
                   5306: }
                   5307: 
1.679     raeburn  5308: # ------------------------------------------------------- Course Group routines
                   5309: 
                   5310: sub get_coursegroups {
1.809     raeburn  5311:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5312:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5313: }
                   5314: 
1.679     raeburn  5315: sub modify_coursegroup {
                   5316:     my ($cdom,$cnum,$groupsettings) = @_;
                   5317:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5318: }
                   5319: 
1.809     raeburn  5320: sub toggle_coursegroup_status {
                   5321:     my ($cdom,$cnum,$group,$action) = @_;
                   5322:     my ($from_namespace,$to_namespace);
                   5323:     if ($action eq 'delete') {
                   5324:         $from_namespace = 'coursegroups';
                   5325:         $to_namespace = 'deleted_groups';
                   5326:     } else {
                   5327:         $from_namespace = 'deleted_groups';
                   5328:         $to_namespace = 'coursegroups';
                   5329:     }
                   5330:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5331:     if (my $tmp = &error(%curr_group)) {
                   5332:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5333:         return ('read error',$tmp);
                   5334:     } else {
                   5335:         my %savedsettings = %curr_group; 
1.809     raeburn  5336:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5337:         my $deloutcome;
                   5338:         if ($result eq 'ok') {
1.809     raeburn  5339:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5340:         } else {
                   5341:             return ('write error',$result);
                   5342:         }
                   5343:         if ($deloutcome eq 'ok') {
                   5344:             return 'ok';
                   5345:         } else {
                   5346:             return ('delete error',$deloutcome);
                   5347:         }
                   5348:     }
                   5349: }
                   5350: 
1.679     raeburn  5351: sub modify_group_roles {
1.957     raeburn  5352:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5353:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5354:     my $role = 'gr/'.&escape($userprivs);
                   5355:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5356:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5357:     if ($result eq 'ok') {
                   5358:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5359:     }
1.679     raeburn  5360:     return $result;
                   5361: }
                   5362: 
                   5363: sub modify_coursegroup_membership {
                   5364:     my ($cdom,$cnum,$membership) = @_;
                   5365:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5366:     return $result;
                   5367: }
                   5368: 
1.682     raeburn  5369: sub get_active_groups {
                   5370:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5371:     my $now = time;
                   5372:     my %groups = ();
                   5373:     foreach my $key (keys(%env)) {
1.811     albertel 5374:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5375:             my ($start,$end) = split(/\./,$env{$key});
                   5376:             if (($end!=0) && ($end<$now)) { next; }
                   5377:             if (($start!=0) && ($start>$now)) { next; }
                   5378:             if ($1 eq $cdom && $2 eq $cnum) {
                   5379:                 $groups{$3} = $env{$key} ;
                   5380:             }
                   5381:         }
                   5382:     }
                   5383:     return %groups;
                   5384: }
                   5385: 
1.683     raeburn  5386: sub get_group_membership {
                   5387:     my ($cdom,$cnum,$group) = @_;
                   5388:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5389: }
                   5390: 
                   5391: sub get_users_groups {
                   5392:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5393:     my @usersgroups;
1.683     raeburn  5394:     my $cachetime=1800;
                   5395: 
                   5396:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5397:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5398:     if (defined($cached)) {
1.734     albertel 5399:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5400:     } else {  
                   5401:         $grouplist = '';
1.816     raeburn  5402:         my $courseurl = &courseid_to_courseurl($courseid);
                   5403:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5404:         my $access_end = $env{'course.'.$courseid.
                   5405:                               '.default_enrollment_end_date'};
                   5406:         my $now = time;
                   5407:         foreach my $key (keys(%roleshash)) {
                   5408:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5409:                 my $group = $1;
                   5410:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5411:                     my $start = $2;
                   5412:                     my $end = $1;
                   5413:                     if ($start == -1) { next; } # deleted from group
                   5414:                     if (($start!=0) && ($start>$now)) { next; }
                   5415:                     if (($end!=0) && ($end<$now)) {
                   5416:                         if ($access_end && $access_end < $now) {
                   5417:                             if ($access_end - $end < 86400) {
                   5418:                                 push(@usersgroups,$group);
1.733     raeburn  5419:                             }
                   5420:                         }
1.817     raeburn  5421:                         next;
1.733     raeburn  5422:                     }
1.817     raeburn  5423:                     push(@usersgroups,$group);
1.683     raeburn  5424:                 }
                   5425:             }
                   5426:         }
1.817     raeburn  5427:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5428:         $grouplist = join(':',@usersgroups);
                   5429:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5430:     }
1.733     raeburn  5431:     return @usersgroups;
1.683     raeburn  5432: }
                   5433: 
                   5434: sub devalidate_getgroups_cache {
                   5435:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5436:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5437: 
1.683     raeburn  5438:     my $hashid="$udom:$uname:$courseid";
                   5439:     &devalidate_cache_new('getgroups',$hashid);
                   5440: }
                   5441: 
1.12      www      5442: # ------------------------------------------------------------------ Plain Text
                   5443: 
                   5444: sub plaintext {
1.742     raeburn  5445:     my ($short,$type,$cid) = @_;
1.758     albertel 5446:     if ($short =~ /^cr/) {
                   5447: 	return (split('/',$short))[-1];
                   5448:     }
1.742     raeburn  5449:     if (!defined($cid)) {
                   5450:         $cid = $env{'request.course.id'};
                   5451:     }
                   5452:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5453:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5454:                                           '.plaintext'});
                   5455:     }
                   5456:     my %rolenames = (
                   5457:                       Course => 'std',
                   5458:                       Group => 'alt1',
                   5459:                     );
                   5460:     if (defined($type) && 
                   5461:          defined($rolenames{$type}) && 
                   5462:          defined($prp{$short}{$rolenames{$type}})) {
                   5463:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5464:     } else {
                   5465:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5466:     }
1.12      www      5467: }
                   5468: 
                   5469: # ----------------------------------------------------------------- Assign Role
                   5470: 
                   5471: sub assignrole {
1.957     raeburn  5472:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5473:         $context)=@_;
1.21      www      5474:     my $mrole;
                   5475:     if ($role =~ /^cr\//) {
1.393     www      5476:         my $cwosec=$url;
1.811     albertel 5477:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5478: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5479:            &logthis('Refused custom assignrole: '.
                   5480:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5481: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5482:            return 'refused'; 
                   5483:         }
1.21      www      5484:         $mrole='cr';
1.678     raeburn  5485:     } elsif ($role =~ /^gr\//) {
                   5486:         my $cwogrp=$url;
1.811     albertel 5487:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5488:         unless (&allowed('mdg',$cwogrp)) {
                   5489:             &logthis('Refused group assignrole: '.
                   5490:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5491:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5492:             return 'refused';
                   5493:         }
                   5494:         $mrole='gr';
1.21      www      5495:     } else {
1.82      www      5496:         my $cwosec=$url;
1.811     albertel 5497:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5498:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5499:             my $refused;
                   5500:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5501:                 if (!(&allowed('c'.$role,$url))) {
                   5502:                     $refused = 1;
                   5503:                 }
                   5504:             } else {
                   5505:                 $refused = 1;
                   5506:             }
1.947     raeburn  5507:             if ($refused) {
                   5508:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5509:                     $refused = '';
                   5510:                 } else {
                   5511:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5512:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5513: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5514:                     return 'refused';
                   5515:                 }
1.932     raeburn  5516:             }
1.104     www      5517:         }
1.21      www      5518:         $mrole=$role;
                   5519:     }
1.620     albertel 5520:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5521:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5522:     if ($end) { $command.='_'.$end; }
1.21      www      5523:     if ($start) {
                   5524: 	if ($end) { 
1.81      www      5525:            $command.='_'.$start; 
1.21      www      5526:         } else {
1.81      www      5527:            $command.='_0_'.$start;
1.21      www      5528:         }
                   5529:     }
1.739     raeburn  5530:     my $origstart = $start;
                   5531:     my $origend = $end;
1.957     raeburn  5532:     my $delflag;
1.357     www      5533: # actually delete
                   5534:     if ($deleteflag) {
1.373     www      5535: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5536: # modify command to delete the role
1.620     albertel 5537:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5538:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5539: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5540: # set start and finish to negative values for userrolelog
                   5541:            $start=-1;
                   5542:            $end=-1;
1.957     raeburn  5543:            $delflag = 1;
1.357     www      5544:         }
                   5545:     }
                   5546: # send command
1.349     www      5547:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5548: # log new user role if status is ok
1.349     www      5549:     if ($answer eq 'ok') {
1.663     raeburn  5550: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5551: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5552:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5553:         unless ($role =~ /^gr/) {
                   5554:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5555:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5556:         }
1.349     www      5557:     }
                   5558:     return $answer;
1.169     harris41 5559: }
                   5560: 
                   5561: # -------------------------------------------------- Modify user authentication
1.197     www      5562: # Overrides without validation
                   5563: 
1.169     harris41 5564: sub modifyuserauth {
                   5565:     my ($udom,$uname,$umode,$upass)=@_;
                   5566:     my $uhome=&homeserver($uname,$udom);
1.197     www      5567:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5568:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5569:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5570:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5571:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5572: 		     &escape($upass),$uhome);
1.620     albertel 5573:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5574:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5575:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5576:     &log($udom,,$uname,$uhome,
1.620     albertel 5577:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5578:                                      $env{'user.name'}.', '.$umode.
1.197     www      5579:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5580:     unless ($reply eq 'ok') {
1.197     www      5581:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5582: 	return 'error: '.$reply;
                   5583:     }   
1.170     harris41 5584:     return 'ok';
1.80      www      5585: }
                   5586: 
1.81      www      5587: # --------------------------------------------------------------- Modify a user
1.80      www      5588: 
1.81      www      5589: sub modifyuser {
1.206     matthew  5590:     my ($udom,    $uname, $uid,
                   5591:         $umode,   $upass, $first,
                   5592:         $middle,  $last,  $gene,
1.963     raeburn  5593:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5594:     $udom= &LONCAPA::clean_domain($udom);
                   5595:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5596:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5597:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5598: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5599:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5600:                                      ' desiredhome not specified'). 
1.620     albertel 5601:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5602:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5603:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5604: # ----------------------------------------------------------------- Create User
1.406     albertel 5605:     if (($uhome eq 'no_host') && 
                   5606: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5607:         my $unhome='';
1.844     albertel 5608:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5609:             $unhome = $desiredhome;
1.620     albertel 5610: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5611: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5612:         } else { # load balancing routine for determining $unhome
1.81      www      5613:             my $loadm=10000000;
1.841     albertel 5614: 	    my %servers = &get_servers($udom,'library');
                   5615: 	    foreach my $tryserver (keys(%servers)) {
                   5616: 		my $answer=reply('load',$tryserver);
                   5617: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5618: 		    $loadm=$answer;
                   5619: 		    $unhome=$tryserver;
                   5620: 		}
1.80      www      5621: 	    }
                   5622:         }
                   5623:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5624: 	    return 'error: unable to find a home server for '.$uname.
                   5625:                    ' in domain '.$udom;
1.80      www      5626:         }
                   5627:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5628:                          &escape($upass),$unhome);
                   5629: 	unless ($reply eq 'ok') {
                   5630:             return 'error: '.$reply;
                   5631:         }   
1.230     stredwic 5632:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5633:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5634: 	    return 'error: unable verify users home machine.';
1.80      www      5635:         }
1.209     matthew  5636:     }   # End of creation of new user
1.80      www      5637: # ---------------------------------------------------------------------- Add ID
                   5638:     if ($uid) {
                   5639:        $uid=~tr/A-Z/a-z/;
                   5640:        my %uidhash=&idrget($udom,$uname);
1.196     www      5641:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5642:          && (!$forceid)) {
1.80      www      5643: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5644: 	      return 'error: user id "'.$uid.'" does not match '.
                   5645:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5646:           }
                   5647:        } else {
                   5648: 	  &idput($udom,($uname => $uid));
                   5649:        }
                   5650:     }
                   5651: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5652:     my @tmp=&get('environment',
1.899     raeburn  5653: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5654:                     'permanentemail','inststatus'],
1.134     albertel 5655: 		   $udom,$uname);
1.313     matthew  5656:     my %names;
                   5657:     if ($tmp[0] =~ m/^error:.*/) { 
                   5658:         %names=(); 
                   5659:     } else {
                   5660:         %names = @tmp;
                   5661:     }
1.388     www      5662: #
                   5663: # Make sure to not trash student environment if instructor does not bother
                   5664: # to supply name and email information
                   5665: #
                   5666:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5667:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5668:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5669:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5670:     if ($email) {
                   5671:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5672:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5673:     }
1.899     raeburn  5674:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5675:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5676:     my $reply = &put('environment', \%names, $udom,$uname);
                   5677:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5678:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5679:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5680:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5681:                  $umode.', '.$first.', '.$middle.', '.
                   5682: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5683:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5684:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5685:     } else {
                   5686:         $logmsg .= ' during self creation';
                   5687:     }
                   5688:     &logthis($logmsg);
1.134     albertel 5689:     return 'ok';
1.80      www      5690: }
                   5691: 
1.81      www      5692: # -------------------------------------------------------------- Modify student
1.80      www      5693: 
1.81      www      5694: sub modifystudent {
                   5695:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5696:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5697:         $selfenroll,$context)=@_;
1.455     albertel 5698:     if (!$cid) {
1.620     albertel 5699: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5700: 	    return 'not_in_class';
                   5701: 	}
1.80      www      5702:     }
                   5703: # --------------------------------------------------------------- Make the user
1.81      www      5704:     my $reply=&modifyuser
1.209     matthew  5705: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5706:          $desiredhome,$email);
1.80      www      5707:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5708:     # This will cause &modify_student_enrollment to get the uid from the
                   5709:     # students environment
                   5710:     $uid = undef if (!$forceid);
1.455     albertel 5711:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5712: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5713:     return $reply;
                   5714: }
                   5715: 
                   5716: sub modify_student_enrollment {
1.957     raeburn  5717:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5718:     my ($cdom,$cnum,$chome);
                   5719:     if (!$cid) {
1.620     albertel 5720: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5721: 	    return 'not_in_class';
                   5722: 	}
1.620     albertel 5723: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5724: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5725:     } else {
                   5726: 	($cdom,$cnum)=split(/_/,$cid);
                   5727:     }
1.620     albertel 5728:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5729:     if (!$chome) {
1.457     raeburn  5730: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5731:     }
1.455     albertel 5732:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5733:     # Make sure the user exists
1.81      www      5734:     my $uhome=&homeserver($uname,$udom);
                   5735:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5736: 	return 'error: no such user';
                   5737:     }
1.297     matthew  5738:     # Get student data if we were not given enough information
                   5739:     if (!defined($first)  || $first  eq '' || 
                   5740:         !defined($last)   || $last   eq '' || 
                   5741:         !defined($uid)    || $uid    eq '' || 
                   5742:         !defined($middle) || $middle eq '' || 
                   5743:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5744:         # They did not supply us with enough data to enroll the student, so
                   5745:         # we need to pick up more information.
1.297     matthew  5746:         my %tmp = &get('environment',
1.294     matthew  5747:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5748:                        ,$udom,$uname);
                   5749: 
1.800     albertel 5750:         #foreach my $key (keys(%tmp)) {
                   5751:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5752:         #}
1.294     matthew  5753:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5754:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5755:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5756:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5757:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5758:     }
1.556     albertel 5759:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5760:     my $reply=cput('classlist',
                   5761: 		   {"$uname:$udom" => 
1.515     raeburn  5762: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5763: 		   $cdom,$cnum);
1.81      www      5764:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5765: 	return 'error: '.$reply;
1.652     albertel 5766:     } else {
                   5767: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5768:     }
1.297     matthew  5769:     # Add student role to user
1.83      www      5770:     my $uurl='/'.$cid;
1.81      www      5771:     $uurl=~s/\_/\//g;
                   5772:     if ($usec) {
                   5773: 	$uurl.='/'.$usec;
                   5774:     }
1.957     raeburn  5775:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5776: }
                   5777: 
1.556     albertel 5778: sub format_name {
                   5779:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5780:     my $name;
                   5781:     if ($first ne 'lastname') {
                   5782: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5783:     } else {
                   5784: 	if ($lastname=~/\S/) {
                   5785: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5786: 	    $name=~s/\s+,/,/;
                   5787: 	} else {
                   5788: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5789: 	}
                   5790:     }
                   5791:     $name=~s/^\s+//;
                   5792:     $name=~s/\s+$//;
                   5793:     $name=~s/\s+/ /g;
                   5794:     return $name;
                   5795: }
                   5796: 
1.84      www      5797: # ------------------------------------------------- Write to course preferences
                   5798: 
                   5799: sub writecoursepref {
                   5800:     my ($courseid,%prefs)=@_;
                   5801:     $courseid=~s/^\///;
                   5802:     $courseid=~s/\_/\//g;
                   5803:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5804:     my $chome=homeserver($cnum,$cdomain);
                   5805:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5806: 	return 'error: no such course';
                   5807:     }
                   5808:     my $cstring='';
1.800     albertel 5809:     foreach my $pref (keys(%prefs)) {
                   5810: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5811:     }
1.84      www      5812:     $cstring=~s/\&$//;
                   5813:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5814: }
                   5815: 
                   5816: # ---------------------------------------------------------- Make/modify course
                   5817: 
                   5818: sub createcourse {
1.741     raeburn  5819:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5820:         $course_owner,$crstype)=@_;
1.84      www      5821:     $url=&declutter($url);
                   5822:     my $cid='';
1.264     matthew  5823:     unless (&allowed('ccc',$udom)) {
1.84      www      5824:         return 'refused';
                   5825:     }
                   5826: # ------------------------------------------------------------------- Create ID
1.674     www      5827:    my $uname=int(1+rand(9)).
                   5828:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5829:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5830:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5831: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5832:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5833:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5834:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5835:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5836:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5837:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5838:            return 'error: unable to generate unique course-ID';
                   5839:        } 
                   5840:    }
1.264     matthew  5841: # ------------------------------------------------ Check supplied server name
1.620     albertel 5842:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5843:     if (! &is_library($course_server)) {
1.264     matthew  5844:         return 'error:bad server name '.$course_server;
                   5845:     }
1.84      www      5846: # ------------------------------------------------------------- Make the course
                   5847:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5848:                       $course_server);
1.84      www      5849:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5850:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5851:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5852: 	return 'error: no such course';
                   5853:     }
1.271     www      5854: # ----------------------------------------------------------------- Course made
1.516     raeburn  5855: # log existence
1.918     raeburn  5856:     my $newcourse = {
                   5857:                     $udom.'_'.$uname => {
1.921     raeburn  5858:                                      description => $description,
                   5859:                                      inst_code   => $inst_code,
                   5860:                                      owner       => $course_owner,
                   5861:                                      type        => $crstype,
1.918     raeburn  5862:                                                 },
                   5863:                     };
1.921     raeburn  5864:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5865: # set toplevel url
1.271     www      5866:     my $topurl=$url;
                   5867:     unless ($nonstandard) {
                   5868: # ------------------------------------------ For standard courses, make top url
                   5869:         my $mapurl=&clutter($url);
1.278     www      5870:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5871:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5872: <map>
                   5873: <resource id="1" type="start"></resource>
                   5874: <resource id="2" src="$mapurl"></resource>
                   5875: <resource id="3" type="finish"></resource>
                   5876: <link index="1" from="1" to="2"></link>
                   5877: <link index="2" from="2" to="3"></link>
                   5878: </map>
                   5879: ENDINITMAP
                   5880:         $topurl=&declutter(
1.638     albertel 5881:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5882:                           );
                   5883:     }
                   5884: # ----------------------------------------------------------- Write preferences
1.84      www      5885:     &writecoursepref($udom.'_'.$uname,
                   5886:                      ('description' => $description,
1.271     www      5887:                       'url'         => $topurl));
1.84      www      5888:     return '/'.$udom.'/'.$uname;
                   5889: }
                   5890: 
1.813     albertel 5891: sub is_course {
                   5892:     my ($cdom,$cnum) = @_;
                   5893:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5894: 				undef,'.');
1.813     albertel 5895:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5896:         return 1;
                   5897:     }
                   5898:     return 0;
                   5899: }
                   5900: 
1.21      www      5901: # ---------------------------------------------------------- Assign Custom Role
                   5902: 
                   5903: sub assigncustomrole {
1.957     raeburn  5904:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5905:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  5906:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      5907: }
                   5908: 
                   5909: # ----------------------------------------------------------------- Revoke Role
                   5910: 
                   5911: sub revokerole {
1.957     raeburn  5912:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5913:     my $now=time;
1.965     raeburn  5914:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      5915: }
                   5916: 
                   5917: # ---------------------------------------------------------- Revoke Custom Role
                   5918: 
                   5919: sub revokecustomrole {
1.957     raeburn  5920:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5921:     my $now=time;
1.357     www      5922:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  5923:            $deleteflag,$selfenroll,$context);
1.17      www      5924: }
                   5925: 
1.533     banghart 5926: # ------------------------------------------------------------ Disk usage
1.535     albertel 5927: sub diskusage {
1.955     raeburn  5928:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   5929:     $directorypath =~ s/\/$//;
                   5930:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   5931:                        .&escape($getpropath).':'.&escape($uname).':'
                   5932:                        .&escape($udom),homeserver($uname,$udom));
                   5933:     if ($listing eq 'unknown_cmd') {
                   5934:         if ($getpropath) {
                   5935:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   5936:         }
                   5937:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   5938:     }
1.514     albertel 5939:     return $listing;
1.512     banghart 5940: }
                   5941: 
1.566     banghart 5942: sub is_locked {
                   5943:     my ($file_name, $domain, $user) = @_;
                   5944:     my @check;
                   5945:     my $is_locked;
                   5946:     push @check, $file_name;
1.613     albertel 5947:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5948: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5949:     my ($tmp)=keys(%locked);
                   5950:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5951:     
1.566     banghart 5952:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5953:         $is_locked = 'false';
                   5954:         foreach my $entry (@{$locked{$file_name}}) {
                   5955:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5956:                $is_locked = 'true';
                   5957:                last;
1.745     raeburn  5958:            }
                   5959:        }
1.566     banghart 5960:     } else {
                   5961:         $is_locked = 'false';
                   5962:     }
                   5963: }
                   5964: 
1.759     albertel 5965: sub declutter_portfile {
                   5966:     my ($file) = @_;
1.833     albertel 5967:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5968:     return $file;
                   5969: }
                   5970: 
1.559     banghart 5971: # ------------------------------------------------------------- Mark as Read Only
                   5972: 
                   5973: sub mark_as_readonly {
                   5974:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5975:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5976:     my ($tmp)=keys(%current_permissions);
                   5977:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5978:     foreach my $file (@{$files}) {
1.759     albertel 5979: 	$file = &declutter_portfile($file);
1.561     banghart 5980:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5981:     }
1.613     albertel 5982:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5983:     return;
                   5984: }
                   5985: 
1.572     banghart 5986: # ------------------------------------------------------------Save Selected Files
                   5987: 
                   5988: sub save_selected_files {
                   5989:     my ($user, $path, @files) = @_;
                   5990:     my $filename = $user."savedfiles";
1.573     banghart 5991:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5992:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5993:     foreach my $file (@files) {
1.620     albertel 5994:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5995:     }
                   5996:     foreach my $file (@other_files) {
1.574     banghart 5997:         print (OUT $file."\n");
1.572     banghart 5998:     }
1.574     banghart 5999:     close (OUT);
1.572     banghart 6000:     return 'ok';
                   6001: }
                   6002: 
1.574     banghart 6003: sub clear_selected_files {
                   6004:     my ($user) = @_;
                   6005:     my $filename = $user."savedfiles";
                   6006:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6007:     print (OUT undef);
                   6008:     close (OUT);
                   6009:     return ("ok");    
                   6010: }
                   6011: 
1.572     banghart 6012: sub files_in_path {
                   6013:     my ($user, $path) = @_;
                   6014:     my $filename = $user."savedfiles";
                   6015:     my %return_files;
1.574     banghart 6016:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6017:     while (my $line_in = <IN>) {
1.574     banghart 6018:         chomp ($line_in);
                   6019:         my @paths_and_file = split (m!/!, $line_in);
                   6020:         my $file_part = pop (@paths_and_file);
                   6021:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6022:         $path_part.='/';
                   6023:         my $path_and_file = $path_part.$file_part;
                   6024:         if ($path_part eq $path) {
                   6025:             $return_files{$file_part}= 'selected';
                   6026:         }
                   6027:     }
1.574     banghart 6028:     close (IN);
                   6029:     return (\%return_files);
1.572     banghart 6030: }
                   6031: 
                   6032: # called in portfolio select mode, to show files selected NOT in current directory
                   6033: sub files_not_in_path {
                   6034:     my ($user, $path) = @_;
                   6035:     my $filename = $user."savedfiles";
                   6036:     my @return_files;
                   6037:     my $path_part;
1.800     albertel 6038:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6039:     while (my $line = <IN>) {
1.572     banghart 6040:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6041:         my @paths_and_file = split(m|/|, $line);
                   6042:         my $file_part = pop(@paths_and_file);
                   6043:         chomp($file_part);
                   6044:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6045:         $path_part .= '/';
                   6046:         my $path_and_file = $path_part.$file_part;
                   6047:         if ($path_part ne $path) {
1.800     albertel 6048:             push(@return_files, ($path_and_file));
1.572     banghart 6049:         }
                   6050:     }
1.800     albertel 6051:     close(OUT);
1.574     banghart 6052:     return (@return_files);
1.572     banghart 6053: }
                   6054: 
1.745     raeburn  6055: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6056: 
1.745     raeburn  6057: sub get_portfile_permissions {
                   6058:     my ($domain,$user) = @_;
1.613     albertel 6059:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6060:     my ($tmp)=keys(%current_permissions);
                   6061:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6062:     return \%current_permissions;
                   6063: }
                   6064: 
                   6065: #---------------------------------------------Get portfolio file access controls
                   6066: 
1.749     raeburn  6067: sub get_access_controls {
1.745     raeburn  6068:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6069:     my %access;
                   6070:     my $real_file = $file;
                   6071:     $file =~ s/\.meta$//;
1.745     raeburn  6072:     if (defined($file)) {
1.749     raeburn  6073:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6074:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6075:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6076:             }
                   6077:         }
1.745     raeburn  6078:     } else {
1.749     raeburn  6079:         foreach my $key (keys(%{$current_permissions})) {
                   6080:             if ($key =~ /\0accesscontrol$/) {
                   6081:                 if (defined($group)) {
                   6082:                     if ($key !~ m-^\Q$group\E/-) {
                   6083:                         next;
                   6084:                     }
                   6085:                 }
                   6086:                 my ($fullpath) = split(/\0/,$key);
                   6087:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6088:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6089:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6090:                     }
                   6091:                 }
                   6092:             }
                   6093:         }
                   6094:     }
                   6095:     return %access;
                   6096: }
                   6097: 
                   6098: sub modify_access_controls {
                   6099:     my ($file_name,$changes,$domain,$user)=@_;
                   6100:     my ($outcome,$deloutcome);
                   6101:     my %store_permissions;
                   6102:     my %new_values;
                   6103:     my %new_control;
                   6104:     my %translation;
                   6105:     my @deletions = ();
                   6106:     my $now = time;
                   6107:     if (exists($$changes{'activate'})) {
                   6108:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6109:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6110:             my $numnew = scalar(@newitems);
                   6111:             for (my $i=0; $i<$numnew; $i++) {
                   6112:                 my $newkey = $newitems[$i];
                   6113:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6114:                 if ($newkey =~ /^\d+:/) { 
                   6115:                     $newkey =~ s/^(\d+)/$newid/;
                   6116:                     $translation{$1} = $newid;
                   6117:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6118:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6119:                     $translation{$1} = $newid;
                   6120:                 }
1.749     raeburn  6121:                 $new_values{$file_name."\0".$newkey} = 
                   6122:                                           $$changes{'activate'}{$newitems[$i]};
                   6123:                 $new_control{$newkey} = $now;
                   6124:             }
                   6125:         }
                   6126:     }
                   6127:     my %todelete;
                   6128:     my %changed_items;
                   6129:     foreach my $action ('delete','update') {
                   6130:         if (exists($$changes{$action})) {
                   6131:             if (ref($$changes{$action}) eq 'HASH') {
                   6132:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6133:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6134:                     if ($action eq 'delete') { 
                   6135:                         $todelete{$itemnum} = 1;
                   6136:                     } else {
                   6137:                         $changed_items{$itemnum} = $key;
                   6138:                     }
                   6139:                 }
1.745     raeburn  6140:             }
                   6141:         }
1.749     raeburn  6142:     }
                   6143:     # get lock on access controls for file.
                   6144:     my $lockhash = {
                   6145:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6146:                                                        ':'.$env{'user.domain'},
                   6147:                    }; 
                   6148:     my $tries = 0;
                   6149:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6150:    
                   6151:     while (($gotlock ne 'ok') && $tries <3) {
                   6152:         $tries ++;
                   6153:         sleep 1;
                   6154:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6155:     }
                   6156:     if ($gotlock eq 'ok') {
                   6157:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6158:         my ($tmp)=keys(%curr_permissions);
                   6159:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6160:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6161:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6162:             if (ref($curr_controls) eq 'HASH') {
                   6163:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6164:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6165:                     if (defined($todelete{$itemnum})) {
                   6166:                         push(@deletions,$file_name."\0".$control_item);
                   6167:                     } else {
                   6168:                         if (defined($changed_items{$itemnum})) {
                   6169:                             $new_control{$changed_items{$itemnum}} = $now;
                   6170:                             push(@deletions,$file_name."\0".$control_item);
                   6171:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6172:                         } else {
                   6173:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6174:                         }
                   6175:                     }
1.745     raeburn  6176:                 }
                   6177:             }
                   6178:         }
1.970     raeburn  6179:         my ($group);
                   6180:         if (&is_course($domain,$user)) {
                   6181:             ($group,my $file) = split(/\//,$file_name,2);
                   6182:         }
1.749     raeburn  6183:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6184:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6185:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6186:         #  remove lock
                   6187:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6188:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6189:         my $sqlresult =
1.970     raeburn  6190:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6191:                                     $group);
1.749     raeburn  6192:     } else {
                   6193:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6194:     }
1.749     raeburn  6195:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6196: }
                   6197: 
1.827     raeburn  6198: sub make_public_indefinitely {
                   6199:     my ($requrl) = @_;
                   6200:     my $now = time;
                   6201:     my $action = 'activate';
                   6202:     my $aclnum = 0;
                   6203:     if (&is_portfolio_url($requrl)) {
                   6204:         my (undef,$udom,$unum,$file_name,$group) =
                   6205:             &parse_portfolio_url($requrl);
                   6206:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6207:         my %access_controls = &get_access_controls($current_perms,
                   6208:                                                    $group,$file_name);
                   6209:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6210:             my ($num,$scope,$end,$start) = 
                   6211:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6212:             if ($scope eq 'public') {
                   6213:                 if ($start <= $now && $end == 0) {
                   6214:                     $action = 'none';
                   6215:                 } else {
                   6216:                     $action = 'update';
                   6217:                     $aclnum = $num;
                   6218:                 }
                   6219:                 last;
                   6220:             }
                   6221:         }
                   6222:         if ($action eq 'none') {
                   6223:              return 'ok';
                   6224:         } else {
                   6225:             my %changes;
                   6226:             my $newend = 0;
                   6227:             my $newstart = $now;
                   6228:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6229:             $changes{$action}{$newkey} = {
                   6230:                 type => 'public',
                   6231:                 time => {
                   6232:                     start => $newstart,
                   6233:                     end   => $newend,
                   6234:                 },
                   6235:             };
                   6236:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6237:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6238:             return $outcome;
                   6239:         }
                   6240:     } else {
                   6241:         return 'invalid';
                   6242:     }
                   6243: }
                   6244: 
1.745     raeburn  6245: #------------------------------------------------------Get Marked as Read Only
                   6246: 
                   6247: sub get_marked_as_readonly {
                   6248:     my ($domain,$user,$what,$group) = @_;
                   6249:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6250:     my @readonly_files;
1.629     banghart 6251:     my $cmp1=$what;
                   6252:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6253:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6254:         if (defined($group)) {
                   6255:             if ($file_name !~ m-^\Q$group\E/-) {
                   6256:                 next;
                   6257:             }
                   6258:         }
1.561     banghart 6259:         if (ref($value) eq "ARRAY"){
                   6260:             foreach my $stored_what (@{$value}) {
1.629     banghart 6261:                 my $cmp2=$stored_what;
1.759     albertel 6262:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6263:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6264:                 }
1.629     banghart 6265:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6266:                     push(@readonly_files, $file_name);
1.745     raeburn  6267:                     last;
1.563     banghart 6268:                 } elsif (!defined($what)) {
                   6269:                     push(@readonly_files, $file_name);
1.745     raeburn  6270:                     last;
1.561     banghart 6271:                 }
                   6272:             }
1.745     raeburn  6273:         }
1.561     banghart 6274:     }
                   6275:     return @readonly_files;
                   6276: }
1.577     banghart 6277: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6278: 
1.577     banghart 6279: sub get_marked_as_readonly_hash {
1.745     raeburn  6280:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6281:     my %readonly_files;
1.745     raeburn  6282:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6283:         if (defined($group)) {
                   6284:             if ($file_name !~ m-^\Q$group\E/-) {
                   6285:                 next;
                   6286:             }
                   6287:         }
1.577     banghart 6288:         if (ref($value) eq "ARRAY"){
                   6289:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6290:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6291:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6292:                         if ($lock_descriptor eq 'graded') {
                   6293:                             $readonly_files{$file_name} = 'graded';
                   6294:                         } elsif ($lock_descriptor eq 'handback') {
                   6295:                             $readonly_files{$file_name} = 'handback';
                   6296:                         } else {
                   6297:                             if (!exists($readonly_files{$file_name})) {
                   6298:                                 $readonly_files{$file_name} = 'locked';
                   6299:                             }
                   6300:                         }
1.745     raeburn  6301:                     }
1.750     banghart 6302:                 } 
1.577     banghart 6303:             }
                   6304:         } 
                   6305:     }
                   6306:     return %readonly_files;
                   6307: }
1.559     banghart 6308: # ------------------------------------------------------------ Unmark as Read Only
                   6309: 
                   6310: sub unmark_as_readonly {
1.629     banghart 6311:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6312:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6313:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6314:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6315:     my $symb_crs = $what;
                   6316:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6317:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6318:     my ($tmp)=keys(%current_permissions);
                   6319:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6320:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6321:     foreach my $file (@readonly_files) {
1.759     albertel 6322: 	my $clean_file = &declutter_portfile($file);
                   6323: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6324: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6325:         my @new_locks;
                   6326:         my @del_keys;
                   6327:         if (ref($current_locks) eq "ARRAY"){
                   6328:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6329:                 my $compare=$locker;
1.749     raeburn  6330:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6331:                     $compare=join('',@{$locker});
1.746     raeburn  6332:                     if ($compare ne $symb_crs) {
                   6333:                         push(@new_locks, $locker);
                   6334:                     }
1.563     banghart 6335:                 }
                   6336:             }
1.650     albertel 6337:             if (scalar(@new_locks) > 0) {
1.563     banghart 6338:                 $current_permissions{$file} = \@new_locks;
                   6339:             } else {
                   6340:                 push(@del_keys, $file);
1.613     albertel 6341:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6342:                 delete($current_permissions{$file});
1.563     banghart 6343:             }
                   6344:         }
1.561     banghart 6345:     }
1.613     albertel 6346:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6347:     return;
                   6348: }
1.512     banghart 6349: 
1.17      www      6350: # ------------------------------------------------------------ Directory lister
                   6351: 
                   6352: sub dirlist {
1.955     raeburn  6353:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6354:     $uri=~s/^\///;
                   6355:     $uri=~s/\/$//;
1.253     stredwic 6356:     my ($udom, $uname);
1.955     raeburn  6357:     if ($getuserdir) {
1.253     stredwic 6358:         $udom = $userdomain;
                   6359:         $uname = $username;
1.955     raeburn  6360:     } else {
                   6361:         (undef,$udom,$uname)=split(/\//,$uri);
                   6362:         if(defined($userdomain)) {
                   6363:             $udom = $userdomain;
                   6364:         }
                   6365:         if(defined($username)) {
                   6366:             $uname = $username;
                   6367:         }
1.253     stredwic 6368:     }
1.955     raeburn  6369:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6370: 
1.955     raeburn  6371:     $dirRoot = $perlvar{'lonDocRoot'};
                   6372:     if (defined($getpropath)) {
                   6373:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6374:         $dirRoot =~ s/\/$//;
1.955     raeburn  6375:     } elsif (defined($getuserdir)) {
                   6376:         my $subdir=$uname.'__';
                   6377:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6378:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6379:                    ."/$udom/$subdir/$uname";
                   6380:     } elsif (defined($alternateRoot)) {
                   6381:         $dirRoot = $alternateRoot;
1.751     banghart 6382:     }
1.253     stredwic 6383: 
                   6384:     if($udom) {
                   6385:         if($uname) {
1.955     raeburn  6386:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6387:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6388:                               .':'.&escape($uname).':'.&escape($udom),
                   6389:                               &homeserver($uname,$udom));
                   6390:             if ($listing eq 'unknown_cmd') {
                   6391:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6392:                                   &homeserver($uname,$udom));
                   6393:             } else {
                   6394:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6395:             }
1.605     matthew  6396:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6397:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6398: 				  &homeserver($uname,$udom));
1.605     matthew  6399:                 @listing_results = split(/:/,$listing);
                   6400:             } else {
                   6401:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6402:             }
                   6403:             return @listing_results;
1.955     raeburn  6404:         } elsif(!$alternateRoot) {
1.800     albertel 6405:             my %allusers;
1.841     albertel 6406: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6407:  	    foreach my $tryserver (keys(%servers)) {
                   6408:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6409:                                   &escape($udom),$tryserver);
                   6410:                 if ($listing eq 'unknown_cmd') {
                   6411: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6412: 				      $udom, $tryserver);
                   6413:                 } else {
                   6414:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6415:                 }
1.841     albertel 6416: 		if ($listing eq 'unknown_cmd') {
                   6417: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6418: 				      $udom, $tryserver);
                   6419: 		    @listing_results = split(/:/,$listing);
                   6420: 		} else {
                   6421: 		    @listing_results =
                   6422: 			map { &unescape($_); } split(/:/,$listing);
                   6423: 		}
                   6424: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6425: 		    $listing_results[0] ne 'empty'       &&
                   6426: 		    $listing_results[0] ne 'con_lost') {
                   6427: 		    foreach my $line (@listing_results) {
                   6428: 			my ($entry) = split(/&/,$line,2);
                   6429: 			$allusers{$entry} = 1;
                   6430: 		    }
                   6431: 		}
1.253     stredwic 6432:             }
                   6433:             my $alluserstr='';
1.800     albertel 6434:             foreach my $user (sort(keys(%allusers))) {
                   6435:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6436:             }
                   6437:             $alluserstr=~s/:$//;
                   6438:             return split(/:/,$alluserstr);
                   6439:         } else {
1.800     albertel 6440:             return ('missing user name');
1.253     stredwic 6441:         }
1.955     raeburn  6442:     } elsif(!defined($getpropath)) {
1.841     albertel 6443:         my @all_domains = sort(&all_domains());
1.955     raeburn  6444:         foreach my $domain (@all_domains) {
                   6445:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6446:         }
                   6447:         return @all_domains;
                   6448:     } else {
1.800     albertel 6449:         return ('missing domain');
1.275     stredwic 6450:     }
                   6451: }
                   6452: 
                   6453: # --------------------------------------------- GetFileTimestamp
                   6454: # This function utilizes dirlist and returns the date stamp for
                   6455: # when it was last modified.  It will also return an error of -1
                   6456: # if an error occurs
                   6457: 
                   6458: sub GetFileTimestamp {
1.955     raeburn  6459:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6460:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6461:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6462:     my ($fileStat) = 
                   6463:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6464:                                  undef,$getuserdir);
1.275     stredwic 6465:     my @stats = split('&', $fileStat);
                   6466:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6467:         # @stats contains first the filename, then the stat output
                   6468:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6469:     } else {
                   6470:         return -1;
1.253     stredwic 6471:     }
1.26      www      6472: }
                   6473: 
1.712     albertel 6474: sub stat_file {
                   6475:     my ($uri) = @_;
1.787     albertel 6476:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6477: 
1.955     raeburn  6478:     my ($udom,$uname,$file);
1.712     albertel 6479:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6480: 	($udom,$uname,$file) =
1.811     albertel 6481: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6482: 	$file = 'userfiles/'.$file;
                   6483:     }
                   6484:     if ($uri =~ m-^/res/-) {
                   6485: 	($udom,$uname) = 
1.807     albertel 6486: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6487: 	$file = $uri;
                   6488:     }
                   6489: 
                   6490:     if (!$udom || !$uname || !$file) {
                   6491: 	# unable to handle the uri
                   6492: 	return ();
                   6493:     }
1.956     raeburn  6494:     my $getpropath;
                   6495:     if ($file =~ /^userfiles\//) {
                   6496:         $getpropath = 1;
                   6497:     }
1.955     raeburn  6498:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6499:     my @stats = split('&', $result);
1.721     banghart 6500:     
1.712     albertel 6501:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6502: 	shift(@stats); #filename is first
                   6503: 	return @stats;
                   6504:     }
                   6505:     return ();
                   6506: }
                   6507: 
1.26      www      6508: # -------------------------------------------------------- Value of a Condition
                   6509: 
1.713     albertel 6510: # gets the value of a specific preevaluated condition
                   6511: #    stored in the string  $env{user.state.<cid>}
                   6512: # or looks up a condition reference in the bighash and if if hasn't
                   6513: # already been evaluated recurses into docondval to get the value of
                   6514: # the condition, then memoizing it to 
                   6515: #   $env{user.state.<cid>.<condition>}
1.40      www      6516: sub directcondval {
                   6517:     my $number=shift;
1.620     albertel 6518:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6519: 	&Apache::lonuserstate::evalstate();
                   6520:     }
1.713     albertel 6521:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6522: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6523:     } elsif ($number =~ /^_/) {
                   6524: 	my $sub_condition;
                   6525: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6526: 		&GDBM_READER(),0640)) {
                   6527: 	    $sub_condition=$bighash{'conditions'.$number};
                   6528: 	    untie(%bighash);
                   6529: 	}
                   6530: 	my $value = &docondval($sub_condition);
1.949     raeburn  6531: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6532: 	return $value;
                   6533:     }
1.620     albertel 6534:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6535:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6536:     } else {
                   6537:        return 2;
                   6538:     }
                   6539: }
                   6540: 
1.713     albertel 6541: # get the collection of conditions for this resource
1.26      www      6542: sub condval {
                   6543:     my $condidx=shift;
1.54      www      6544:     my $allpathcond='';
1.713     albertel 6545:     foreach my $cond (split(/\|/,$condidx)) {
                   6546: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6547: 	    $allpathcond.=
                   6548: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6549: 	}
1.191     harris41 6550:     }
1.54      www      6551:     $allpathcond=~s/\|$//;
1.713     albertel 6552:     return &docondval($allpathcond);
                   6553: }
                   6554: 
                   6555: #evaluates an expression of conditions
                   6556: sub docondval {
                   6557:     my ($allpathcond) = @_;
                   6558:     my $result=0;
                   6559:     if ($env{'request.course.id'}
                   6560: 	&& defined($allpathcond)) {
                   6561: 	my $operand='|';
                   6562: 	my @stack;
                   6563: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6564: 	    if ($chunk eq '(') {
                   6565: 		push @stack,($operand,$result);
                   6566: 	    } elsif ($chunk eq ')') {
                   6567: 		my $before=pop @stack;
                   6568: 		if (pop @stack eq '&') {
                   6569: 		    $result=$result>$before?$before:$result;
                   6570: 		} else {
                   6571: 		    $result=$result>$before?$result:$before;
                   6572: 		}
                   6573: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6574: 		$operand=$chunk;
                   6575: 	    } else {
                   6576: 		my $new=directcondval($chunk);
                   6577: 		if ($operand eq '&') {
                   6578: 		    $result=$result>$new?$new:$result;
                   6579: 		} else {
                   6580: 		    $result=$result>$new?$result:$new;
                   6581: 		}
                   6582: 	    }
                   6583: 	}
1.26      www      6584:     }
                   6585:     return $result;
1.421     albertel 6586: }
                   6587: 
                   6588: # ---------------------------------------------------- Devalidate courseresdata
                   6589: 
                   6590: sub devalidatecourseresdata {
                   6591:     my ($coursenum,$coursedomain)=@_;
                   6592:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6593:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6594: }
                   6595: 
1.763     www      6596: 
1.200     www      6597: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6598: #
                   6599: #  Parameters:
                   6600: #      $coursenum    - Number of the course.
                   6601: #      $coursedomain - Domain at which the course was created.
                   6602: #  Returns:
                   6603: #     A hash of the course parameters along (I think) with timestamps
                   6604: #     and version info.
1.877     foxr     6605: 
1.624     albertel 6606: sub get_courseresdata {
                   6607:     my ($coursenum,$coursedomain)=@_;
1.200     www      6608:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6609:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6610:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6611:     my %dumpreply;
1.417     albertel 6612:     unless (defined($cached)) {
1.624     albertel 6613: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6614: 	$result=\%dumpreply;
1.251     albertel 6615: 	my ($tmp) = keys(%dumpreply);
                   6616: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6617: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6618: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6619: 	    return $tmp;
1.416     albertel 6620: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6621: 	    $result=undef;
1.599     albertel 6622: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6623: 	}
                   6624:     }
1.624     albertel 6625:     return $result;
                   6626: }
                   6627: 
1.633     albertel 6628: sub devalidateuserresdata {
                   6629:     my ($uname,$udom)=@_;
                   6630:     my $hashid="$udom:$uname";
                   6631:     &devalidate_cache_new('userres',$hashid);
                   6632: }
                   6633: 
1.624     albertel 6634: sub get_userresdata {
                   6635:     my ($uname,$udom)=@_;
                   6636:     #most student don\'t have any data set, check if there is some data
                   6637:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6638: 
                   6639:     my $hashid="$udom:$uname";
                   6640:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6641:     if (!defined($cached)) {
                   6642: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6643: 	$result=\%resourcedata;
                   6644: 	&do_cache_new('userres',$hashid,$result,600);
                   6645:     }
                   6646:     my ($tmp)=keys(%$result);
                   6647:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6648: 	return $result;
                   6649:     }
                   6650:     #error 2 occurs when the .db doesn't exist
                   6651:     if ($tmp!~/error: 2 /) {
1.672     albertel 6652: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6653: 		 " Trying to get resource data for ".
                   6654: 		 $uname." at ".$udom.": ".
                   6655: 		 $tmp."</font>");
                   6656:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6657: 	#&EXT_cache_set($udom,$uname);
                   6658: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6659: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6660:     }
                   6661:     return $tmp;
                   6662: }
1.879     foxr     6663: #----------------------------------------------- resdata - return resource data
                   6664: #  Purpose:
                   6665: #    Return resource data for either users or for a course.
                   6666: #  Parameters:
                   6667: #     $name      - Course/user name.
                   6668: #     $domain    - Name of the domain the user/course is registered on.
                   6669: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6670: #     @which     - Array of names of resources desired.
                   6671: #  Returns:
                   6672: #     The value of the first reasource in @which that is found in the
                   6673: #     resource hash.
                   6674: #  Exceptional Conditions:
                   6675: #     If the $type passed in is not valid (not the string 'course' or 
                   6676: #     'user', an undefined  reference is returned.
                   6677: #     If none of the resources are found, an undef is returned
1.624     albertel 6678: sub resdata {
                   6679:     my ($name,$domain,$type,@which)=@_;
                   6680:     my $result;
                   6681:     if ($type eq 'course') {
                   6682: 	$result=&get_courseresdata($name,$domain);
                   6683:     } elsif ($type eq 'user') {
                   6684: 	$result=&get_userresdata($name,$domain);
                   6685:     }
                   6686:     if (!ref($result)) { return $result; }    
1.251     albertel 6687:     foreach my $item (@which) {
1.927     albertel 6688: 	if (defined($result->{$item->[0]})) {
                   6689: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6690: 	}
1.250     albertel 6691:     }
1.291     albertel 6692:     return undef;
1.200     www      6693: }
                   6694: 
1.379     matthew  6695: #
                   6696: # EXT resource caching routines
                   6697: #
                   6698: 
                   6699: sub clear_EXT_cache_status {
1.383     albertel 6700:     &delenv('cache.EXT.');
1.379     matthew  6701: }
                   6702: 
                   6703: sub EXT_cache_status {
                   6704:     my ($target_domain,$target_user) = @_;
1.383     albertel 6705:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6706:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6707:         # We know already the user has no data
                   6708:         return 1;
                   6709:     } else {
                   6710:         return 0;
                   6711:     }
                   6712: }
                   6713: 
                   6714: sub EXT_cache_set {
                   6715:     my ($target_domain,$target_user) = @_;
1.383     albertel 6716:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6717:     #&appenv({$cachename => time});
1.379     matthew  6718: }
                   6719: 
1.28      www      6720: # --------------------------------------------------------- Value of a Variable
1.58      www      6721: sub EXT {
1.715     albertel 6722: 
1.395     albertel 6723:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6724:     unless ($varname) { return ''; }
1.218     albertel 6725:     #get real user name/domain, courseid and symb
                   6726:     my $courseid;
1.359     albertel 6727:     my $publicuser;
1.427     www      6728:     if ($symbparm) {
                   6729: 	$symbparm=&get_symb_from_alias($symbparm);
                   6730:     }
1.218     albertel 6731:     if (!($uname && $udom)) {
1.790     albertel 6732:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6733:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6734:     } else {
1.620     albertel 6735: 	$courseid=$env{'request.course.id'};
1.218     albertel 6736:     }
1.48      www      6737:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6738:     my $rest;
1.320     albertel 6739:     if (defined($therest[0])) {
1.48      www      6740:        $rest=join('.',@therest);
                   6741:     } else {
                   6742:        $rest='';
                   6743:     }
1.320     albertel 6744: 
1.57      www      6745:     my $qualifierrest=$qualifier;
                   6746:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6747:     my $spacequalifierrest=$space;
                   6748:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6749:     if ($realm eq 'user') {
1.48      www      6750: # --------------------------------------------------------------- user.resource
                   6751: 	if ($space eq 'resource') {
1.651     albertel 6752: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6753: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6754: 		 &&
1.744     albertel 6755: 		 ($symbparm eq &symbread()) ) {	
                   6756: 		# if we are in the middle of processing the resource the
                   6757: 		# get the value we are planning on committing
                   6758:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6759:                     return $Apache::lonhomework::results{$qualifierrest};
                   6760:                 } else {
                   6761:                     return $Apache::lonhomework::history{$qualifierrest};
                   6762:                 }
1.335     albertel 6763: 	    } else {
1.359     albertel 6764: 		my %restored;
1.620     albertel 6765: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6766: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6767: 		} else {
                   6768: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6769: 		}
1.335     albertel 6770: 		return $restored{$qualifierrest};
                   6771: 	    }
1.48      www      6772: # ----------------------------------------------------------------- user.access
                   6773:         } elsif ($space eq 'access') {
1.218     albertel 6774: 	    # FIXME - not supporting calls for a specific user
1.48      www      6775:             return &allowed($qualifier,$rest);
                   6776: # ------------------------------------------ user.preferences, user.environment
                   6777:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6778: 	    if (($uname eq $env{'user.name'}) &&
                   6779: 		($udom eq $env{'user.domain'})) {
                   6780: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6781: 	    } else {
1.359     albertel 6782: 		my %returnhash;
                   6783: 		if (!$publicuser) {
                   6784: 		    %returnhash=&userenvironment($udom,$uname,
                   6785: 						 $qualifierrest);
                   6786: 		}
1.218     albertel 6787: 		return $returnhash{$qualifierrest};
                   6788: 	    }
1.48      www      6789: # ----------------------------------------------------------------- user.course
                   6790:         } elsif ($space eq 'course') {
1.218     albertel 6791: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6792:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6793: # ------------------------------------------------------------------- user.role
                   6794:         } elsif ($space eq 'role') {
1.218     albertel 6795: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6796:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6797:             if ($qualifier eq 'value') {
                   6798: 		return $role;
                   6799:             } elsif ($qualifier eq 'extent') {
                   6800:                 return $where;
                   6801:             }
                   6802: # ----------------------------------------------------------------- user.domain
                   6803:         } elsif ($space eq 'domain') {
1.218     albertel 6804:             return $udom;
1.48      www      6805: # ------------------------------------------------------------------- user.name
                   6806:         } elsif ($space eq 'name') {
1.218     albertel 6807:             return $uname;
1.48      www      6808: # ---------------------------------------------------- Any other user namespace
1.29      www      6809:         } else {
1.359     albertel 6810: 	    my %reply;
                   6811: 	    if (!$publicuser) {
                   6812: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6813: 	    }
                   6814: 	    return $reply{$qualifierrest};
1.48      www      6815:         }
1.236     www      6816:     } elsif ($realm eq 'query') {
                   6817: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6818:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6819: 						[$spacequalifierrest]);
1.620     albertel 6820: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6821:    } elsif ($realm eq 'request') {
1.48      www      6822: # ------------------------------------------------------------- request.browser
                   6823:         if ($space eq 'browser') {
1.430     www      6824: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6825: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6826: 		    return 1;
                   6827: 		} else {
                   6828: 		    return 0;
                   6829: 		}
                   6830: 	    } else {
1.620     albertel 6831: 		return $env{'browser.'.$qualifier};
1.430     www      6832: 	    }
1.57      www      6833: # ------------------------------------------------------------ request.filename
                   6834:         } else {
1.620     albertel 6835:             return $env{'request.'.$spacequalifierrest};
1.29      www      6836:         }
1.28      www      6837:     } elsif ($realm eq 'course') {
1.48      www      6838: # ---------------------------------------------------------- course.description
1.620     albertel 6839:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6840:     } elsif ($realm eq 'resource') {
1.165     www      6841: 
1.620     albertel 6842: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6843: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6844: 	}
1.693     albertel 6845: 
                   6846: 	if ($space eq 'title') {
                   6847: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6848: 	    return &gettitle($symbparm);
                   6849: 	}
                   6850: 	
                   6851: 	if ($space eq 'map') {
                   6852: 	    my ($map) = &decode_symb($symbparm);
                   6853: 	    return &symbread($map);
                   6854: 	}
1.905     albertel 6855: 	if ($space eq 'filename') {
                   6856: 	    if ($symbparm) {
                   6857: 		return &clutter((&decode_symb($symbparm))[2]);
                   6858: 	    }
                   6859: 	    return &hreflocation('',$env{'request.filename'});
                   6860: 	}
1.693     albertel 6861: 
                   6862: 	my ($section, $group, @groups);
1.593     albertel 6863: 	my ($courselevelm,$courselevel);
1.539     albertel 6864: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6865: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6866: 
1.218     albertel 6867: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6868: 
1.60      www      6869: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6870: 	    my $symbp=$symbparm;
1.735     albertel 6871: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6872: 
                   6873: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6874: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6875: 
1.620     albertel 6876: 	    if (($env{'user.name'} eq $uname) &&
                   6877: 		($env{'user.domain'} eq $udom)) {
                   6878: 		$section=$env{'request.course.sec'};
1.733     raeburn  6879:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6880:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6881: 	    } else {
1.539     albertel 6882: 		if (! defined($usection)) {
1.551     albertel 6883: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6884: 		} else {
                   6885: 		    $section = $usection;
                   6886: 		}
1.733     raeburn  6887:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6888: 	    }
                   6889: 
                   6890: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6891: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6892: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6893: 
1.593     albertel 6894: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6895: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6896: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6897: 
1.60      www      6898: # ----------------------------------------------------------- first, check user
1.624     albertel 6899: 
                   6900: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6901: 				       ([$courselevelr,'resource'],
                   6902: 					[$courselevelm,'map'     ],
                   6903: 					[$courselevel, 'course'  ]));
1.931     albertel 6904: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6905: 
1.594     albertel 6906: # ------------------------------------------------ second, check some of course
1.684     raeburn  6907:             my $coursereply;
1.691     raeburn  6908:             if (@groups > 0) {
                   6909:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6910:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6911:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6912:             }
1.96      www      6913: 
1.684     raeburn  6914: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6915: 				  $env{'course.'.$courseid.'.domain'},
                   6916: 				  'course',
                   6917: 				  ([$seclevelr,   'resource'],
                   6918: 				   [$seclevelm,   'map'     ],
                   6919: 				   [$seclevel,    'course'  ],
                   6920: 				   [$courselevelr,'resource']));
                   6921: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6922: 
1.60      www      6923: # ------------------------------------------------------ third, check map parms
1.218     albertel 6924: 	    my %parmhash=();
                   6925: 	    my $thisparm='';
                   6926: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6927: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6928: 		    &GDBM_READER(),0640)) {
1.218     albertel 6929: 		$thisparm=$parmhash{$symbparm};
                   6930: 		untie(%parmhash);
                   6931: 	    }
1.927     albertel 6932: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6933: 	}
1.594     albertel 6934: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6935: 
1.218     albertel 6936: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6937: 	my $filename;
                   6938: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6939: 	if ($symbparm) {
1.409     www      6940: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6941: 	} else {
1.620     albertel 6942: 	    $filename=$env{'request.filename'};
1.282     albertel 6943: 	}
                   6944: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6945: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6946: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6947: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6948: 
1.927     albertel 6949: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6950: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6951: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6952: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6953: 				     $env{'course.'.$courseid.'.domain'},
                   6954: 				     'course',
1.927     albertel 6955: 				     ([$courselevelm,'map'   ],
                   6956: 				      [$courselevel, 'course']));
                   6957: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6958: 	}
1.145     www      6959: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6960: 	unless ($space eq '0') {
1.336     albertel 6961: 	    my @parts=split(/_/,$space);
                   6962: 	    my $id=pop(@parts);
                   6963: 	    my $part=join('_',@parts);
                   6964: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6965: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6966: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6967: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6968: 	}
1.395     albertel 6969: 	if ($recurse) { return undef; }
                   6970: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6971: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6972: # ---------------------------------------------------- Any other user namespace
                   6973:     } elsif ($realm eq 'environment') {
                   6974: # ----------------------------------------------------------------- environment
1.620     albertel 6975: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6976: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6977: 	} else {
1.770     albertel 6978: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6979: 		return '';
                   6980: 	    }
1.219     albertel 6981: 	    my %returnhash=&userenvironment($udom,$uname,
                   6982: 					    $spacequalifierrest);
                   6983: 	    return $returnhash{$spacequalifierrest};
                   6984: 	}
1.28      www      6985:     } elsif ($realm eq 'system') {
1.48      www      6986: # ----------------------------------------------------------------- system.time
                   6987: 	if ($space eq 'time') {
                   6988: 	    return time;
                   6989:         }
1.696     albertel 6990:     } elsif ($realm eq 'server') {
                   6991: # ----------------------------------------------------------------- system.time
                   6992: 	if ($space eq 'name') {
                   6993: 	    return $ENV{'SERVER_NAME'};
                   6994:         }
1.28      www      6995:     }
1.48      www      6996:     return '';
1.61      www      6997: }
                   6998: 
1.927     albertel 6999: sub get_reply {
                   7000:     my ($reply_value) = @_;
1.940     raeburn  7001:     if (ref($reply_value) eq 'ARRAY') {
                   7002:         if (wantarray) {
                   7003: 	    return @$reply_value;
                   7004:         }
                   7005:         return $reply_value->[0];
                   7006:     } else {
                   7007:         return $reply_value;
1.927     albertel 7008:     }
                   7009: }
                   7010: 
1.691     raeburn  7011: sub check_group_parms {
                   7012:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7013:     my @groupitems = ();
                   7014:     my $resultitem;
1.927     albertel 7015:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7016:     foreach my $group (@{$groups}) {
                   7017:         foreach my $level (@levels) {
1.927     albertel 7018:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7019:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7020:         }
                   7021:     }
                   7022:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7023:                             $env{'course.'.$courseid.'.domain'},
                   7024:                                      'course',@groupitems);
                   7025:     return $coursereply;
                   7026: }
                   7027: 
                   7028: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7029:     my ($courseid,@groups) = @_;
                   7030:     @groups = sort(@groups);
1.691     raeburn  7031:     return @groups;
                   7032: }
                   7033: 
1.395     albertel 7034: sub packages_tab_default {
                   7035:     my ($uri,$varname)=@_;
                   7036:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7037: 
                   7038:     my (@extension,@specifics,$do_default);
                   7039:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7040: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7041: 	if ($pack_type eq 'default') {
                   7042: 	    $do_default=1;
                   7043: 	} elsif ($pack_type eq 'extension') {
                   7044: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7045: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7046: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7047: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7048: 	}
                   7049:     }
                   7050:     # first look for a package that matches the requested part id
                   7051:     foreach my $package (@specifics) {
                   7052: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7053: 	next if ($pack_part ne $part);
                   7054: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7055: 	    return $packagetab{"$pack_type&$name&default"};
                   7056: 	}
                   7057:     }
                   7058:     # look for any possible matching non extension_ package
                   7059:     foreach my $package (@specifics) {
                   7060: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7061: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7062: 	    return $packagetab{"$pack_type&$name&default"};
                   7063: 	}
1.585     albertel 7064: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7065: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7066: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7067: 	}
                   7068:     }
1.738     albertel 7069:     # look for any posible extension_ match
                   7070:     foreach my $package (@extension) {
                   7071: 	my ($package,$pack_type)=@{$package};
                   7072: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7073: 	    return $packagetab{"$pack_type&$name&default"};
                   7074: 	}
                   7075: 	if (defined($packagetab{$package."&$name&default"})) {
                   7076: 	    return $packagetab{$package."&$name&default"};
                   7077: 	}
                   7078:     }
                   7079:     # look for a global default setting
                   7080:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7081: 	return $packagetab{"default&$name&default"};
                   7082:     }
1.395     albertel 7083:     return undef;
                   7084: }
                   7085: 
1.334     albertel 7086: sub add_prefix_and_part {
                   7087:     my ($prefix,$part)=@_;
                   7088:     my $keyroot;
                   7089:     if (defined($prefix) && $prefix !~ /^__/) {
                   7090: 	# prefix that has a part already
                   7091: 	$keyroot=$prefix;
                   7092:     } elsif (defined($prefix)) {
                   7093: 	# prefix that is missing a part
                   7094: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7095:     } else {
                   7096: 	# no prefix at all
                   7097: 	if (defined($part)) { $keyroot='_'.$part; }
                   7098:     }
                   7099:     return $keyroot;
                   7100: }
                   7101: 
1.71      www      7102: # ---------------------------------------------------------------- Get metadata
                   7103: 
1.599     albertel 7104: my %metaentry;
1.71      www      7105: sub metadata {
1.176     www      7106:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7107:     $uri=&declutter($uri);
1.288     albertel 7108:     # if it is a non metadata possible uri return quickly
1.529     albertel 7109:     if (($uri eq '') || 
                   7110: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7111: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7112:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7113: 	return undef;
                   7114:     }
                   7115:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7116: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7117: 	return undef;
1.288     albertel 7118:     }
1.73      www      7119:     my $filename=$uri;
                   7120:     $uri=~s/\.meta$//;
1.172     www      7121: #
                   7122: # Is the metadata already cached?
1.177     www      7123: # Look at timestamp of caching
1.172     www      7124: # Everything is cached by the main uri, libraries are never directly cached
                   7125: #
1.428     albertel 7126:     if (!defined($liburi)) {
1.599     albertel 7127: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7128: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7129:     }
                   7130:     {
1.172     www      7131: #
                   7132: # Is this a recursive call for a library?
                   7133: #
1.599     albertel 7134: #	if (! exists($metacache{$uri})) {
                   7135: #	    $metacache{$uri}={};
                   7136: #	}
1.924     albertel 7137: 	my $cachetime = 60*60;
1.171     www      7138:         if ($liburi) {
                   7139: 	    $liburi=&declutter($liburi);
                   7140:             $filename=$liburi;
1.401     bowersj2 7141:         } else {
1.599     albertel 7142: 	    &devalidate_cache_new('meta',$uri);
                   7143: 	    undef(%metaentry);
1.401     bowersj2 7144: 	}
1.140     www      7145:         my %metathesekeys=();
1.73      www      7146:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7147: 	my $metastring;
1.924     albertel 7148: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7149: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7150: 	    $metastring = 
1.929     albertel 7151: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7152: 					  ('grade_target' => 'meta'));
                   7153: 	    $cachetime = 1; # only want this cached in the child not long term
                   7154: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7155: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7156: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7157: 	    $metastring=&getfile($file);
1.489     albertel 7158: 	}
1.208     albertel 7159:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7160:         my $token;
1.140     www      7161:         undef %metathesekeys;
1.71      www      7162:         while ($token=$parser->get_token) {
1.339     albertel 7163: 	    if ($token->[0] eq 'S') {
                   7164: 		if (defined($token->[2]->{'package'})) {
1.172     www      7165: #
                   7166: # This is a package - get package info
                   7167: #
1.339     albertel 7168: 		    my $package=$token->[2]->{'package'};
                   7169: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7170: 		    if (defined($token->[2]->{'id'})) { 
                   7171: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7172: 		    }
1.599     albertel 7173: 		    if ($metaentry{':packages'}) {
                   7174: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7175: 		    } else {
1.599     albertel 7176: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7177: 		    }
1.736     albertel 7178: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7179: 			my $part=$keyroot;
                   7180: 			$part=~s/^\_//;
1.736     albertel 7181: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7182: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7183: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7184: 			    # ignore package.tab specified default values
                   7185:                             # here &package_tab_default() will fetch those
                   7186: 			    if ($subp eq 'default') { next; }
1.736     albertel 7187: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7188: 			    my $unikey;
                   7189: 			    if ($pack =~ /_0$/) {
                   7190: 				$unikey='parameter_0_'.$name;
                   7191: 				$part=0;
                   7192: 			    } else {
                   7193: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7194: 			    }
1.339     albertel 7195: 			    if ($subp eq 'display') {
                   7196: 				$value.=' [Part: '.$part.']';
                   7197: 			    }
1.599     albertel 7198: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7199: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7200: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7201: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7202: 			    }
1.599     albertel 7203: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7204: 				$metaentry{':'.$unikey}=
                   7205: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7206: 			    }
1.339     albertel 7207: 			}
                   7208: 		    }
                   7209: 		} else {
1.172     www      7210: #
                   7211: # This is not a package - some other kind of start tag
1.339     albertel 7212: #
                   7213: 		    my $entry=$token->[1];
                   7214: 		    my $unikey;
                   7215: 		    if ($entry eq 'import') {
                   7216: 			$unikey='';
                   7217: 		    } else {
                   7218: 			$unikey=$entry;
                   7219: 		    }
                   7220: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7221: 
                   7222: 		    if (defined($token->[2]->{'id'})) { 
                   7223: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7224: 		    }
1.175     www      7225: 
1.339     albertel 7226: 		    if ($entry eq 'import') {
1.175     www      7227: #
                   7228: # Importing a library here
1.339     albertel 7229: #
                   7230: 			if ($depthcount<20) {
                   7231: 			    my $location=$parser->get_text('/import');
                   7232: 			    my $dir=$filename;
                   7233: 			    $dir=~s|[^/]*$||;
                   7234: 			    $location=&filelocation($dir,$location);
1.736     albertel 7235: 			    my $metadata = 
                   7236: 				&metadata($uri,'keys', $location,$unikey,
                   7237: 					  $depthcount+1);
                   7238: 			    foreach my $meta (split(',',$metadata)) {
                   7239: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7240: 				$metathesekeys{$meta}=1;
1.339     albertel 7241: 			    }
                   7242: 			}
                   7243: 		    } else { 
                   7244: 			
                   7245: 			if (defined($token->[2]->{'name'})) { 
                   7246: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7247: 			}
                   7248: 			$metathesekeys{$unikey}=1;
1.736     albertel 7249: 			foreach my $param (@{$token->[3]}) {
                   7250: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7251: 				$token->[2]->{$param};
1.339     albertel 7252: 			}
                   7253: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7254: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7255: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7256: 		 # only ws inside the tag, and not in default, so use default
                   7257: 		 # as value
1.599     albertel 7258: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7259: 			} elsif ( $internaltext =~ /\S/ ) {
                   7260: 		  # something interesting inside the tag
                   7261: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7262: 			} else {
1.908     albertel 7263: 		  # no interesting values, don't set a default
1.339     albertel 7264: 			}
1.172     www      7265: # end of not-a-package not-a-library import
1.339     albertel 7266: 		    }
1.172     www      7267: # end of not-a-package start tag
1.339     albertel 7268: 		}
1.172     www      7269: # the next is the end of "start tag"
1.339     albertel 7270: 	    }
                   7271: 	}
1.483     albertel 7272: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7273: 	$extension = lc($extension);
                   7274: 	if ($extension eq 'htm') { $extension='html'; }
                   7275: 
1.737     albertel 7276: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7277: 	    #no specific packages #how's our extension
                   7278: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7279: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7280: 					 \%metathesekeys);
                   7281: 	}
1.883     albertel 7282: 
                   7283: 	if (!exists($metaentry{':packages'})
                   7284: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7285: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7286: 		#no specific packages well let's get default then
                   7287: 		if ($key!~/^default&/) { next; }
1.488     albertel 7288: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7289: 					     \%metathesekeys);
                   7290: 	    }
                   7291: 	}
1.338     www      7292: # are there custom rights to evaluate
1.599     albertel 7293: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7294: 
1.338     www      7295:     #
                   7296:     # Importing a rights file here
1.339     albertel 7297:     #
                   7298: 	    unless ($depthcount) {
1.599     albertel 7299: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7300: 		my $dir=$filename;
                   7301: 		$dir=~s|[^/]*$||;
                   7302: 		$location=&filelocation($dir,$location);
1.736     albertel 7303: 		my $rights_metadata =
                   7304: 		    &metadata($uri,'keys',$location,'_rights',
                   7305: 			      $depthcount+1);
                   7306: 		foreach my $rights (split(',',$rights_metadata)) {
                   7307: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7308: 		    $metathesekeys{$rights}=1;
1.339     albertel 7309: 		}
                   7310: 	    }
                   7311: 	}
1.737     albertel 7312: 	# uniqifiy package listing
                   7313: 	my %seen;
                   7314: 	my @uniq_packages =
                   7315: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7316: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7317: 
                   7318: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7319: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7320: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7321: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7322: # this is the end of "was not already recently cached
1.71      www      7323:     }
1.599     albertel 7324:     return $metaentry{':'.$what};
1.261     albertel 7325: }
                   7326: 
1.488     albertel 7327: sub metadata_create_package_def {
1.483     albertel 7328:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7329:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7330:     if ($subp eq 'default') { next; }
                   7331:     
1.599     albertel 7332:     if (defined($metaentry{':packages'})) {
                   7333: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7334:     } else {
1.599     albertel 7335: 	$metaentry{':packages'}=$package;
1.483     albertel 7336:     }
                   7337:     my $value=$packagetab{$key};
                   7338:     my $unikey;
                   7339:     $unikey='parameter_0_'.$name;
1.599     albertel 7340:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7341:     $$metathesekeys{$unikey}=1;
1.599     albertel 7342:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7343: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7344:     }
1.599     albertel 7345:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7346: 	$metaentry{':'.$unikey}=
                   7347: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7348:     }
                   7349: }
                   7350: 
1.261     albertel 7351: sub metadata_generate_part0 {
                   7352:     my ($metadata,$metacache,$uri) = @_;
                   7353:     my %allnames;
1.737     albertel 7354:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7355: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7356: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7357: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7358: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7359: 	    $allnames{$name}=$part;
                   7360: 	  }
                   7361: 	}
                   7362:     }
                   7363:     foreach my $name (keys(%allnames)) {
                   7364:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7365:       my $key=":parameter_0_$name";
1.261     albertel 7366:       $$metacache{"$key.part"}='0';
                   7367:       $$metacache{"$key.name"}=$name;
1.428     albertel 7368:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7369: 					   $allnames{$name}.'_'.$name.
                   7370: 					   '.type'};
1.428     albertel 7371:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7372: 			     '.display'};
1.644     www      7373:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7374:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7375:       $$metacache{"$key.display"}=$olddis;
                   7376:     }
1.71      www      7377: }
                   7378: 
1.764     albertel 7379: # ------------------------------------------------------ Devalidate title cache
                   7380: 
                   7381: sub devalidate_title_cache {
                   7382:     my ($url)=@_;
                   7383:     if (!$env{'request.course.id'}) { return; }
                   7384:     my $symb=&symbread($url);
                   7385:     if (!$symb) { return; }
                   7386:     my $key=$env{'request.course.id'}."\0".$symb;
                   7387:     &devalidate_cache_new('title',$key);
                   7388: }
                   7389: 
1.301     www      7390: # ------------------------------------------------- Get the title of a resource
                   7391: 
                   7392: sub gettitle {
                   7393:     my $urlsymb=shift;
                   7394:     my $symb=&symbread($urlsymb);
1.534     albertel 7395:     if ($symb) {
1.620     albertel 7396: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7397: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7398: 	if (defined($cached)) { 
                   7399: 	    return $result;
                   7400: 	}
1.534     albertel 7401: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7402: 	my $title='';
1.907     albertel 7403: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7404: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7405: 	} else {
                   7406: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7407: 		    &GDBM_READER(),0640)) {
                   7408: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7409: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7410: 		untie(%bighash);
                   7411: 	    }
1.534     albertel 7412: 	}
                   7413: 	$title=~s/\&colon\;/\:/gs;
                   7414: 	if ($title) {
1.599     albertel 7415: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7416: 	}
                   7417: 	$urlsymb=$url;
                   7418:     }
                   7419:     my $title=&metadata($urlsymb,'title');
                   7420:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7421:     return $title;
1.301     www      7422: }
1.613     albertel 7423: 
1.614     albertel 7424: sub get_slot {
                   7425:     my ($which,$cnum,$cdom)=@_;
                   7426:     if (!$cnum || !$cdom) {
1.790     albertel 7427: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7428: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7429: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7430:     }
1.703     albertel 7431:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7432:     my %slotinfo;
                   7433:     if (exists($remembered{$key})) {
                   7434: 	$slotinfo{$which} = $remembered{$key};
                   7435:     } else {
                   7436: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7437: 	&Apache::lonhomework::showhash(%slotinfo);
                   7438: 	my ($tmp)=keys(%slotinfo);
                   7439: 	if ($tmp=~/^error:/) { return (); }
                   7440: 	$remembered{$key} = $slotinfo{$which};
                   7441:     }
1.616     albertel 7442:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7443: 	return %{$slotinfo{$which}};
                   7444:     }
                   7445:     return $slotinfo{$which};
1.614     albertel 7446: }
1.31      www      7447: # ------------------------------------------------- Update symbolic store links
                   7448: 
                   7449: sub symblist {
                   7450:     my ($mapname,%newhash)=@_;
1.438     www      7451:     $mapname=&deversion(&declutter($mapname));
1.31      www      7452:     my %hash;
1.620     albertel 7453:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7454:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7455:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7456: 	    foreach my $url (keys %newhash) {
                   7457: 		next if ($url eq 'last_known'
                   7458: 			 && $env{'form.no_update_last_known'});
                   7459: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7460: 						    $newhash{$url}->[1],
                   7461: 						    $newhash{$url}->[0]);
1.191     harris41 7462:             }
1.31      www      7463:             if (untie(%hash)) {
                   7464: 		return 'ok';
                   7465:             }
                   7466:         }
                   7467:     }
                   7468:     return 'error';
1.212     www      7469: }
                   7470: 
                   7471: # --------------------------------------------------------------- Verify a symb
                   7472: 
                   7473: sub symbverify {
1.510     www      7474:     my ($symb,$thisurl)=@_;
                   7475:     my $thisfn=$thisurl;
1.439     www      7476:     $thisfn=&declutter($thisfn);
1.215     www      7477: # direct jump to resource in page or to a sequence - will construct own symbs
                   7478:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7479: # check URL part
1.409     www      7480:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7481: 
1.431     www      7482:     unless ($url eq $thisfn) { return 0; }
1.213     www      7483: 
1.216     www      7484:     $symb=&symbclean($symb);
1.510     www      7485:     $thisurl=&deversion($thisurl);
1.439     www      7486:     $thisfn=&deversion($thisfn);
1.213     www      7487: 
                   7488:     my %bighash;
                   7489:     my $okay=0;
1.431     www      7490: 
1.620     albertel 7491:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7492:                             &GDBM_READER(),0640)) {
1.510     www      7493:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7494:         unless ($ids) { 
1.510     www      7495:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7496:         }
                   7497:         if ($ids) {
                   7498: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7499: 	    foreach my $id (split(/\,/,$ids)) {
                   7500: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7501:                if (
                   7502:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7503:    eq $symb) { 
1.620     albertel 7504: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7505: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7506: 		       $okay=1; 
                   7507: 		   }
                   7508: 	       }
1.216     www      7509: 	   }
                   7510:         }
1.213     www      7511: 	untie(%bighash);
                   7512:     }
                   7513:     return $okay;
1.31      www      7514: }
                   7515: 
1.210     www      7516: # --------------------------------------------------------------- Clean-up symb
                   7517: 
                   7518: sub symbclean {
                   7519:     my $symb=shift;
1.568     albertel 7520:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7521: # remove version from map
                   7522:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7523: 
1.210     www      7524: # remove version from URL
                   7525:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7526: 
1.507     www      7527: # remove wrapper
                   7528: 
1.510     www      7529:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7530:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7531:     return $symb;
1.409     www      7532: }
                   7533: 
                   7534: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7535: 
                   7536: sub encode_symb {
                   7537:     my ($map,$resid,$url)=@_;
                   7538:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7539: }
1.409     www      7540: 
                   7541: sub decode_symb {
1.568     albertel 7542:     my $symb=shift;
                   7543:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7544:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7545:     return (&fixversion($map),$resid,&fixversion($url));
                   7546: }
                   7547: 
                   7548: sub fixversion {
                   7549:     my $fn=shift;
1.609     banghart 7550:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7551:     my %bighash;
                   7552:     my $uri=&clutter($fn);
1.620     albertel 7553:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7554: # is this cached?
1.599     albertel 7555:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7556:     if (defined($cached)) { return $result; }
                   7557: # unfortunately not cached, or expired
1.620     albertel 7558:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7559: 	    &GDBM_READER(),0640)) {
                   7560:  	if ($bighash{'version_'.$uri}) {
                   7561:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7562:  	    unless (($version eq 'mostrecent') || 
                   7563: 		    ($version==&getversion($uri))) {
1.440     www      7564:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7565:  	    }
                   7566:  	}
                   7567:  	untie %bighash;
1.413     www      7568:     }
1.599     albertel 7569:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7570: }
                   7571: 
                   7572: sub deversion {
                   7573:     my $url=shift;
                   7574:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7575:     return $url;
1.210     www      7576: }
                   7577: 
1.31      www      7578: # ------------------------------------------------------ Return symb list entry
                   7579: 
                   7580: sub symbread {
1.249     www      7581:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7582:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7583:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7584: # no filename provided? try from environment
1.44      www      7585:     unless ($thisfn) {
1.620     albertel 7586:         if ($env{'request.symb'}) {
                   7587: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7588: 	}
1.620     albertel 7589: 	$thisfn=$env{'request.filename'};
1.44      www      7590:     }
1.569     albertel 7591:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7592: # is that filename actually a symb? Verify, clean, and return
                   7593:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7594: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7595: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7596: 	}
1.242     www      7597:     }
1.44      www      7598:     $thisfn=declutter($thisfn);
1.31      www      7599:     my %hash;
1.37      www      7600:     my %bighash;
                   7601:     my $syval='';
1.620     albertel 7602:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7603:         my $targetfn = $thisfn;
1.609     banghart 7604:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7605:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7606:         }
1.687     albertel 7607: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7608: 	    $targetfn=$1;
                   7609: 	}
1.620     albertel 7610:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7611:                       &GDBM_READER(),0640)) {
1.481     raeburn  7612: 	    $syval=$hash{$targetfn};
1.37      www      7613:             untie(%hash);
                   7614:         }
                   7615: # ---------------------------------------------------------- There was an entry
                   7616:         if ($syval) {
1.601     albertel 7617: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7618: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7619: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7620: 		    #return $env{$cache_str}='';
1.601     albertel 7621: 		#}    
                   7622: 		#$syval.=$1;
                   7623: 	    #}
1.37      www      7624:         } else {
                   7625: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7626:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7627:                             &GDBM_READER(),0640)) {
1.37      www      7628: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7629:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7630:               unless ($ids) { 
                   7631:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7632:               }
                   7633:               unless ($ids) {
                   7634: # alias?
                   7635: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7636:               }
1.37      www      7637:               if ($ids) {
                   7638: # ------------------------------------------------------------------- Has ID(s)
                   7639:                  my @possibilities=split(/\,/,$ids);
1.39      www      7640:                  if ($#possibilities==0) {
                   7641: # ----------------------------------------------- There is only one possibility
1.37      www      7642: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7643: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7644: 						    $resid,$thisfn);
1.249     www      7645:                  } elsif (!$donotrecurse) {
1.39      www      7646: # ------------------------------------------ There is more than one possibility
                   7647:                      my $realpossible=0;
1.800     albertel 7648:                      foreach my $id (@possibilities) {
                   7649: 			 my $file=$bighash{'src_'.$id};
1.39      www      7650:                          if (&allowed('bre',$file)) {
1.800     albertel 7651:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7652:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7653: 				$realpossible++;
1.626     albertel 7654:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7655: 						    $resid,$thisfn);
1.39      www      7656:                             }
                   7657: 			 }
1.191     harris41 7658:                      }
1.39      www      7659: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7660:                  } else {
                   7661:                      $syval='';
1.37      www      7662:                  }
                   7663: 	      }
                   7664:               untie(%bighash)
1.481     raeburn  7665:            }
1.31      www      7666:         }
1.62      www      7667:         if ($syval) {
1.620     albertel 7668: 	    return $env{$cache_str}=$syval;
1.62      www      7669:         }
1.31      www      7670:     }
1.949     raeburn  7671:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7672:     return $env{$cache_str}='';
1.31      www      7673: }
                   7674: 
                   7675: # ---------------------------------------------------------- Return random seed
                   7676: 
1.32      www      7677: sub numval {
                   7678:     my $txt=shift;
                   7679:     $txt=~tr/A-J/0-9/;
                   7680:     $txt=~tr/a-j/0-9/;
                   7681:     $txt=~tr/K-T/0-9/;
                   7682:     $txt=~tr/k-t/0-9/;
                   7683:     $txt=~tr/U-Z/0-5/;
                   7684:     $txt=~tr/u-z/0-5/;
                   7685:     $txt=~s/\D//g;
1.564     albertel 7686:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7687:     return int($txt);
1.368     albertel 7688: }
                   7689: 
1.484     albertel 7690: sub numval2 {
                   7691:     my $txt=shift;
                   7692:     $txt=~tr/A-J/0-9/;
                   7693:     $txt=~tr/a-j/0-9/;
                   7694:     $txt=~tr/K-T/0-9/;
                   7695:     $txt=~tr/k-t/0-9/;
                   7696:     $txt=~tr/U-Z/0-5/;
                   7697:     $txt=~tr/u-z/0-5/;
                   7698:     $txt=~s/\D//g;
                   7699:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7700:     my $total;
                   7701:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7702:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7703:     return int($total);
                   7704: }
                   7705: 
1.575     albertel 7706: sub numval3 {
                   7707:     use integer;
                   7708:     my $txt=shift;
                   7709:     $txt=~tr/A-J/0-9/;
                   7710:     $txt=~tr/a-j/0-9/;
                   7711:     $txt=~tr/K-T/0-9/;
                   7712:     $txt=~tr/k-t/0-9/;
                   7713:     $txt=~tr/U-Z/0-5/;
                   7714:     $txt=~tr/u-z/0-5/;
                   7715:     $txt=~s/\D//g;
                   7716:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7717:     my $total;
                   7718:     foreach my $val (@txts) { $total+=$val; }
                   7719:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7720:     return $total;
                   7721: }
                   7722: 
1.675     albertel 7723: sub digest {
                   7724:     my ($data)=@_;
                   7725:     my $digest=&Digest::MD5::md5($data);
                   7726:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7727:     my ($e,$f);
                   7728:     {
                   7729:         use integer;
                   7730:         $e=($a+$b);
                   7731:         $f=($c+$d);
                   7732:         if ($_64bit) {
                   7733:             $e=(($e<<32)>>32);
                   7734:             $f=(($f<<32)>>32);
                   7735:         }
                   7736:     }
                   7737:     if (wantarray) {
                   7738: 	return ($e,$f);
                   7739:     } else {
                   7740: 	my $g;
                   7741: 	{
                   7742: 	    use integer;
                   7743: 	    $g=($e+$f);
                   7744: 	    if ($_64bit) {
                   7745: 		$g=(($g<<32)>>32);
                   7746: 	    }
                   7747: 	}
                   7748: 	return $g;
                   7749:     }
                   7750: }
                   7751: 
1.368     albertel 7752: sub latest_rnd_algorithm_id {
1.675     albertel 7753:     return '64bit5';
1.366     albertel 7754: }
1.32      www      7755: 
1.503     albertel 7756: sub get_rand_alg {
                   7757:     my ($courseid)=@_;
1.790     albertel 7758:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7759:     if ($courseid) {
1.620     albertel 7760: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7761:     }
                   7762:     return &latest_rnd_algorithm_id();
                   7763: }
                   7764: 
1.562     albertel 7765: sub validCODE {
                   7766:     my ($CODE)=@_;
                   7767:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7768:     return 0;
                   7769: }
                   7770: 
1.491     albertel 7771: sub getCODE {
1.620     albertel 7772:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7773:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7774: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7775: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7776: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7777:     }
                   7778:     return undef;
                   7779: }
                   7780: 
1.31      www      7781: sub rndseed {
1.155     albertel 7782:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7783:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7784:     if (!defined($symb)) {
1.366     albertel 7785: 	unless ($symb=$wsymb) { return time; }
                   7786:     }
                   7787:     if (!$courseid) { $courseid=$wcourseid; }
                   7788:     if (!$domain) { $domain=$wdomain; }
                   7789:     if (!$username) { $username=$wusername }
1.503     albertel 7790:     my $which=&get_rand_alg();
1.803     albertel 7791: 
1.491     albertel 7792:     if (defined(&getCODE())) {
1.675     albertel 7793: 	if ($which eq '64bit5') {
                   7794: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7795: 	} elsif ($which eq '64bit4') {
1.575     albertel 7796: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7797: 	} else {
                   7798: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7799: 	}
1.675     albertel 7800:     } elsif ($which eq '64bit5') {
                   7801: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7802:     } elsif ($which eq '64bit4') {
                   7803: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7804:     } elsif ($which eq '64bit3') {
                   7805: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7806:     } elsif ($which eq '64bit2') {
                   7807: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7808:     } elsif ($which eq '64bit') {
                   7809: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7810:     }
                   7811:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7812: }
                   7813: 
                   7814: sub rndseed_32bit {
                   7815:     my ($symb,$courseid,$domain,$username)=@_;
                   7816:     {
                   7817: 	use integer;
                   7818: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7819: 	my $symbseed=numval($symb) << 22;
                   7820: 	my $namechck=unpack("%32C*",$username) << 17;
                   7821: 	my $nameseed=numval($username) << 12;
                   7822: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7823: 	my $courseseed=unpack("%32C*",$courseid);
                   7824: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7825: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7826: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7827: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7828: 	return $num;
                   7829:     }
                   7830: }
                   7831: 
                   7832: sub rndseed_64bit {
                   7833:     my ($symb,$courseid,$domain,$username)=@_;
                   7834:     {
                   7835: 	use integer;
                   7836: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7837: 	my $symbseed=numval($symb) << 10;
                   7838: 	my $namechck=unpack("%32S*",$username);
                   7839: 	
                   7840: 	my $nameseed=numval($username) << 21;
                   7841: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7842: 	my $courseseed=unpack("%32S*",$courseid);
                   7843: 	
                   7844: 	my $num1=$symbchck+$symbseed+$namechck;
                   7845: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7846: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7847: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7848: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7849: 	return "$num1,$num2";
1.155     albertel 7850:     }
1.366     albertel 7851: }
                   7852: 
1.443     albertel 7853: sub rndseed_64bit2 {
                   7854:     my ($symb,$courseid,$domain,$username)=@_;
                   7855:     {
                   7856: 	use integer;
                   7857: 	# strings need to be an even # of cahracters long, it it is odd the
                   7858:         # last characters gets thrown away
                   7859: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7860: 	my $symbseed=numval($symb) << 10;
                   7861: 	my $namechck=unpack("%32S*",$username.' ');
                   7862: 	
                   7863: 	my $nameseed=numval($username) << 21;
1.501     albertel 7864: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7865: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7866: 	
                   7867: 	my $num1=$symbchck+$symbseed+$namechck;
                   7868: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7869: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7870: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7871: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7872: 	return "$num1,$num2";
                   7873:     }
                   7874: }
                   7875: 
                   7876: sub rndseed_64bit3 {
                   7877:     my ($symb,$courseid,$domain,$username)=@_;
                   7878:     {
                   7879: 	use integer;
                   7880: 	# strings need to be an even # of cahracters long, it it is odd the
                   7881:         # last characters gets thrown away
                   7882: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7883: 	my $symbseed=numval2($symb) << 10;
                   7884: 	my $namechck=unpack("%32S*",$username.' ');
                   7885: 	
                   7886: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7887: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7888: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7889: 	
                   7890: 	my $num1=$symbchck+$symbseed+$namechck;
                   7891: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7892: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7893: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7894: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7895: 	
1.503     albertel 7896: 	return "$num1:$num2";
1.443     albertel 7897:     }
                   7898: }
                   7899: 
1.575     albertel 7900: sub rndseed_64bit4 {
                   7901:     my ($symb,$courseid,$domain,$username)=@_;
                   7902:     {
                   7903: 	use integer;
                   7904: 	# strings need to be an even # of cahracters long, it it is odd the
                   7905:         # last characters gets thrown away
                   7906: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7907: 	my $symbseed=numval3($symb) << 10;
                   7908: 	my $namechck=unpack("%32S*",$username.' ');
                   7909: 	
                   7910: 	my $nameseed=numval3($username) << 21;
                   7911: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7912: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7913: 	
                   7914: 	my $num1=$symbchck+$symbseed+$namechck;
                   7915: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7916: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7917: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7918: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7919: 	
                   7920: 	return "$num1:$num2";
                   7921:     }
                   7922: }
                   7923: 
1.675     albertel 7924: sub rndseed_64bit5 {
                   7925:     my ($symb,$courseid,$domain,$username)=@_;
                   7926:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7927:     return "$num1:$num2";
                   7928: }
                   7929: 
1.366     albertel 7930: sub rndseed_CODE_64bit {
                   7931:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7932:     {
1.366     albertel 7933: 	use integer;
1.443     albertel 7934: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7935: 	my $symbseed=numval2($symb);
1.491     albertel 7936: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7937: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7938: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7939: 	my $num1=$symbseed+$CODEchck;
                   7940: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7941: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7942: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7943: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7944: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7945: 	return "$num1:$num2";
1.366     albertel 7946:     }
                   7947: }
                   7948: 
1.575     albertel 7949: sub rndseed_CODE_64bit4 {
                   7950:     my ($symb,$courseid,$domain,$username)=@_;
                   7951:     {
                   7952: 	use integer;
                   7953: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7954: 	my $symbseed=numval3($symb);
                   7955: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7956: 	my $CODEseed=numval3(&getCODE());
                   7957: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7958: 	my $num1=$symbseed+$CODEchck;
                   7959: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7960: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7961: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7962: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7963: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7964: 	return "$num1:$num2";
                   7965:     }
                   7966: }
                   7967: 
1.675     albertel 7968: sub rndseed_CODE_64bit5 {
                   7969:     my ($symb,$courseid,$domain,$username)=@_;
                   7970:     my $code = &getCODE();
                   7971:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7972:     return "$num1:$num2";
                   7973: }
                   7974: 
1.366     albertel 7975: sub setup_random_from_rndseed {
                   7976:     my ($rndseed)=@_;
1.503     albertel 7977:     if ($rndseed =~/([,:])/) {
                   7978: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7979: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7980:     } else {
                   7981: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7982:     }
1.36      albertel 7983: }
                   7984: 
1.474     albertel 7985: sub latest_receipt_algorithm_id {
1.835     albertel 7986:     return 'receipt3';
1.474     albertel 7987: }
                   7988: 
1.480     www      7989: sub recunique {
                   7990:     my $fucourseid=shift;
                   7991:     my $unique;
1.835     albertel 7992:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7993: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7994: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7995:     } else {
                   7996: 	$unique=$perlvar{'lonReceipt'};
                   7997:     }
                   7998:     return unpack("%32C*",$unique);
                   7999: }
                   8000: 
                   8001: sub recprefix {
                   8002:     my $fucourseid=shift;
                   8003:     my $prefix;
1.835     albertel 8004:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8005: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8006: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8007:     } else {
                   8008: 	$prefix=$perlvar{'lonHostID'};
                   8009:     }
                   8010:     return unpack("%32C*",$prefix);
                   8011: }
                   8012: 
1.76      www      8013: sub ireceipt {
1.474     albertel 8014:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8015: 
                   8016:     my $return =&recprefix($fucourseid).'-';
                   8017: 
                   8018:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8019: 	$env{'request.state'} eq 'construct') {
                   8020: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8021: 	return $return;
                   8022:     }
                   8023: 
1.76      www      8024:     my $cuname=unpack("%32C*",$funame);
                   8025:     my $cudom=unpack("%32C*",$fudom);
                   8026:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8027:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8028:     my $cunique=&recunique($fucourseid);
1.474     albertel 8029:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8030:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8031: 
1.790     albertel 8032: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8033: 			       
                   8034: 	$return.= ($cunique%$cuname+
                   8035: 		   $cunique%$cudom+
                   8036: 		   $cusymb%$cuname+
                   8037: 		   $cusymb%$cudom+
                   8038: 		   $cucourseid%$cuname+
                   8039: 		   $cucourseid%$cudom+
                   8040: 		   $cpart%$cuname+
                   8041: 		   $cpart%$cudom);
                   8042:     } else {
                   8043: 	$return.= ($cunique%$cuname+
                   8044: 		   $cunique%$cudom+
                   8045: 		   $cusymb%$cuname+
                   8046: 		   $cusymb%$cudom+
                   8047: 		   $cucourseid%$cuname+
                   8048: 		   $cucourseid%$cudom);
                   8049:     }
                   8050:     return $return;
1.76      www      8051: }
                   8052: 
                   8053: sub receipt {
1.474     albertel 8054:     my ($part)=@_;
1.790     albertel 8055:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8056:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8057: }
1.260     ng       8058: 
1.790     albertel 8059: sub whichuser {
                   8060:     my ($passedsymb)=@_;
                   8061:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8062:     if (defined($env{'form.grade_symb'})) {
                   8063: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8064: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8065: 	if (!$allowed &&
                   8066: 	    exists($env{'request.course.sec'}) &&
                   8067: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8068: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8069: 			      '/'.$env{'request.course.sec'});
                   8070: 	}
                   8071: 	if ($allowed) {
                   8072: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8073: 	    $courseid=$tmp_courseid;
                   8074: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8075: 	    ($name)=&get_env_multiple('form.grade_username');
                   8076: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8077: 	}
                   8078:     }
                   8079:     if (!$passedsymb) {
                   8080: 	$symb=&symbread();
                   8081:     } else {
                   8082: 	$symb=$passedsymb;
                   8083:     }
                   8084:     $courseid=$env{'request.course.id'};
                   8085:     $domain=$env{'user.domain'};
                   8086:     $name=$env{'user.name'};
                   8087:     if ($name eq 'public' && $domain eq 'public') {
                   8088: 	if (!defined($env{'form.username'})) {
                   8089: 	    $env{'form.username'}.=time.rand(10000000);
                   8090: 	}
                   8091: 	$name.=$env{'form.username'};
                   8092:     }
                   8093:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8094: 
                   8095: }
                   8096: 
1.36      albertel 8097: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8098: # returns either the contents of the file or 
                   8099: # -1 if the file doesn't exist
1.481     raeburn  8100: #
                   8101: # if the target is a file that was uploaded via DOCS, 
                   8102: # a check will be made to see if a current copy exists on the local server,
                   8103: # if it does this will be served, otherwise a copy will be retrieved from
                   8104: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8105: # the local server.   
1.472     albertel 8106: 
1.36      albertel 8107: sub getfile {
1.538     albertel 8108:     my ($file) = @_;
1.609     banghart 8109:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8110:     &repcopy($file);
                   8111:     return &readfile($file);
                   8112: }
                   8113: 
                   8114: sub repcopy_userfile {
                   8115:     my ($file)=@_;
1.609     banghart 8116:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8117:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8118:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8119: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8120:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8121:     if (-e "$file") {
1.828     www      8122: # we already have a local copy, check it out
1.538     albertel 8123: 	my @fileinfo = stat($file);
1.828     www      8124: 	my $rtncode;
                   8125: 	my $info;
1.538     albertel 8126: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8127: 	if ($lwpresp ne 'ok') {
1.828     www      8128: # there is no such file anymore, even though we had a local copy
1.482     albertel 8129: 	    if ($rtncode eq '404') {
1.538     albertel 8130: 		unlink($file);
1.482     albertel 8131: 	    }
                   8132: 	    return -1;
                   8133: 	}
                   8134: 	if ($info < $fileinfo[9]) {
1.828     www      8135: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8136: 	    return 'ok';
1.828     www      8137: 	} else {
                   8138: # the file is outdated, get rid of it
                   8139: 	    unlink($file);
1.482     albertel 8140: 	}
1.828     www      8141:     }
                   8142: # one way or the other, at this point, we don't have the file
                   8143: # construct the correct path for the file
                   8144:     my @parts = ($cdom,$cnum); 
                   8145:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8146: 	push @parts, split(/\//,$1);
                   8147:     }
                   8148:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8149:     foreach my $part (@parts) {
                   8150: 	$path .= '/'.$part;
                   8151: 	if (!-e $path) {
                   8152: 	    mkdir($path,0770);
1.482     albertel 8153: 	}
                   8154:     }
1.828     www      8155: # now the path exists for sure
                   8156: # get a user agent
                   8157:     my $ua=new LWP::UserAgent;
                   8158:     my $transferfile=$file.'.in.transfer';
                   8159: # FIXME: this should flock
                   8160:     if (-e $transferfile) { return 'ok'; }
                   8161:     my $request;
                   8162:     $uri=~s/^\///;
1.838     albertel 8163:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8164:     my $response=$ua->request($request,$transferfile);
                   8165: # did it work?
                   8166:     if ($response->is_error()) {
                   8167: 	unlink($transferfile);
                   8168: 	&logthis("Userfile repcopy failed for $uri");
                   8169: 	return -1;
                   8170:     }
                   8171: # worked, rename the transfer file
                   8172:     rename($transferfile,$file);
1.607     raeburn  8173:     return 'ok';
1.481     raeburn  8174: }
                   8175: 
1.517     albertel 8176: sub tokenwrapper {
                   8177:     my $uri=shift;
1.552     albertel 8178:     $uri=~s|^http\://([^/]+)||;
                   8179:     $uri=~s|^/||;
1.620     albertel 8180:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8181:     my $token=$1;
1.552     albertel 8182:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8183:     if ($udom && $uname && $file) {
                   8184: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8185:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8186:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8187:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8188:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8189:     } else {
                   8190:         return '/adm/notfound.html';
                   8191:     }
                   8192: }
                   8193: 
1.828     www      8194: # call with reqtype HEAD: get last modification time
                   8195: # call with reqtype GET: get the file contents
                   8196: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8197: #
1.481     raeburn  8198: sub getuploaded {
                   8199:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8200:     $uri=~s/^\///;
1.838     albertel 8201:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8202:     my $ua=new LWP::UserAgent;
                   8203:     my $request=new HTTP::Request($reqtype,$uri);
                   8204:     my $response=$ua->request($request);
                   8205:     $$rtncode = $response->code;
1.482     albertel 8206:     if (! $response->is_success()) {
                   8207: 	return 'failed';
                   8208:     }      
                   8209:     if ($reqtype eq 'HEAD') {
1.486     www      8210: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8211:     } elsif ($reqtype eq 'GET') {
                   8212: 	$$info = $response->content;
1.472     albertel 8213:     }
1.482     albertel 8214:     return 'ok';
1.36      albertel 8215: }
                   8216: 
1.481     raeburn  8217: sub readfile {
                   8218:     my $file = shift;
                   8219:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8220:     my $fh;
                   8221:     open($fh,"<$file");
                   8222:     my $a='';
1.800     albertel 8223:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8224:     return $a;
                   8225: }
                   8226: 
1.36      albertel 8227: sub filelocation {
1.590     banghart 8228:     my ($dir,$file) = @_;
                   8229:     my $location;
                   8230:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8231: 
                   8232:     if ($file =~ m-^/adm/-) {
                   8233: 	$file=~s-^/adm/wrapper/-/-;
                   8234: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8235:     }
1.882     albertel 8236: 
1.590     banghart 8237:     if ($file=~m:^/~:) { # is a contruction space reference
                   8238:         $location = $file;
                   8239:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8240:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8241: 	# is a correct contruction space reference
                   8242:         $location = $file;
1.956     raeburn  8243:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8244:         $location = $file;
1.609     banghart 8245:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8246:         my ($udom,$uname,$filename)=
1.811     albertel 8247:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8248:         my $home=&homeserver($uname,$udom);
                   8249:         my $is_me=0;
                   8250:         my @ids=&current_machine_ids();
                   8251:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8252:         if ($is_me) {
1.955     raeburn  8253:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8254:         } else {
                   8255:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8256:   	      $udom.'/'.$uname.'/'.$filename;
                   8257:         }
1.882     albertel 8258:     } elsif ($file =~ m-^/adm/-) {
                   8259: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8260:     } else {
                   8261:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8262:         $file=~s:^/res/:/:;
                   8263:         if ( !( $file =~ m:^/:) ) {
                   8264:             $location = $dir. '/'.$file;
                   8265:         } else {
                   8266:             $location = '/home/httpd/html/res'.$file;
                   8267:         }
1.59      albertel 8268:     }
1.590     banghart 8269:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8270:     while ($location=~m{/\.\./}) {
                   8271: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8272: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8273: 	} else {
                   8274: 	    $location=~ s{/\.\./}{/}g;
                   8275: 	}
                   8276:     } #remove dir/..
1.590     banghart 8277:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8278:     return $location;
1.46      www      8279: }
1.36      albertel 8280: 
1.46      www      8281: sub hreflocation {
                   8282:     my ($dir,$file)=@_;
1.460     albertel 8283:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8284: 	$file=filelocation($dir,$file);
1.700     albertel 8285:     } elsif ($file=~m-^/adm/-) {
                   8286: 	$file=~s-^/adm/wrapper/-/-;
                   8287: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8288:     }
                   8289:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8290: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8291:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8292: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8293:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8294: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8295: 	    -/uploaded/$1/$2/-x;
1.46      www      8296:     }
1.913     albertel 8297:     if ($file=~ m{^/userfiles/}) {
                   8298: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8299:     }
1.462     albertel 8300:     return $file;
1.465     albertel 8301: }
                   8302: 
                   8303: sub current_machine_domains {
1.853     albertel 8304:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8305: }
                   8306: 
                   8307: sub machine_domains {
                   8308:     my ($hostname) = @_;
1.465     albertel 8309:     my @domains;
1.838     albertel 8310:     my %hostname = &all_hostnames();
1.465     albertel 8311:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8312: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8313: 	if ($hostname eq $name) {
1.844     albertel 8314: 	    push(@domains,&host_domain($id));
1.465     albertel 8315: 	}
                   8316:     }
                   8317:     return @domains;
                   8318: }
                   8319: 
                   8320: sub current_machine_ids {
1.853     albertel 8321:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8322: }
                   8323: 
                   8324: sub machine_ids {
                   8325:     my ($hostname) = @_;
                   8326:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8327:     my @ids;
1.888     albertel 8328:     my %name_to_host = &all_names();
1.889     albertel 8329:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8330: 	return @{ $name_to_host{$hostname} };
                   8331:     }
                   8332:     return;
1.31      www      8333: }
                   8334: 
1.824     raeburn  8335: sub additional_machine_domains {
                   8336:     my @domains;
                   8337:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8338:     while( my $line = <$fh>) {
                   8339:         $line =~ s/\s//g;
                   8340:         push(@domains,$line);
                   8341:     }
                   8342:     return @domains;
                   8343: }
                   8344: 
                   8345: sub default_login_domain {
                   8346:     my $domain = $perlvar{'lonDefDomain'};
                   8347:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8348:     foreach my $posdom (&current_machine_domains(),
                   8349:                         &additional_machine_domains()) {
                   8350:         if (lc($posdom) eq lc($testdomain)) {
                   8351:             $domain=$posdom;
                   8352:             last;
                   8353:         }
                   8354:     }
                   8355:     return $domain;
                   8356: }
                   8357: 
1.31      www      8358: # ------------------------------------------------------------- Declutters URLs
                   8359: 
                   8360: sub declutter {
                   8361:     my $thisfn=shift;
1.569     albertel 8362:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8363:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8364:     $thisfn=~s/^\///;
1.697     albertel 8365:     $thisfn=~s|^adm/wrapper/||;
                   8366:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8367:     $thisfn=~s/^res\///;
1.235     www      8368:     $thisfn=~s/\?.+$//;
1.268     www      8369:     return $thisfn;
                   8370: }
                   8371: 
                   8372: # ------------------------------------------------------------- Clutter up URLs
                   8373: 
                   8374: sub clutter {
                   8375:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8376:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8377: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8378:        $thisfn='/res'.$thisfn; 
                   8379:     }
1.694     albertel 8380:     if ($thisfn !~m|/adm|) {
1.695     albertel 8381: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8382: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8383: 	} else {
                   8384: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8385: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8386: 	    if ($embstyle eq 'ssi'
                   8387: 		|| ($embstyle eq 'hdn')
                   8388: 		|| ($embstyle eq 'rat')
                   8389: 		|| ($embstyle eq 'prv')
                   8390: 		|| ($embstyle eq 'ign')) {
                   8391: 		#do nothing with these
                   8392: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8393: 		|| ($embstyle eq 'emb')
                   8394: 		|| ($embstyle eq 'wrp')) {
                   8395: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8396: 	    } elsif ($embstyle eq 'unk'
                   8397: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8398: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8399: 	    } else {
1.718     www      8400: #		&logthis("Got a blank emb style");
1.695     albertel 8401: 	    }
1.694     albertel 8402: 	}
                   8403:     }
1.31      www      8404:     return $thisfn;
1.12      www      8405: }
                   8406: 
1.787     albertel 8407: sub clutter_with_no_wrapper {
                   8408:     my $uri = &clutter(shift);
                   8409:     if ($uri =~ m-^/adm/-) {
                   8410: 	$uri =~ s-^/adm/wrapper/-/-;
                   8411: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8412:     }
                   8413:     return $uri;
                   8414: }
                   8415: 
1.557     albertel 8416: sub freeze_escape {
                   8417:     my ($value)=@_;
                   8418:     if (ref($value)) {
                   8419: 	$value=&nfreeze($value);
                   8420: 	return '__FROZEN__'.&escape($value);
                   8421:     }
                   8422:     return &escape($value);
                   8423: }
                   8424: 
1.11      www      8425: 
1.557     albertel 8426: sub thaw_unescape {
                   8427:     my ($value)=@_;
                   8428:     if ($value =~ /^__FROZEN__/) {
                   8429: 	substr($value,0,10,undef);
                   8430: 	$value=&unescape($value);
                   8431: 	return &thaw($value);
                   8432:     }
                   8433:     return &unescape($value);
                   8434: }
                   8435: 
1.436     albertel 8436: sub correct_line_ends {
                   8437:     my ($result)=@_;
                   8438:     $$result =~s/\r\n/\n/mg;
                   8439:     $$result =~s/\r/\n/mg;
1.415     albertel 8440: }
1.1       albertel 8441: # ================================================================ Main Program
                   8442: 
1.184     www      8443: sub goodbye {
1.204     albertel 8444:    &logthis("Starting Shut down");
1.443     albertel 8445: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8446:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8447: #converted
1.599     albertel 8448: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8449:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8450: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8451: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8452: #1.1 only
1.870     albertel 8453: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8454: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8455: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8456: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8457:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8458:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8459:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8460:    &flushcourselogs();
                   8461:    &logthis("Shutting down");
                   8462: }
                   8463: 
1.852     albertel 8464: sub get_dns {
1.869     albertel 8465:     my ($url,$func,$ignore_cache) = @_;
                   8466:     if (!$ignore_cache) {
                   8467: 	my ($content,$cached)=
                   8468: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8469: 	if ($cached) {
                   8470: 	    &$func($content);
                   8471: 	    return;
                   8472: 	}
                   8473:     }
                   8474: 
                   8475:     my %alldns;
1.852     albertel 8476:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8477:     foreach my $dns (<$config>) {
                   8478: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8479: 	$alldns{$1} = 1;
                   8480:     }
                   8481:     while (%alldns) {
                   8482: 	my ($dns) = keys(%alldns);
                   8483: 	delete($alldns{$dns});
1.852     albertel 8484: 	my $ua=new LWP::UserAgent;
                   8485: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8486: 	my $response=$ua->request($request);
                   8487: 	next if ($response->is_error());
                   8488: 	my @content = split("\n",$response->content);
1.869     albertel 8489: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8490: 	&$func(\@content);
1.869     albertel 8491: 	return;
1.852     albertel 8492:     }
                   8493:     close($config);
1.871     albertel 8494:     my $which = (split('/',$url))[3];
                   8495:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8496:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8497:     my @content = <$config>;
                   8498:     &$func(\@content);
                   8499:     return;
1.852     albertel 8500: }
1.327     albertel 8501: # ------------------------------------------------------------ Read domain file
                   8502: {
1.852     albertel 8503:     my $loaded;
1.846     albertel 8504:     my %domain;
                   8505: 
1.852     albertel 8506:     sub parse_domain_tab {
                   8507: 	my ($lines) = @_;
                   8508: 	foreach my $line (@$lines) {
                   8509: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8510: 
1.846     albertel 8511: 	    chomp($line);
1.852     albertel 8512: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8513: 	    my %this_domain;
                   8514: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8515: 			       'lang_def', 'city', 'longi', 'lati',
                   8516: 			       'primary') {
                   8517: 		$this_domain{$field} = shift(@elements);
                   8518: 	    }
                   8519: 	    $domain{$name} = \%this_domain;
1.852     albertel 8520: 	}
                   8521:     }
1.864     albertel 8522: 
                   8523:     sub reset_domain_info {
                   8524: 	undef($loaded);
                   8525: 	undef(%domain);
                   8526:     }
                   8527: 
1.852     albertel 8528:     sub load_domain_tab {
1.869     albertel 8529: 	my ($ignore_cache) = @_;
                   8530: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8531: 	my $fh;
                   8532: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8533: 	    my @lines = <$fh>;
                   8534: 	    &parse_domain_tab(\@lines);
1.448     albertel 8535: 	}
1.852     albertel 8536: 	close($fh);
                   8537: 	$loaded = 1;
1.327     albertel 8538:     }
1.846     albertel 8539: 
                   8540:     sub domain {
1.852     albertel 8541: 	&load_domain_tab() if (!$loaded);
                   8542: 
1.846     albertel 8543: 	my ($name,$what) = @_;
                   8544: 	return if ( !exists($domain{$name}) );
                   8545: 
                   8546: 	if (!$what) {
                   8547: 	    return $domain{$name}{'description'};
                   8548: 	}
                   8549: 	return $domain{$name}{$what};
                   8550:     }
1.974     raeburn  8551: 
                   8552:     sub domain_info {
                   8553:         &load_domain_tab() if (!$loaded);
                   8554:         return %domain;
                   8555:     }
                   8556: 
1.327     albertel 8557: }
                   8558: 
                   8559: 
1.1       albertel 8560: # ------------------------------------------------------------- Read hosts file
                   8561: {
1.838     albertel 8562:     my %hostname;
1.844     albertel 8563:     my %hostdom;
1.845     albertel 8564:     my %libserv;
1.852     albertel 8565:     my $loaded;
1.888     albertel 8566:     my %name_to_host;
1.852     albertel 8567: 
                   8568:     sub parse_hosts_tab {
                   8569: 	my ($file) = @_;
                   8570: 	foreach my $configline (@$file) {
                   8571: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8572: 	    next if ($configline =~ /^\^/);
                   8573: 	    chomp($configline);
1.968     raeburn  8574: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8575: 	    $name=~s/\s//g;
                   8576: 	    if ($id && $domain && $role && $name) {
                   8577: 		$hostname{$id}=$name;
1.888     albertel 8578: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8579: 		$hostdom{$id}=$domain;
                   8580: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8581:                 if (defined($protocol)) {
                   8582:                     if ($protocol eq 'https') {
                   8583:                         $protocol{$id} = $protocol;
                   8584:                     } else {
                   8585:                         $protocol{$id} = 'http'; 
                   8586:                     }
1.968     raeburn  8587:                 } else {
1.969     raeburn  8588:                     $protocol{$id} = 'http';
1.968     raeburn  8589:                 }
1.852     albertel 8590: 	    }
                   8591: 	}
                   8592:     }
1.864     albertel 8593:     
                   8594:     sub reset_hosts_info {
1.897     albertel 8595: 	&purge_remembered();
1.864     albertel 8596: 	&reset_domain_info();
                   8597: 	&reset_hosts_ip_info();
1.892     albertel 8598: 	undef(%name_to_host);
1.864     albertel 8599: 	undef(%hostname);
                   8600: 	undef(%hostdom);
                   8601: 	undef(%libserv);
                   8602: 	undef($loaded);
                   8603:     }
1.1       albertel 8604: 
1.852     albertel 8605:     sub load_hosts_tab {
1.869     albertel 8606: 	my ($ignore_cache) = @_;
                   8607: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8608: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8609: 	my @config = <$config>;
                   8610: 	&parse_hosts_tab(\@config);
                   8611: 	close($config);
                   8612: 	$loaded=1;
1.1       albertel 8613:     }
1.852     albertel 8614: 
1.838     albertel 8615:     sub hostname {
1.852     albertel 8616: 	&load_hosts_tab() if (!$loaded);
                   8617: 
1.838     albertel 8618: 	my ($lonid) = @_;
                   8619: 	return $hostname{$lonid};
                   8620:     }
1.845     albertel 8621: 
1.838     albertel 8622:     sub all_hostnames {
1.852     albertel 8623: 	&load_hosts_tab() if (!$loaded);
                   8624: 
1.838     albertel 8625: 	return %hostname;
                   8626:     }
1.845     albertel 8627: 
1.888     albertel 8628:     sub all_names {
                   8629: 	&load_hosts_tab() if (!$loaded);
                   8630: 
                   8631: 	return %name_to_host;
                   8632:     }
                   8633: 
1.974     raeburn  8634:     sub all_host_domain {
                   8635:         &load_hosts_tab() if (!$loaded);
                   8636:         return %hostdom;
                   8637:     }
                   8638: 
1.845     albertel 8639:     sub is_library {
1.852     albertel 8640: 	&load_hosts_tab() if (!$loaded);
                   8641: 
1.845     albertel 8642: 	return exists($libserv{$_[0]});
                   8643:     }
                   8644: 
                   8645:     sub all_library {
1.852     albertel 8646: 	&load_hosts_tab() if (!$loaded);
                   8647: 
1.845     albertel 8648: 	return %libserv;
                   8649:     }
                   8650: 
1.841     albertel 8651:     sub get_servers {
1.852     albertel 8652: 	&load_hosts_tab() if (!$loaded);
                   8653: 
1.841     albertel 8654: 	my ($domain,$type) = @_;
                   8655: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8656: 	                                          : %hostname;
                   8657: 	my %result;
1.842     albertel 8658: 	if (ref($domain) eq 'ARRAY') {
                   8659: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8660: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8661: 		    $result{$host} = $hostname;
                   8662: 		}
                   8663: 	    }
                   8664: 	} else {
                   8665: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8666: 		if ($hostdom{$host} eq $domain) {
                   8667: 		    $result{$host} = $hostname;
                   8668: 		}
1.841     albertel 8669: 	    }
                   8670: 	}
                   8671: 	return %result;
                   8672:     }
1.845     albertel 8673: 
1.844     albertel 8674:     sub host_domain {
1.852     albertel 8675: 	&load_hosts_tab() if (!$loaded);
                   8676: 
1.844     albertel 8677: 	my ($lonid) = @_;
                   8678: 	return $hostdom{$lonid};
                   8679:     }
                   8680: 
1.841     albertel 8681:     sub all_domains {
1.852     albertel 8682: 	&load_hosts_tab() if (!$loaded);
                   8683: 
1.841     albertel 8684: 	my %seen;
                   8685: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8686: 	return @uniq;
                   8687:     }
1.1       albertel 8688: }
                   8689: 
1.847     albertel 8690: { 
                   8691:     my %iphost;
1.856     albertel 8692:     my %name_to_ip;
                   8693:     my %lonid_to_ip;
1.869     albertel 8694: 
1.847     albertel 8695:     sub get_hosts_from_ip {
                   8696: 	my ($ip) = @_;
                   8697: 	my %iphosts = &get_iphost();
                   8698: 	if (ref($iphosts{$ip})) {
                   8699: 	    return @{$iphosts{$ip}};
                   8700: 	}
                   8701: 	return;
1.839     albertel 8702:     }
1.864     albertel 8703:     
                   8704:     sub reset_hosts_ip_info {
                   8705: 	undef(%iphost);
                   8706: 	undef(%name_to_ip);
                   8707: 	undef(%lonid_to_ip);
                   8708:     }
1.856     albertel 8709: 
                   8710:     sub get_host_ip {
                   8711: 	my ($lonid) = @_;
                   8712: 	if (exists($lonid_to_ip{$lonid})) {
                   8713: 	    return $lonid_to_ip{$lonid};
                   8714: 	}
                   8715: 	my $name=&hostname($lonid);
                   8716:    	my $ip = gethostbyname($name);
                   8717: 	return if (!$ip || length($ip) ne 4);
                   8718: 	$ip=inet_ntoa($ip);
                   8719: 	$name_to_ip{$name}   = $ip;
                   8720: 	$lonid_to_ip{$lonid} = $ip;
                   8721: 	return $ip;
                   8722:     }
1.847     albertel 8723:     
                   8724:     sub get_iphost {
1.869     albertel 8725: 	my ($ignore_cache) = @_;
1.894     albertel 8726: 
1.869     albertel 8727: 	if (!$ignore_cache) {
                   8728: 	    if (%iphost) {
                   8729: 		return %iphost;
                   8730: 	    }
                   8731: 	    my ($ip_info,$cached)=
                   8732: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8733: 	    if ($cached) {
                   8734: 		%iphost      = %{$ip_info->[0]};
                   8735: 		%name_to_ip  = %{$ip_info->[1]};
                   8736: 		%lonid_to_ip = %{$ip_info->[2]};
                   8737: 		return %iphost;
                   8738: 	    }
                   8739: 	}
1.894     albertel 8740: 
                   8741: 	# get yesterday's info for fallback
                   8742: 	my %old_name_to_ip;
                   8743: 	my ($ip_info,$cached)=
                   8744: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8745: 	if ($cached) {
                   8746: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8747: 	}
                   8748: 
1.888     albertel 8749: 	my %name_to_host = &all_names();
                   8750: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8751: 	    my $ip;
                   8752: 	    if (!exists($name_to_ip{$name})) {
                   8753: 		$ip = gethostbyname($name);
                   8754: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8755: 		    if (defined($old_name_to_ip{$name})) {
                   8756: 			$ip = $old_name_to_ip{$name};
                   8757: 			&logthis("Can't find $name defaulting to old $ip");
                   8758: 		    } else {
                   8759: 			&logthis("Name $name no IP found");
                   8760: 			next;
                   8761: 		    }
                   8762: 		} else {
                   8763: 		    $ip=inet_ntoa($ip);
1.847     albertel 8764: 		}
                   8765: 		$name_to_ip{$name} = $ip;
                   8766: 	    } else {
                   8767: 		$ip = $name_to_ip{$name};
1.653     albertel 8768: 	    }
1.888     albertel 8769: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8770: 		$lonid_to_ip{$id} = $ip;
                   8771: 	    }
                   8772: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8773: 	}
1.869     albertel 8774: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8775: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8776: 				      48*60*60);
1.869     albertel 8777: 
1.847     albertel 8778: 	return %iphost;
1.598     albertel 8779:     }
                   8780: }
                   8781: 
1.862     albertel 8782: BEGIN {
                   8783: 
                   8784: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8785:     unless ($readit) {
                   8786: {
                   8787:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8788:     %perlvar = (%perlvar,%{$configvars});
                   8789: }
                   8790: 
                   8791: 
1.1       albertel 8792: # ------------------------------------------------------ Read spare server file
                   8793: {
1.448     albertel 8794:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8795: 
                   8796:     while (my $configline=<$config>) {
                   8797:        chomp($configline);
1.284     matthew  8798:        if ($configline) {
1.784     albertel 8799: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8800: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8801: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8802:        }
                   8803:     }
1.448     albertel 8804:     close($config);
1.1       albertel 8805: }
1.11      www      8806: # ------------------------------------------------------------ Read permissions
                   8807: {
1.448     albertel 8808:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8809: 
                   8810:     while (my $configline=<$config>) {
1.448     albertel 8811: 	chomp($configline);
                   8812: 	if ($configline) {
                   8813: 	    my ($role,$perm)=split(/ /,$configline);
                   8814: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8815: 	}
1.11      www      8816:     }
1.448     albertel 8817:     close($config);
1.11      www      8818: }
                   8819: 
                   8820: # -------------------------------------------- Read plain texts for permissions
                   8821: {
1.448     albertel 8822:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8823: 
                   8824:     while (my $configline=<$config>) {
1.448     albertel 8825: 	chomp($configline);
                   8826: 	if ($configline) {
1.742     raeburn  8827: 	    my ($short,@plain)=split(/:/,$configline);
                   8828:             %{$prp{$short}} = ();
                   8829: 	    if (@plain > 0) {
                   8830:                 $prp{$short}{'std'} = $plain[0];
                   8831:                 for (my $i=1; $i<@plain; $i++) {
                   8832:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8833:                 }
                   8834:             }
1.448     albertel 8835: 	}
1.135     www      8836:     }
1.448     albertel 8837:     close($config);
1.135     www      8838: }
                   8839: 
                   8840: # ---------------------------------------------------------- Read package table
                   8841: {
1.448     albertel 8842:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8843: 
                   8844:     while (my $configline=<$config>) {
1.483     albertel 8845: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8846: 	chomp($configline);
                   8847: 	my ($short,$plain)=split(/:/,$configline);
                   8848: 	my ($pack,$name)=split(/\&/,$short);
                   8849: 	if ($plain ne '') {
                   8850: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8851: 	    $packagetab{$short}=$plain; 
                   8852: 	}
1.11      www      8853:     }
1.448     albertel 8854:     close($config);
1.329     matthew  8855: }
                   8856: 
                   8857: # ------------- set up temporary directory
                   8858: {
                   8859:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8860: 
1.11      www      8861: }
                   8862: 
1.794     albertel 8863: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8864: 				'compress_threshold'=> 20_000,
                   8865:  			        });
1.185     www      8866: 
1.281     www      8867: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8868: $dumpcount=0;
1.958     www      8869: $locknum=0;
1.22      www      8870: 
1.163     harris41 8871: &logtouch();
1.672     albertel 8872: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8873: $readit=1;
1.564     albertel 8874:     {
                   8875: 	use integer;
                   8876: 	my $test=(2**32)+1;
1.568     albertel 8877: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8878: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8879:     }
1.195     www      8880: }
1.1       albertel 8881: }
1.179     www      8882: 
1.1       albertel 8883: 1;
1.191     harris41 8884: __END__
                   8885: 
1.243     albertel 8886: =pod
                   8887: 
1.191     harris41 8888: =head1 NAME
                   8889: 
1.243     albertel 8890: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8891: 
                   8892: =head1 SYNOPSIS
                   8893: 
1.243     albertel 8894: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8895: 
                   8896:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8897: 
1.243     albertel 8898: Common parameters:
                   8899: 
                   8900: =over 4
                   8901: 
                   8902: =item *
                   8903: 
                   8904: $uname : an internal username (if $cname expecting a course Id specifically)
                   8905: 
                   8906: =item *
                   8907: 
                   8908: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8909: 
                   8910: =item *
                   8911: 
                   8912: $symb : a resource instance identifier
                   8913: 
                   8914: =item *
                   8915: 
                   8916: $namespace : the name of a .db file that contains the data needed or
                   8917: being set.
                   8918: 
                   8919: =back
                   8920: 
1.394     bowersj2 8921: =head1 OVERVIEW
1.191     harris41 8922: 
1.394     bowersj2 8923: lonnet provides subroutines which interact with the
                   8924: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8925: about classes, users, and resources.
1.243     albertel 8926: 
                   8927: For many of these objects you can also use this to store data about
                   8928: them or modify them in various ways.
1.191     harris41 8929: 
1.394     bowersj2 8930: =head2 Symbs
1.191     harris41 8931: 
1.394     bowersj2 8932: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8933: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8934: map, the resource number of the resource in the map, and the URL of
                   8935: the resource itself. The latter is somewhat redundant, but might help
                   8936: if maps change.
                   8937: 
                   8938: An example is
                   8939: 
                   8940:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8941: 
                   8942: The respective map entry is
                   8943: 
                   8944:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8945:   title="Problem 2">
                   8946:  </resource>
                   8947: 
                   8948: Symbs are used by the random number generator, as well as to store and
                   8949: restore data specific to a certain instance of for example a problem.
                   8950: 
                   8951: =head2 Storing And Retrieving Data
                   8952: 
                   8953: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8954: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8955: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8956: is is the non-critical message twin of cstore. These functions are for
                   8957: handlers to store a perl hash to a user's permanent data space in an
                   8958: easy manner, and to retrieve it again on another call. It is expected
                   8959: that a handler would use this once at the beginning to retrieve data,
                   8960: and then again once at the end to send only the new data back.
                   8961: 
                   8962: The data is stored in the user's data directory on the user's
                   8963: homeserver under the ID of the course.
                   8964: 
                   8965: The hash that is returned by restore will have all of the previous
                   8966: value for all of the elements of the hash.
                   8967: 
                   8968: Example:
                   8969: 
                   8970:  #creating a hash
                   8971:  my %hash;
                   8972:  $hash{'foo'}='bar';
                   8973: 
                   8974:  #storing it
                   8975:  &Apache::lonnet::cstore(\%hash);
                   8976: 
                   8977:  #changing a value
                   8978:  $hash{'foo'}='notbar';
                   8979: 
                   8980:  #adding a new value
                   8981:  $hash{'bar'}='foo';
                   8982:  &Apache::lonnet::cstore(\%hash);
                   8983: 
                   8984:  #retrieving the hash
                   8985:  my %history=&Apache::lonnet::restore();
                   8986: 
                   8987:  #print the hash
                   8988:  foreach my $key (sort(keys(%history))) {
                   8989:    print("\%history{$key} = $history{$key}");
                   8990:  }
                   8991: 
                   8992: Will print out:
1.191     harris41 8993: 
1.394     bowersj2 8994:  %history{1:foo} = bar
                   8995:  %history{1:keys} = foo:timestamp
                   8996:  %history{1:timestamp} = 990455579
                   8997:  %history{2:bar} = foo
                   8998:  %history{2:foo} = notbar
                   8999:  %history{2:keys} = foo:bar:timestamp
                   9000:  %history{2:timestamp} = 990455580
                   9001:  %history{bar} = foo
                   9002:  %history{foo} = notbar
                   9003:  %history{timestamp} = 990455580
                   9004:  %history{version} = 2
                   9005: 
                   9006: Note that the special hash entries C<keys>, C<version> and
                   9007: C<timestamp> were added to the hash. C<version> will be equal to the
                   9008: total number of versions of the data that have been stored. The
                   9009: C<timestamp> attribute will be the UNIX time the hash was
                   9010: stored. C<keys> is available in every historical section to list which
                   9011: keys were added or changed at a specific historical revision of a
                   9012: hash.
                   9013: 
                   9014: B<Warning>: do not store the hash that restore returns directly. This
                   9015: will cause a mess since it will restore the historical keys as if the
                   9016: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9017: 
1.394     bowersj2 9018: Calling convention:
1.191     harris41 9019: 
1.394     bowersj2 9020:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9021:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9022: 
1.394     bowersj2 9023: For more detailed information, see lonnet specific documentation.
1.191     harris41 9024: 
1.394     bowersj2 9025: =head1 RETURN MESSAGES
1.191     harris41 9026: 
1.394     bowersj2 9027: =over 4
1.191     harris41 9028: 
1.394     bowersj2 9029: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9030: 
1.394     bowersj2 9031: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9032: when the connection is brought back up
1.191     harris41 9033: 
1.394     bowersj2 9034: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9035: for later delivery
1.191     harris41 9036: 
1.967     bisitz   9037: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9038: 
1.394     bowersj2 9039: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9040: that was requested
1.191     harris41 9041: 
1.243     albertel 9042: =back
1.191     harris41 9043: 
1.243     albertel 9044: =head1 PUBLIC SUBROUTINES
1.191     harris41 9045: 
1.243     albertel 9046: =head2 Session Environment Functions
1.191     harris41 9047: 
1.243     albertel 9048: =over 4
1.191     harris41 9049: 
1.394     bowersj2 9050: =item * 
                   9051: X<appenv()>
1.949     raeburn  9052: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9053: the user envirnoment file, and will be restored for each access this
1.620     albertel 9054: user makes during this session, also modifies the %env for the current
1.949     raeburn  9055: process. Optional rolesarrayref - if defined contains a reference to an array
                   9056: of roles which are exempt from the restriction on modifying user.role entries 
                   9057: in the user's environment.db and in %env.    
1.191     harris41 9058: 
                   9059: =item *
1.394     bowersj2 9060: X<delenv()>
                   9061: B<delenv($regexp)>: removes all items from the session
                   9062: environment file that matches the regular expression in $regexp. The
1.620     albertel 9063: values are also delted from the current processes %env.
1.191     harris41 9064: 
1.795     albertel 9065: =item * get_env_multiple($name) 
                   9066: 
                   9067: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9068: values may be defined and end up as an array ref.
                   9069: 
                   9070: returns an array of values
                   9071: 
1.243     albertel 9072: =back
                   9073: 
                   9074: =head2 User Information
1.191     harris41 9075: 
1.243     albertel 9076: =over 4
1.191     harris41 9077: 
                   9078: =item *
1.394     bowersj2 9079: X<queryauthenticate()>
                   9080: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9081: authentication scheme
                   9082: 
                   9083: =item *
1.394     bowersj2 9084: X<authenticate()>
                   9085: B<authenticate($uname,$upass,$udom)>: try to
                   9086: authenticate user from domain's lib servers (first use the current
                   9087: one). C<$upass> should be the users password.
1.191     harris41 9088: 
                   9089: =item *
1.394     bowersj2 9090: X<homeserver()>
                   9091: B<homeserver($uname,$udom)>: find the server which has
                   9092: the user's directory and files (there must be only one), this caches
                   9093: the answer, and also caches if there is a borken connection.
1.191     harris41 9094: 
                   9095: =item *
1.394     bowersj2 9096: X<idget()>
                   9097: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9098: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9099: username, and only 1 username per ID in a specific domain) (returns
                   9100: hash: id=>name,id=>name)
1.191     harris41 9101: 
                   9102: =item *
1.394     bowersj2 9103: X<idrget()>
                   9104: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9105: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9106: 
                   9107: =item *
1.394     bowersj2 9108: X<idput()>
                   9109: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9110: 
                   9111: =item *
1.394     bowersj2 9112: X<rolesinit()>
                   9113: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9114: 
                   9115: =item *
1.551     albertel 9116: X<getsection()>
                   9117: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9118: course $cname, return section name/number or '' for "not in course"
                   9119: and '-1' for "no section"
                   9120: 
                   9121: =item *
1.394     bowersj2 9122: X<userenvironment()>
                   9123: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9124: passed in @what from the requested user's environment, returns a hash
                   9125: 
1.858     raeburn  9126: =item * 
                   9127: X<userlog_query()>
1.859     albertel 9128: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9129: activity.log file. %filters defines filters applied when parsing the
                   9130: log file. These can be start or end timestamps, or the type of action
                   9131: - log to look for Login or Logout events, check for Checkin or
                   9132: Checkout, role for role selection. The response is in the form
                   9133: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9134: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9135: 
1.243     albertel 9136: =back
                   9137: 
                   9138: =head2 User Roles
                   9139: 
                   9140: =over 4
                   9141: 
                   9142: =item *
                   9143: 
1.810     raeburn  9144: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9145:  F: full access
                   9146:  U,I,K: authentication modes (cxx only)
                   9147:  '': forbidden
                   9148:  1: user needs to choose course
                   9149:  2: browse allowed
1.766     albertel 9150:  A: passphrase authentication needed
1.243     albertel 9151: 
                   9152: =item *
                   9153: 
                   9154: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9155: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9156: and course level
                   9157: 
                   9158: =item *
                   9159: 
                   9160: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9161: explanation of a user role term
                   9162: 
1.832     raeburn  9163: =item *
                   9164: 
1.935     raeburn  9165: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9166: All arguments are optional. Returns a hash of a roles, either for
                   9167: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9168: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9169: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9170: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9171: For each key, value is set to colon-separated start and end times for
                   9172: the role.  If no username and domain are specified, will default to
1.934     raeburn  9173: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9174: of role statuses (active, future or previous), roles 
                   9175: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9176: to restrict the list of roles reported. If no array ref is 
                   9177: provided for types, will default to return only active roles.
1.834     albertel 9178: 
1.243     albertel 9179: =back
                   9180: 
                   9181: =head2 User Modification
                   9182: 
                   9183: =over 4
                   9184: 
                   9185: =item *
                   9186: 
1.957     raeburn  9187: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9188: user for the level given by URL.  Optional start and end dates (leave empty
                   9189: string or zero for "no date")
1.191     harris41 9190: 
                   9191: =item *
                   9192: 
1.243     albertel 9193: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9194: change a users, password, possible return values are: ok,
                   9195: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9196: refused
1.191     harris41 9197: 
                   9198: =item *
                   9199: 
1.243     albertel 9200: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9201: 
                   9202: =item *
                   9203: 
1.963     raeburn  9204: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9205:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9206: modify user
1.191     harris41 9207: 
                   9208: =item *
                   9209: 
1.286     matthew  9210: modifystudent
                   9211: 
1.957     raeburn  9212: modify a student's enrollment and identification information.
1.286     matthew  9213: The course id is resolved based on the current users environment.  
                   9214: This means the envoking user must be a course coordinator or otherwise
                   9215: associated with a course.
                   9216: 
1.297     matthew  9217: This call is essentially a wrapper for lonnet::modifyuser and
                   9218: lonnet::modify_student_enrollment
1.286     matthew  9219: 
                   9220: Inputs: 
                   9221: 
                   9222: =over 4
                   9223: 
1.957     raeburn  9224: =item B<$udom> Student's loncapa domain
1.286     matthew  9225: 
1.957     raeburn  9226: =item B<$uname> Student's loncapa login name
1.286     matthew  9227: 
1.964     bisitz   9228: =item B<$uid> Student/Employee ID
1.286     matthew  9229: 
1.957     raeburn  9230: =item B<$umode> Student's authentication mode
1.286     matthew  9231: 
1.957     raeburn  9232: =item B<$upass> Student's password
1.286     matthew  9233: 
1.957     raeburn  9234: =item B<$first> Student's first name
1.286     matthew  9235: 
1.957     raeburn  9236: =item B<$middle> Student's middle name
1.286     matthew  9237: 
1.957     raeburn  9238: =item B<$last> Student's last name
1.286     matthew  9239: 
1.957     raeburn  9240: =item B<$gene> Student's generation
1.286     matthew  9241: 
1.957     raeburn  9242: =item B<$usec> Student's section in course
1.286     matthew  9243: 
                   9244: =item B<$end> Unix time of the roles expiration
                   9245: 
                   9246: =item B<$start> Unix time of the roles start date
                   9247: 
                   9248: =item B<$forceid> If defined, allow $uid to be changed
                   9249: 
                   9250: =item B<$desiredhome> server to use as home server for student
                   9251: 
1.957     raeburn  9252: =item B<$email> Student's permanent e-mail address
                   9253: 
                   9254: =item B<$type> Type of enrollment (auto or manual)
                   9255: 
1.963     raeburn  9256: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9257: 
                   9258: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9259: 
1.963     raeburn  9260: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9261: 
1.963     raeburn  9262: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9263: 
1.963     raeburn  9264: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9265: 
1.286     matthew  9266: =back
1.297     matthew  9267: 
                   9268: =item *
                   9269: 
                   9270: modify_student_enrollment
                   9271: 
                   9272: Change a students enrollment status in a class.  The environment variable
                   9273: 'role.request.course' must be defined for this function to proceed.
                   9274: 
                   9275: Inputs:
                   9276: 
                   9277: =over 4
                   9278: 
                   9279: =item $udom, students domain
                   9280: 
                   9281: =item $uname, students name
                   9282: 
                   9283: =item $uid, students user id
                   9284: 
                   9285: =item $first, students first name
                   9286: 
                   9287: =item $middle
                   9288: 
                   9289: =item $last
                   9290: 
                   9291: =item $gene
                   9292: 
                   9293: =item $usec
                   9294: 
                   9295: =item $end
                   9296: 
                   9297: =item $start
                   9298: 
1.957     raeburn  9299: =item $type
                   9300: 
                   9301: =item $locktype
                   9302: 
                   9303: =item $cid
                   9304: 
                   9305: =item $selfenroll
                   9306: 
                   9307: =item $context
                   9308: 
1.297     matthew  9309: =back
                   9310: 
1.191     harris41 9311: 
                   9312: =item *
                   9313: 
1.243     albertel 9314: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9315: custom role; give a custom role to a user for the level given by URL.  Specify
                   9316: name and domain of role author, and role name
1.191     harris41 9317: 
                   9318: =item *
                   9319: 
1.243     albertel 9320: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9321: 
                   9322: =item *
                   9323: 
1.243     albertel 9324: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9325: 
                   9326: =back
                   9327: 
                   9328: =head2 Course Infomation
                   9329: 
                   9330: =over 4
1.191     harris41 9331: 
                   9332: =item *
                   9333: 
1.631     albertel 9334: coursedescription($courseid) : returns a hash of information about the
                   9335: specified course id, including all environment settings for the
                   9336: course, the description of the course will be in the hash under the
                   9337: key 'description'
1.191     harris41 9338: 
                   9339: =item *
                   9340: 
1.624     albertel 9341: resdata($name,$domain,$type,@which) : request for current parameter
                   9342: setting for a specific $type, where $type is either 'course' or 'user',
                   9343: @what should be a list of parameters to ask about. This routine caches
                   9344: answers for 5 minutes.
1.243     albertel 9345: 
1.877     foxr     9346: =item *
                   9347: 
                   9348: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9349: data base, returning a hash that is keyed by the resource name and has
                   9350: values that are the resource value.  I believe that the timestamps and
                   9351: versions are also returned.
                   9352: 
                   9353: 
1.243     albertel 9354: =back
                   9355: 
                   9356: =head2 Course Modification
                   9357: 
                   9358: =over 4
1.191     harris41 9359: 
                   9360: =item *
                   9361: 
1.243     albertel 9362: writecoursepref($courseid,%prefs) : write preferences (environment
                   9363: database) for a course
1.191     harris41 9364: 
                   9365: =item *
                   9366: 
1.243     albertel 9367: createcourse($udom,$description,$url) : make/modify course
                   9368: 
                   9369: =back
                   9370: 
                   9371: =head2 Resource Subroutines
                   9372: 
                   9373: =over 4
1.191     harris41 9374: 
                   9375: =item *
                   9376: 
1.243     albertel 9377: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9378: 
                   9379: =item *
                   9380: 
1.243     albertel 9381: repcopy($filename) : subscribes to the requested file, and attempts to
                   9382: replicate from the owning library server, Might return
1.607     raeburn  9383: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9384: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9385: resource. Expects the local filesystem pathname
                   9386: (/home/httpd/html/res/....)
                   9387: 
                   9388: =back
                   9389: 
                   9390: =head2 Resource Information
                   9391: 
                   9392: =over 4
1.191     harris41 9393: 
                   9394: =item *
                   9395: 
1.243     albertel 9396: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9397: a vairety of different possible values, $varname should be a request
                   9398: string, and the other parameters can be used to specify who and what
                   9399: one is asking about.
                   9400: 
                   9401: Possible values for $varname are environment.lastname (or other item
                   9402: from the envirnment hash), user.name (or someother aspect about the
                   9403: user), resource.0.maxtries (or some other part and parameter of a
                   9404: resource)
1.204     albertel 9405: 
                   9406: =item *
                   9407: 
1.243     albertel 9408: directcondval($number) : get current value of a condition; reads from a state
                   9409: string
1.204     albertel 9410: 
                   9411: =item *
                   9412: 
1.243     albertel 9413: condval($condidx) : value of condition index based on state
1.204     albertel 9414: 
                   9415: =item *
                   9416: 
1.243     albertel 9417: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9418: resource's metadata, $what should be either a specific key, or either
                   9419: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9420: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9421: 
                   9422: this function automatically caches all requests
1.191     harris41 9423: 
                   9424: =item *
                   9425: 
1.243     albertel 9426: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9427: network of library servers; returns file handle of where SQL and regex results
                   9428: will be stored for query
1.191     harris41 9429: 
                   9430: =item *
                   9431: 
1.243     albertel 9432: symbread($filename) : return symbolic list entry (filename argument optional);
                   9433: returns the data handle
1.191     harris41 9434: 
                   9435: =item *
                   9436: 
1.243     albertel 9437: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9438: a possible symb for the URL in $thisfn, and if is an encryypted
                   9439: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9440: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9441: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9442: 
1.191     harris41 9443: 
                   9444: =item *
                   9445: 
1.243     albertel 9446: symbclean($symb) : removes versions numbers from a symb, returns the
                   9447: cleaned symb
1.191     harris41 9448: 
                   9449: =item *
                   9450: 
1.243     albertel 9451: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9452: course map, user must be in a course for it to work.
1.191     harris41 9453: 
                   9454: =item *
                   9455: 
1.243     albertel 9456: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9461: a random seed, all arguments are optional, if they aren't sent it uses the
                   9462: environment to derive them. Note: if symb isn't sent and it can't get one
                   9463: from &symbread it will use the current time as its return value
1.191     harris41 9464: 
                   9465: =item *
                   9466: 
1.243     albertel 9467: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9468: unfakeable, receipt
1.191     harris41 9469: 
                   9470: =item *
                   9471: 
1.620     albertel 9472: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9473: 
                   9474: =item *
                   9475: 
1.243     albertel 9476: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9477: 
                   9478: =item *
                   9479: 
1.243     albertel 9480: 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 9481: 
                   9482: =item *
                   9483: 
1.243     albertel 9484: 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 9485: 
                   9486: =item *
                   9487: 
1.243     albertel 9488: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9489: 
                   9490: =item *
                   9491: 
1.243     albertel 9492: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9493: forcing spreadsheet to reevaluate the resource scores next time.
                   9494: 
                   9495: =back
                   9496: 
                   9497: =head2 Storing/Retreiving Data
                   9498: 
                   9499: =over 4
1.191     harris41 9500: 
                   9501: =item *
                   9502: 
1.243     albertel 9503: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9504: for this url; hashref needs to be given and should be a \%hashname; the
                   9505: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9506: be derived from the env
1.191     harris41 9507: 
                   9508: =item *
                   9509: 
1.243     albertel 9510: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9511: uses critical subroutine
1.191     harris41 9512: 
                   9513: =item *
                   9514: 
1.243     albertel 9515: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9516: all args are optional
1.191     harris41 9517: 
                   9518: =item *
                   9519: 
1.717     albertel 9520: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9521: dumps the complete (or key matching regexp) namespace into a hash
                   9522: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9523: normally &store()ed into
                   9524: 
                   9525: $range should be either an integer '100' (give me the first 100
                   9526:                                            matching records)
                   9527:               or be  two integers sperated by a - with no spaces
                   9528:                  '30-50' (give me the 30th through the 50th matching
                   9529:                           records)
                   9530: 
                   9531: 
                   9532: =item *
                   9533: 
                   9534: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9535: replaces a &store() version of data with a replacement set of data
                   9536: for a particular resource in a namespace passed in the $storehash hash 
                   9537: reference
                   9538: 
                   9539: =item *
                   9540: 
1.243     albertel 9541: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9542: works very similar to store/cstore, but all data is stored in a
                   9543: temporary location and can be reset using tmpreset, $storehash should
                   9544: be a hash reference, returns nothing on success
1.191     harris41 9545: 
                   9546: =item *
                   9547: 
1.243     albertel 9548: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9549: similar to restore, but all data is stored in a temporary location and
                   9550: can be reset using tmpreset. Returns a hash of values on success,
                   9551: error string otherwise.
1.191     harris41 9552: 
                   9553: =item *
                   9554: 
1.243     albertel 9555: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9556: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9557: 
                   9558: =item *
                   9559: 
1.243     albertel 9560: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9561: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9562: 
                   9563: =item *
                   9564: 
1.243     albertel 9565: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9566: namesp ($udom and $uname are optional)
1.191     harris41 9567: 
                   9568: =item *
                   9569: 
1.702     albertel 9570: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9571: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9572: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9573: 
1.702     albertel 9574: $range should be either an integer '100' (give me the first 100
                   9575:                                            matching records)
                   9576:               or be  two integers sperated by a - with no spaces
                   9577:                  '30-50' (give me the 30th through the 50th matching
                   9578:                           records)
1.449     matthew  9579: =item *
                   9580: 
                   9581: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9582: $store can be a scalar, an array reference, or if the amount to be 
                   9583: incremented is > 1, a hash reference.
                   9584: 
                   9585: ($udom and $uname are optional)
1.191     harris41 9586: 
                   9587: =item *
                   9588: 
1.243     albertel 9589: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9590: ($udom and $uname are optional)
1.191     harris41 9591: 
                   9592: =item *
                   9593: 
1.243     albertel 9594: cput($namespace,$storehash,$udom,$uname) : critical put
                   9595: ($udom and $uname are optional)
1.191     harris41 9596: 
                   9597: =item *
                   9598: 
1.748     albertel 9599: newput($namespace,$storehash,$udom,$uname) :
                   9600: 
                   9601: Attempts to store the items in the $storehash, but only if they don't
                   9602: currently exist, if this succeeds you can be certain that you have 
                   9603: successfully created a new key value pair in the $namespace db.
                   9604: 
                   9605: 
                   9606: Args:
                   9607:  $namespace: name of database to store values to
                   9608:  $storehash: hashref to store to the db
                   9609:  $udom: (optional) domain of user containing the db
                   9610:  $uname: (optional) name of user caontaining the db
                   9611: 
                   9612: Returns:
                   9613:  'ok' -> succeeded in storing all keys of $storehash
                   9614:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9615:                         least <key> already existed in the db (other
                   9616:                         requested keys may also already exist)
1.967     bisitz   9617:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9618:  'con_lost' -> unable to contact request server
                   9619:  'refused' -> action was not allowed by remote machine
                   9620: 
                   9621: 
                   9622: =item *
                   9623: 
1.243     albertel 9624: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9625: reference filled in from namesp (encrypts the return communication)
                   9626: ($udom and $uname are optional)
1.191     harris41 9627: 
                   9628: =item *
                   9629: 
1.243     albertel 9630: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9631: critical subroutine
                   9632: 
1.806     raeburn  9633: =item *
                   9634: 
1.860     raeburn  9635: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9636: array reference filled in from namespace found in domain level on either
                   9637: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9638: 
                   9639: =item *
                   9640: 
1.860     raeburn  9641: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9642: domain level either on specified domain server ($uhome) or primary domain 
                   9643: server ($udom and $uhome are optional)
1.806     raeburn  9644: 
1.943     raeburn  9645: =item * 
                   9646: 
                   9647: get_domain_defaults($target_domain) : returns hash with defaults for
                   9648: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9649: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9650: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9651: Values are retrieved from cache (if current), or from domain's configuration.db
                   9652: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9653: or lonTabs/domain.tab. 
                   9654: 
                   9655: %domdefaults = &get_auth_defaults($target_domain);
                   9656: 
1.243     albertel 9657: =back
                   9658: 
                   9659: =head2 Network Status Functions
                   9660: 
                   9661: =over 4
1.191     harris41 9662: 
                   9663: =item *
                   9664: 
                   9665: dirlist($uri) : return directory list based on URI
                   9666: 
                   9667: =item *
                   9668: 
1.243     albertel 9669: spareserver() : find server with least workload from spare.tab
                   9670: 
                   9671: =back
                   9672: 
                   9673: =head2 Apache Request
                   9674: 
                   9675: =over 4
1.191     harris41 9676: 
                   9677: =item *
                   9678: 
1.243     albertel 9679: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9680: localhost, posts hash
                   9681: 
                   9682: =back
                   9683: 
                   9684: =head2 Data to String to Data
                   9685: 
                   9686: =over 4
1.191     harris41 9687: 
                   9688: =item *
                   9689: 
1.243     albertel 9690: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9691: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9692: 
                   9693: =item *
                   9694: 
1.243     albertel 9695: hashref2str($hashref) : convert a hashref into a string complete with
                   9696: escaping and '=' and '&' separators, supports elements that are
                   9697: arrayrefs and hashrefs
1.191     harris41 9698: 
                   9699: =item *
                   9700: 
1.243     albertel 9701: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9702: with escaping and '&' separators, supports elements that are arrayrefs
                   9703: and hashrefs
1.191     harris41 9704: 
                   9705: =item *
                   9706: 
1.243     albertel 9707: str2hash($string) : convert string to hash using unescaping and
                   9708: splitting on '=' and '&', supports elements that are arrayrefs and
                   9709: hashrefs
1.191     harris41 9710: 
                   9711: =item *
                   9712: 
1.243     albertel 9713: str2array($string) : convert string to hash using unescaping and
                   9714: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9715: 
                   9716: =back
                   9717: 
                   9718: =head2 Logging Routines
                   9719: 
                   9720: =over 4
                   9721: 
                   9722: These routines allow one to make log messages in the lonnet.log and
                   9723: lonnet.perm logfiles.
1.191     harris41 9724: 
                   9725: =item *
                   9726: 
1.243     albertel 9727: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9728: 
                   9729: =item *
                   9730: 
1.243     albertel 9731: logthis() : append message to the normal lonnet.log file, it gets
                   9732: preiodically rolled over and deleted.
1.191     harris41 9733: 
                   9734: =item *
                   9735: 
1.243     albertel 9736: logperm() : append a permanent message to lonnet.perm.log, this log
                   9737: file never gets deleted by any automated portion of the system, only
                   9738: messages of critical importance should go in here.
                   9739: 
                   9740: =back
                   9741: 
                   9742: =head2 General File Helper Routines
                   9743: 
                   9744: =over 4
1.191     harris41 9745: 
                   9746: =item *
                   9747: 
1.481     raeburn  9748: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9749: (a) files in /uploaded
                   9750:   (i) If a local copy of the file exists - 
                   9751:       compares modification date of local copy with last-modified date for 
                   9752:       definitive version stored on home server for course. If local copy is 
                   9753:       stale, requests a new version from the home server and stores it. 
                   9754:       If the original has been removed from the home server, then local copy 
                   9755:       is unlinked.
                   9756:   (ii) If local copy does not exist -
                   9757:       requests the file from the home server and stores it. 
                   9758:   
                   9759:   If $caller is 'uploadrep':  
                   9760:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9761:     for request for files originally uploaded via DOCS. 
                   9762:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9763:   
                   9764:   Otherwise:
                   9765:      This indicates a call from the content generation phase of the request.
                   9766:      -  returns the entire contents of the file or -1.
                   9767:      
                   9768: (b) files in /res
                   9769:    - returns the entire contents of a file or -1; 
                   9770:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9771: 
1.712     albertel 9772: 
                   9773: =item *
                   9774: 
                   9775: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9776:                   reference
                   9777: 
                   9778: returns either a stat() list of data about the file or an empty list
                   9779: if the file doesn't exist or couldn't find out about it (connection
                   9780: problems or user unknown)
                   9781: 
1.191     harris41 9782: =item *
                   9783: 
1.243     albertel 9784: filelocation($dir,$file) : returns file system location of a file
                   9785: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9786: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9787: and a file of ../bob will become /a/bob)
1.191     harris41 9788: 
                   9789: =item *
                   9790: 
                   9791: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9792: filelocation except for hrefs
                   9793: 
                   9794: =item *
                   9795: 
                   9796: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9797: 
1.243     albertel 9798: =back
                   9799: 
1.608     albertel 9800: =head2 Usererfile file routines (/uploaded*)
                   9801: 
                   9802: =over 4
                   9803: 
                   9804: =item *
                   9805: 
                   9806: userfileupload(): main rotine for putting a file in a user or course's
                   9807:                   filespace, arguments are,
                   9808: 
1.620     albertel 9809:  formname - required - this is the name of the element in $env where the
1.608     albertel 9810:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9811:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9812:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9813:  coursedoc - if true, store the file in the course of the active role
                   9814:              of the current user
                   9815:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9816:          if undefined, it will be placed in "unknown"
                   9817: 
                   9818:  (This routine calls clean_filename() to remove any dangerous
                   9819:  characters from the filename, and then calls finuserfileupload() to
                   9820:  complete the transaction)
                   9821: 
                   9822:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9823:  and /adm/notfound.html if unsuccessful
                   9824: 
                   9825: =item *
                   9826: 
                   9827: clean_filename(): routine for cleaing a filename up for storage in
                   9828:                  userfile space, argument is:
                   9829: 
                   9830:  filename - proposed filename
                   9831: 
                   9832: returns: the new clean filename
                   9833: 
                   9834: =item *
                   9835: 
                   9836: finishuserfileupload(): routine that creaes and sends the file to
                   9837: userspace, probably shouldn't be called directly
                   9838: 
                   9839:   docuname: username or courseid of destination for the file
                   9840:   docudom: domain of user/course of destination for the file
                   9841:   formname: same as for userfileupload()
                   9842:   fname: filename (inculding subdirectories) for the file
                   9843: 
                   9844:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9845:  and /adm/notfound.html if unsuccessful
                   9846: 
                   9847: =item *
                   9848: 
                   9849: renameuserfile(): renames an existing userfile to a new name
                   9850: 
                   9851:   Args:
                   9852:    docuname: username or courseid of destination for the file
                   9853:    docudom: domain of user/course of destination for the file
                   9854:    old: current file name (including any subdirs under userfiles)
                   9855:    new: desired file name (including any subdirs under userfiles)
                   9856: 
                   9857: =item *
                   9858: 
                   9859: mkdiruserfile(): creates a directory is a userfiles dir
                   9860: 
                   9861:   Args:
                   9862:    docuname: username or courseid of destination for the file
                   9863:    docudom: domain of user/course of destination for the file
                   9864:    dir: dir to create (including any subdirs under userfiles)
                   9865: 
                   9866: =item *
                   9867: 
                   9868: removeuserfile(): removes a file that exists in userfiles
                   9869: 
                   9870:   Args:
                   9871:    docuname: username or courseid of destination for the file
                   9872:    docudom: domain of user/course of destination for the file
                   9873:    fname: filname to delete (including any subdirs under userfiles)
                   9874: 
                   9875: =item *
                   9876: 
                   9877: removeuploadedurl(): convience function for removeuserfile()
                   9878: 
                   9879:   Args:
                   9880:    url:  a full /uploaded/... url to delete
                   9881: 
1.747     albertel 9882: =item * 
                   9883: 
                   9884: get_portfile_permissions():
                   9885:   Args:
                   9886:     domain: domain of user or course contain the portfolio files
                   9887:     user: name of user or num of course contain the portfolio files
                   9888:   Returns:
                   9889:     hashref of a dump of the proper file_permissions.db
                   9890:    
                   9891: 
                   9892: =item * 
                   9893: 
                   9894: get_access_controls():
                   9895: 
                   9896: Args:
                   9897:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9898:   group: (optional) the group you want the files associated with
                   9899:   file: (optional) the file you want access info on
                   9900: 
                   9901: Returns:
1.749     raeburn  9902:     a hash (keys are file names) of hashes containing
                   9903:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9904:         values are XML containing access control settings (see below) 
1.747     albertel 9905: 
                   9906: Internal notes:
                   9907: 
1.749     raeburn  9908:  access controls are stored in file_permissions.db as key=value pairs.
                   9909:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9910:         where scope -> public,guest,course,group,domains or users.
                   9911:               end -> UNIX time for end of access (0 -> no end date)
                   9912:               start -> UNIX time for start of access
                   9913: 
                   9914:     value -> XML description of access control
                   9915:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9916:             <start></start>
                   9917:             <end></end>
                   9918: 
                   9919:             <password></password>  for scope type = guest
                   9920: 
                   9921:             <domain></domain>     for scope type = course or group
                   9922:             <number></number>
                   9923:             <roles id="">
                   9924:              <role></role>
                   9925:              <access></access>
                   9926:              <section></section>
                   9927:              <group></group>
                   9928:             </roles>
                   9929: 
                   9930:             <dom></dom>         for scope type = domains
                   9931: 
                   9932:             <users>             for scope type = users
                   9933:              <user>
                   9934:               <uname></uname>
                   9935:               <udom></udom>
                   9936:              </user>
                   9937:             </users>
                   9938:            </scope> 
                   9939:               
                   9940:  Access data is also aggregated for each file in an additional key=value pair:
                   9941:  key -> path to file/file_name\0accesscontrol 
                   9942:  value -> reference to hash
                   9943:           hash contains key = value pairs
                   9944:           where key = uniqueID:scope_end_start
                   9945:                 value = UNIX time record was last updated
                   9946: 
                   9947:           Used to improve speed of look-ups of access controls for each file.  
                   9948:  
                   9949:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9950: 
                   9951: modify_access_controls():
                   9952: 
                   9953: Modifies access controls for a portfolio file
                   9954: Args
                   9955: 1. file name
                   9956: 2. reference to hash of required changes,
                   9957: 3. domain
                   9958: 4. username
                   9959:   where domain,username are the domain of the portfolio owner 
                   9960:   (either a user or a course) 
                   9961: 
                   9962: Returns:
                   9963: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9964: 2. result of deletions ('ok' or 'error', with error message).
                   9965: 3. reference to hash of any new or updated access controls.
                   9966: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9967:    key = integer (inbound ID)
                   9968:    value = uniqueID  
1.747     albertel 9969: 
1.608     albertel 9970: =back
                   9971: 
1.243     albertel 9972: =head2 HTTP Helper Routines
                   9973: 
                   9974: =over 4
                   9975: 
1.191     harris41 9976: =item *
                   9977: 
                   9978: escape() : unpack non-word characters into CGI-compatible hex codes
                   9979: 
                   9980: =item *
                   9981: 
                   9982: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9983: 
1.243     albertel 9984: =back
                   9985: 
                   9986: =head1 PRIVATE SUBROUTINES
                   9987: 
                   9988: =head2 Underlying communication routines (Shouldn't call)
                   9989: 
                   9990: =over 4
                   9991: 
                   9992: =item *
                   9993: 
                   9994: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9995: 
                   9996: =item *
                   9997: 
                   9998: reply() : uses subreply to send a message to remote machine, logs all failures
                   9999: 
                   10000: =item *
                   10001: 
                   10002: critical() : passes a critical message to another server; if cannot
                   10003: get through then place message in connection buffer directory and
                   10004: returns con_delayed, if incapable of saving message, returns
                   10005: con_failed
                   10006: 
                   10007: =item *
                   10008: 
                   10009: reconlonc() : tries to reconnect lonc client processes.
                   10010: 
                   10011: =back
                   10012: 
                   10013: =head2 Resource Access Logging
                   10014: 
                   10015: =over 4
                   10016: 
                   10017: =item *
                   10018: 
                   10019: flushcourselogs() : flush (save) buffer logs and access logs
                   10020: 
                   10021: =item *
                   10022: 
                   10023: courselog($what) : save message for course in hash
                   10024: 
                   10025: =item *
                   10026: 
                   10027: courseacclog($what) : save message for course using &courselog().  Perform
                   10028: special processing for specific resource types (problems, exams, quizzes, etc).
                   10029: 
1.191     harris41 10030: =item *
                   10031: 
                   10032: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10033: as a PerlChildExitHandler
1.243     albertel 10034: 
                   10035: =back
                   10036: 
                   10037: =head2 Other
                   10038: 
                   10039: =over 4
                   10040: 
                   10041: =item *
                   10042: 
                   10043: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10044: 
                   10045: =back
                   10046: 
                   10047: =cut
1.877     foxr     10048: 

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