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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.960   ! raeburn     4: # $Id: lonnet.pm,v 1.959 2008/05/29 05:44:53 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        42:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
1.957     raeburn    91: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                     92:         if (($cnum eq '') || ($cdom eq '')) {
                     93:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                     94:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                     95:         }
1.729     www        96: 	$logid++;
1.957     raeburn    97:         my $now = time();
                     98: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www        99: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       100: 				    { $id => {
                    101: 					'exe_uname' => $env{'user.name'},
                    102: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   103: 					'exe_time'  => $now,
1.730     www       104: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    105: 					'delflag'   => $delflag,
                    106: 					'logentry'  => $storehash,
                    107: 					'uname'     => $uname,
                    108: 					'udom'      => $udom,
                    109: 				    }
1.957     raeburn   110: 				  },$cdom,$cnum);
1.729     www       111:     }
                    112: }
1.1       albertel  113: 
1.163     harris41  114: sub logtouch {
                    115:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  116:     unless (-e "$execdir/logs/lonnet.log") {	
                    117: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  118: 	close $fh;
                    119:     }
                    120:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    121:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    122: }
                    123: 
1.1       albertel  124: sub logthis {
                    125:     my $message=shift;
                    126:     my $execdir=$perlvar{'lonDaemons'};
                    127:     my $now=time;
                    128:     my $local=localtime($now);
1.448     albertel  129:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    130: 	print $fh "$local ($$): $message\n";
                    131: 	close($fh);
                    132:     }
1.1       albertel  133:     return 1;
                    134: }
                    135: 
                    136: sub logperm {
                    137:     my $message=shift;
                    138:     my $execdir=$perlvar{'lonDaemons'};
                    139:     my $now=time;
                    140:     my $local=localtime($now);
1.448     albertel  141:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    142: 	print $fh "$now:$message:$local\n";
                    143: 	close($fh);
                    144:     }
1.1       albertel  145:     return 1;
                    146: }
                    147: 
1.850     albertel  148: sub create_connection {
1.853     albertel  149:     my ($hostname,$lonid) = @_;
1.851     albertel  150:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  151: 				     Type    => SOCK_STREAM,
                    152: 				     Timeout => 10);
                    153:     return 0 if (!$client);
1.890     albertel  154:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  155:     my $result = <$client>;
                    156:     chomp($result);
                    157:     return 1 if ($result eq 'done');
                    158:     return 0;
                    159: }
                    160: 
                    161: 
1.1       albertel  162: # -------------------------------------------------- Non-critical communication
                    163: sub subreply {
                    164:     my ($cmd,$server)=@_;
1.838     albertel  165:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      166:     #
                    167:     #  With loncnew process trimming, there's a timing hole between lonc server
                    168:     #  process exit and the master server picking up the listen on the AF_UNIX
                    169:     #  socket.  In that time interval, a lock file will exist:
                    170: 
                    171:     my $lockfile=$peerfile.".lock";
                    172:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    173: 	sleep(1);
                    174:     }
                    175:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      176:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      177:     #
1.550     foxr      178:     #   We'll give the connection a few tries before abandoning it.  If
                    179:     #   connection is not possible, we'll con_lost back to the client.
                    180:     #   
                    181:     my $client;
                    182:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    183: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    184: 				      Type    => SOCK_STREAM,
                    185: 				      Timeout => 10);
1.869     albertel  186: 	if ($client) {
1.550     foxr      187: 	    last;		# Connected!
1.850     albertel  188: 	} else {
1.853     albertel  189: 	    &create_connection(&hostname($server),$server);
1.550     foxr      190: 	}
1.850     albertel  191:         sleep(1);		# Try again later if failed connection.
1.550     foxr      192:     }
                    193:     my $answer;
                    194:     if ($client) {
1.704     albertel  195: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      196: 	$answer=<$client>;
                    197: 	if (!$answer) { $answer="con_lost"; }
                    198: 	chomp($answer);
                    199:     } else {
                    200: 	$answer = 'con_lost';	# Failed connection.
                    201:     }
1.1       albertel  202:     return $answer;
                    203: }
                    204: 
                    205: sub reply {
                    206:     my ($cmd,$server)=@_;
1.838     albertel  207:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  208:     my $answer=subreply($cmd,$server);
1.65      www       209:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  210:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       211:                 " $cmd to $server returned $answer</font>");
                    212:     }
1.1       albertel  213:     return $answer;
                    214: }
                    215: 
                    216: # ----------------------------------------------------------- Send USR1 to lonc
                    217: 
                    218: sub reconlonc {
1.891     albertel  219:     my ($lonid) = @_;
                    220:     my $hostname = &hostname($lonid);
                    221:     if ($lonid) {
                    222: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    223: 	if ($hostname && -e $peerfile) {
                    224: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    225: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    226: 					     Type    => SOCK_STREAM,
                    227: 					     Timeout => 10);
                    228: 	    if ($client) {
                    229: 		print $client ("reset_retries\n");
                    230: 		my $answer=<$client>;
                    231: 		#reset just this one.
                    232: 	    }
                    233: 	}
                    234: 	return;
                    235:     }
                    236: 
1.836     www       237:     &logthis("Trying to reconnect lonc");
1.1       albertel  238:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  239:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  240: 	my $loncpid=<$fh>;
                    241:         chomp($loncpid);
                    242:         if (kill 0 => $loncpid) {
                    243: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    244:             kill USR1 => $loncpid;
                    245:             sleep 1;
1.836     www       246:          } else {
1.12      www       247: 	    &logthis(
1.672     albertel  248:                "<font color=\"blue\">WARNING:".
1.12      www       249:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  250:         }
                    251:     } else {
1.836     www       252: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  253:     }
                    254: }
                    255: 
                    256: # ------------------------------------------------------ Critical communication
1.12      www       257: 
1.1       albertel  258: sub critical {
                    259:     my ($cmd,$server)=@_;
1.838     albertel  260:     unless (&hostname($server)) {
1.672     albertel  261:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       262:                " Critical message to unknown server ($server)</font>");
                    263:         return 'no_such_host';
                    264:     }
1.1       albertel  265:     my $answer=reply($cmd,$server);
                    266:     if ($answer eq 'con_lost') {
                    267: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  268: 	my $answer=reply($cmd,$server);
1.1       albertel  269:         if ($answer eq 'con_lost') {
                    270:             my $now=time;
                    271:             my $middlename=$cmd;
1.5       www       272:             $middlename=substr($middlename,0,16);
1.1       albertel  273:             $middlename=~s/\W//g;
                    274:             my $dfilename=
1.305     www       275:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    276:             $dumpcount++;
1.1       albertel  277:             {
1.448     albertel  278: 		my $dfh;
                    279: 		if (open($dfh,">$dfilename")) {
                    280: 		    print $dfh "$cmd\n"; 
                    281: 		    close($dfh);
                    282: 		}
1.1       albertel  283:             }
                    284:             sleep 2;
                    285:             my $wcmd='';
                    286:             {
1.448     albertel  287: 		my $dfh;
                    288: 		if (open($dfh,"<$dfilename")) {
                    289: 		    $wcmd=<$dfh>; 
                    290: 		    close($dfh);
                    291: 		}
1.1       albertel  292:             }
                    293:             chomp($wcmd);
1.7       www       294:             if ($wcmd eq $cmd) {
1.672     albertel  295: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       296:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  297:                 &logperm("D:$server:$cmd");
                    298: 	        return 'con_delayed';
                    299:             } else {
1.672     albertel  300:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       301:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  302:                 &logperm("F:$server:$cmd");
                    303:                 return 'con_failed';
                    304:             }
                    305:         }
                    306:     }
                    307:     return $answer;
1.405     albertel  308: }
                    309: 
1.755     albertel  310: # ------------------------------------------- check if return value is an error
                    311: 
                    312: sub error {
                    313:     my ($result) = @_;
1.756     albertel  314:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  315: 	if ($2 == 2) { return undef; }
                    316: 	return $1;
                    317:     }
                    318:     return undef;
                    319: }
                    320: 
1.783     albertel  321: sub convert_and_load_session_env {
                    322:     my ($lonidsdir,$handle)=@_;
                    323:     my @profile;
                    324:     {
1.917     albertel  325: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    326: 	if (!$opened) {
1.915     albertel  327: 	    return 0;
                    328: 	}
1.783     albertel  329: 	flock($idf,LOCK_SH);
                    330: 	@profile=<$idf>;
                    331: 	close($idf);
                    332:     }
                    333:     my %temp_env;
                    334:     foreach my $line (@profile) {
1.786     albertel  335: 	if ($line !~ m/=/) {
                    336: 	    return 0;
                    337: 	}
1.783     albertel  338: 	chomp($line);
                    339: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    340: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    341:     }
                    342:     unlink("$lonidsdir/$handle.id");
                    343:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    344: 	    0640)) {
                    345: 	%disk_env = %temp_env;
                    346: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    347: 	untie(%disk_env);
                    348:     }
1.786     albertel  349:     return 1;
1.783     albertel  350: }
                    351: 
1.374     www       352: # ------------------------------------------- Transfer profile into environment
1.780     albertel  353: my $env_loaded;
                    354: sub transfer_profile_to_env {
1.788     albertel  355:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    356:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       357: 
1.720     albertel  358:     if (!defined($lonidsdir)) {
                    359: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    360:     }
                    361:     if (!defined($handle)) {
                    362:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    363:     }
                    364: 
1.786     albertel  365:     my $convert;
                    366:     {
1.917     albertel  367:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    368: 	if (!$opened) {
1.915     albertel  369: 	    return;
                    370: 	}
1.786     albertel  371: 	flock($idf,LOCK_SH);
                    372: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    373: 		&GDBM_READER(),0640)) {
                    374: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    375: 	    untie(%disk_env);
                    376: 	} else {
                    377: 	    $convert = 1;
                    378: 	}
                    379:     }
                    380:     if ($convert) {
                    381: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    382: 	    &logthis("Failed to load session, or convert session.");
                    383: 	}
1.374     www       384:     }
1.783     albertel  385: 
1.786     albertel  386:     my %remove;
1.783     albertel  387:     while ( my $envname = each(%env) ) {
1.433     matthew   388:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    389:             if ($time < time-300) {
1.783     albertel  390:                 $remove{$key}++;
1.433     matthew   391:             }
                    392:         }
                    393:     }
1.783     albertel  394: 
1.619     albertel  395:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  396:     $env_loaded=1;
1.783     albertel  397:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   398:         &delenv($expired_key);
1.374     www       399:     }
1.1       albertel  400: }
                    401: 
1.916     albertel  402: # ---------------------------------------------------- Check for valid session 
                    403: sub check_for_valid_session {
                    404:     my ($r) = @_;
                    405:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    406:     my $lonid=$cookies{'lonID'};
                    407:     return undef if (!$lonid);
                    408: 
                    409:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    410:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    411:     return undef if (!-e "$lonidsdir/$handle.id");
                    412: 
1.917     albertel  413:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    414:     return undef if (!$opened);
1.916     albertel  415: 
                    416:     flock($idf,LOCK_SH);
                    417:     my %disk_env;
                    418:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    419: 	    &GDBM_READER(),0640)) {
                    420: 	return undef;	
                    421:     }
                    422: 
                    423:     if (!defined($disk_env{'user.name'})
                    424: 	|| !defined($disk_env{'user.domain'})) {
                    425: 	return undef;
                    426:     }
                    427:     return $handle;
                    428: }
                    429: 
1.830     albertel  430: sub timed_flock {
                    431:     my ($file,$lock_type) = @_;
                    432:     my $failed=0;
                    433:     eval {
                    434: 	local $SIG{__DIE__}='DEFAULT';
                    435: 	local $SIG{ALRM}=sub {
                    436: 	    $failed=1;
                    437: 	    die("failed lock");
                    438: 	};
                    439: 	alarm(13);
                    440: 	flock($file,$lock_type);
                    441: 	alarm(0);
                    442:     };
                    443:     if ($failed) {
                    444: 	return undef;
                    445:     } else {
                    446: 	return 1;
                    447:     }
                    448: }
                    449: 
1.5       www       450: # ---------------------------------------------------------- Append Environment
                    451: 
                    452: sub appenv {
1.949     raeburn   453:     my ($newenv,$roles) = @_;
                    454:     if (ref($newenv) eq 'HASH') {
                    455:         foreach my $key (keys(%{$newenv})) {
                    456:             my $refused = 0;
                    457: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    458:                 $refused = 1;
                    459:                 if (ref($roles) eq 'ARRAY') {
                    460:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    461:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    462:                         $refused = 0;
                    463:                     }
                    464:                 }
                    465:             }
                    466:             if ($refused) {
                    467:                 &logthis("<font color=\"blue\">WARNING: ".
                    468:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    469:                          .'</font>');
                    470: 	        delete($newenv->{$key});
                    471:             } else {
                    472:                 $env{$key}=$newenv->{$key};
                    473:             }
                    474:         }
                    475:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    476:         if ($opened
                    477: 	    && &timed_flock($env_file,LOCK_EX)
                    478: 	    &&
                    479: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    480: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    481: 	    while (my ($key,$value) = each(%{$newenv})) {
                    482: 	        $disk_env{$key} = $value;
                    483: 	    }
                    484: 	    untie(%disk_env);
1.35      www       485:         }
1.191     harris41  486:     }
1.56      www       487:     return 'ok';
                    488: }
                    489: # ----------------------------------------------------- Delete from Environment
                    490: 
                    491: sub delenv {
                    492:     my $delthis=shift;
                    493:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  494:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       495:                 "Attempt to delete from environment ".$delthis);
                    496:         return 'error';
                    497:     }
1.917     albertel  498:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    499:     if ($opened
1.915     albertel  500: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  501: 	&&
                    502: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    503: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  504: 	foreach my $key (keys(%disk_env)) {
                    505: 	    if ($key=~/^$delthis/) { 
1.915     albertel  506: 		delete($env{$key});
                    507: 		delete($disk_env{$key});
                    508: 	    }
1.448     albertel  509: 	}
1.783     albertel  510: 	untie(%disk_env);
1.5       www       511:     }
                    512:     return 'ok';
1.369     albertel  513: }
                    514: 
1.790     albertel  515: sub get_env_multiple {
                    516:     my ($name) = @_;
                    517:     my @values;
                    518:     if (defined($env{$name})) {
                    519:         # exists is it an array
                    520:         if (ref($env{$name})) {
                    521:             @values=@{ $env{$name} };
                    522:         } else {
                    523:             $values[0]=$env{$name};
                    524:         }
                    525:     }
                    526:     return(@values);
                    527: }
                    528: 
1.958     www       529: # ------------------------------------------------------------------- Locking
                    530: 
                    531: sub set_lock {
                    532:     my ($text)=@_;
                    533:     $locknum++;
                    534:     my $id=$$.'-'.$locknum;
                    535:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    536:              'session.lock.'.$id => $text});
                    537:     return $id;
                    538: }
                    539: 
                    540: sub get_locks {
                    541:     my $num=0;
                    542:     my %texts=();
                    543:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    544:        if ($lock=~/\w/) {
                    545:           $num++;
                    546:           $texts{$lock}=$env{'session.lock.'.$lock};
                    547:        }
                    548:    }
                    549:    return ($num,%texts);
                    550: }
                    551: 
                    552: sub remove_lock {
                    553:     my ($id)=@_;
                    554:     my $newlocks='';
                    555:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    556:        if (($lock=~/\w/) && ($lock ne $id)) {
                    557:           $newlocks.=','.$lock;
                    558:        }
                    559:     }
                    560:     &appenv({'session.locks' => $newlocks});
                    561:     &delenv('session.lock.'.$id);
                    562: }
                    563: 
                    564: sub remove_all_locks {
                    565:     my $activelocks=$env{'session.locks'};
                    566:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    567:        if ($lock=~/\w/) {
                    568:           &remove_lock($lock);
                    569:        }
                    570:     }
                    571: }
                    572: 
                    573: 
1.369     albertel  574: # ------------------------------------------ Find out current server userload
                    575: sub userload {
                    576:     my $numusers=0;
                    577:     {
                    578: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    579: 	my $filename;
                    580: 	my $curtime=time;
                    581: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  582: 	    next if ($filename eq '.' || $filename eq '..');
                    583: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  584: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  585: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  586: 	}
                    587: 	closedir(LONIDS);
                    588:     }
                    589:     my $userloadpercent=0;
                    590:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    591:     if ($maxuserload) {
1.371     albertel  592: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  593:     }
1.372     albertel  594:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  595:     return $userloadpercent;
1.283     www       596: }
                    597: 
                    598: # ------------------------------------------ Fight off request when overloaded
                    599: 
                    600: sub overloaderror {
                    601:     my ($r,$checkserver)=@_;
                    602:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    603:     my $loadavg;
                    604:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  605:        open(my $loadfile,'/proc/loadavg');
1.283     www       606:        $loadavg=<$loadfile>;
                    607:        $loadavg =~ s/\s.*//g;
1.285     matthew   608:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  609:        close($loadfile);
1.283     www       610:     } else {
                    611:        $loadavg=&reply('load',$checkserver);
                    612:     }
1.285     matthew   613:     my $overload=$loadavg-100;
1.283     www       614:     if ($overload>0) {
1.285     matthew   615: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       616:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       617:         return 413;
1.283     www       618:     }    
                    619:     return '';
1.5       www       620: }
1.1       albertel  621: 
                    622: # ------------------------------ Find server with least workload from spare.tab
1.11      www       623: 
1.1       albertel  624: sub spareserver {
1.670     albertel  625:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  626:     my $spare_server;
1.370     albertel  627:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  628:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    629:                                                      :  $userloadpercent;
                    630:     
                    631:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    632: 	($spare_server, $lowest_load) =
                    633: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    634:     }
                    635: 
                    636:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    637: 
                    638:     if (!$found_server) {
                    639: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    640: 	    ($spare_server, $lowest_load) =
                    641: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    642: 	}
                    643:     }
                    644: 
                    645:     if (!$want_server_name) {
1.838     albertel  646: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  647:     }
                    648:     return $spare_server;
                    649: }
                    650: 
                    651: sub compare_server_load {
                    652:     my ($try_server, $spare_server, $lowest_load) = @_;
                    653: 
                    654:     my $loadans     = &reply('load',    $try_server);
                    655:     my $userloadans = &reply('userload',$try_server);
                    656: 
                    657:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    658: 	next; #didn't get a number from the server
                    659:     }
                    660: 
                    661:     my $load;
                    662:     if ($loadans =~ /\d/) {
                    663: 	if ($userloadans =~ /\d/) {
                    664: 	    #both are numbers, pick the bigger one
                    665: 	    $load = ($loadans > $userloadans) ? $loadans 
                    666: 		                              : $userloadans;
1.411     albertel  667: 	} else {
1.784     albertel  668: 	    $load = $loadans;
1.411     albertel  669: 	}
1.784     albertel  670:     } else {
                    671: 	$load = $userloadans;
                    672:     }
                    673: 
                    674:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    675: 	$spare_server = $try_server;
                    676: 	$lowest_load  = $load;
1.370     albertel  677:     }
1.784     albertel  678:     return ($spare_server,$lowest_load);
1.202     matthew   679: }
1.914     albertel  680: 
                    681: # --------------------------- ask offload servers if user already has a session
                    682: sub find_existing_session {
                    683:     my ($udom,$uname) = @_;
                    684:     foreach my $try_server (@{ $spareid{'primary'} },
                    685: 			    @{ $spareid{'default'} }) {
                    686: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    687:     }
                    688:     return;
                    689: }
                    690: 
                    691: # -------------------------------- ask if server already has a session for user
                    692: sub has_user_session {
                    693:     my ($lonid,$udom,$uname) = @_;
                    694:     my $result = &reply(join(':','userhassession',
                    695: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    696:     return 1 if ($result eq 'ok');
                    697: 
                    698:     return 0;
                    699: }
                    700: 
1.202     matthew   701: # --------------------------------------------- Try to change a user's password
                    702: 
                    703: sub changepass {
1.799     raeburn   704:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   705:     $currentpass = &escape($currentpass);
                    706:     $newpass     = &escape($newpass);
1.799     raeburn   707:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   708: 		       $server);
                    709:     if (! $answer) {
                    710: 	&logthis("No reply on password change request to $server ".
                    711: 		 "by $uname in domain $udom.");
                    712:     } elsif ($answer =~ "^ok") {
                    713:         &logthis("$uname in $udom successfully changed their password ".
                    714: 		 "on $server.");
                    715:     } elsif ($answer =~ "^pwchange_failure") {
                    716: 	&logthis("$uname in $udom was unable to change their password ".
                    717: 		 "on $server.  The action was blocked by either lcpasswd ".
                    718: 		 "or pwchange");
                    719:     } elsif ($answer =~ "^non_authorized") {
                    720:         &logthis("$uname in $udom did not get their password correct when ".
                    721: 		 "attempting to change it on $server.");
                    722:     } elsif ($answer =~ "^auth_mode_error") {
                    723:         &logthis("$uname in $udom attempted to change their password despite ".
                    724: 		 "not being locally or internally authenticated on $server.");
                    725:     } elsif ($answer =~ "^unknown_user") {
                    726:         &logthis("$uname in $udom attempted to change their password ".
                    727: 		 "on $server but were unable to because $server is not ".
                    728: 		 "their home server.");
                    729:     } elsif ($answer =~ "^refused") {
                    730: 	&logthis("$server refused to change $uname in $udom password because ".
                    731: 		 "it was sent an unencrypted request to change the password.");
                    732:     }
                    733:     return $answer;
1.1       albertel  734: }
                    735: 
1.169     harris41  736: # ----------------------- Try to determine user's current authentication scheme
                    737: 
                    738: sub queryauthenticate {
                    739:     my ($uname,$udom)=@_;
1.456     albertel  740:     my $uhome=&homeserver($uname,$udom);
                    741:     if (!$uhome) {
                    742: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    743: 	return 'no_host';
                    744:     }
                    745:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    746:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    747: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  748:     }
1.456     albertel  749:     return $answer;
1.169     harris41  750: }
                    751: 
1.1       albertel  752: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       753: 
1.1       albertel  754: sub authenticate {
1.952     raeburn   755:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  756:     $upass=&escape($upass);
                    757:     $uname= &LONCAPA::clean_username($uname);
1.836     www       758:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   759:     my $newhome;
1.836     www       760:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    761: # Maybe the machine was offline and only re-appeared again recently?
                    762:         &reconlonc();
                    763: # One more
1.952     raeburn   764: 	$uhome=&homeserver($uname,$udom,1);
                    765:         if (($uhome eq 'no_host') && $checkdefauth) {
                    766:             if (defined(&domain($udom,'primary'))) {
                    767:                 $newhome=&domain($udom,'primary');
                    768:             }
                    769:             if ($newhome ne '') {
                    770:                 $uhome = $newhome;
                    771:             }
                    772:         }
1.836     www       773: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    774: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   775: 	    return 'no_host';
                    776:         }
1.1       albertel  777:     }
1.952     raeburn   778:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  779:     if ($answer eq 'authorized') {
1.952     raeburn   780:         if ($newhome) {
                    781:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    782:             return 'no_account_on_host'; 
                    783:         } else {
                    784:             &logthis("User $uname at $udom authorized by $uhome");
                    785:             return $uhome;
                    786:         }
1.471     albertel  787:     }
                    788:     if ($answer eq 'non_authorized') {
                    789: 	&logthis("User $uname at $udom rejected by $uhome");
                    790: 	return 'no_host'; 
1.9       www       791:     }
1.471     albertel  792:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  793:     return 'no_host';
                    794: }
                    795: 
                    796: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       797: 
1.599     albertel  798: my %homecache;
1.1       albertel  799: sub homeserver {
1.230     stredwic  800:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  801:     my $index="$uname:$udom";
1.426     albertel  802: 
1.599     albertel  803:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  804: 
                    805:     my %servers = &get_servers($udom,'library');
                    806:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  807:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  808: 		 exists($badServerCache{$tryserver}));
1.841     albertel  809: 
                    810: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    811: 	if ($answer eq 'found') {
                    812: 	    delete($badServerCache{$tryserver}); 
                    813: 	    return $homecache{$index}=$tryserver;
                    814: 	} elsif ($answer eq 'no_host') {
                    815: 	    $badServerCache{$tryserver}=1;
                    816: 	}
1.1       albertel  817:     }    
                    818:     return 'no_host';
1.70      www       819: }
                    820: 
                    821: # ------------------------------------- Find the usernames behind a list of IDs
                    822: 
                    823: sub idget {
                    824:     my ($udom,@ids)=@_;
                    825:     my %returnhash=();
                    826:     
1.841     albertel  827:     my %servers = &get_servers($udom,'library');
                    828:     foreach my $tryserver (keys(%servers)) {
                    829: 	my $idlist=join('&',@ids);
                    830: 	$idlist=~tr/A-Z/a-z/; 
                    831: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    832: 	my @answer=();
                    833: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    834: 	    @answer=split(/\&/,$reply);
                    835: 	}                    ;
                    836: 	my $i;
                    837: 	for ($i=0;$i<=$#ids;$i++) {
                    838: 	    if ($answer[$i]) {
                    839: 		$returnhash{$ids[$i]}=$answer[$i];
                    840: 	    } 
                    841: 	}
                    842:     } 
1.70      www       843:     return %returnhash;
                    844: }
                    845: 
                    846: # ------------------------------------- Find the IDs behind a list of usernames
                    847: 
                    848: sub idrget {
                    849:     my ($udom,@unames)=@_;
                    850:     my %returnhash=();
1.800     albertel  851:     foreach my $uname (@unames) {
                    852:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  853:     }
1.70      www       854:     return %returnhash;
                    855: }
                    856: 
                    857: # ------------------------------- Store away a list of names and associated IDs
                    858: 
                    859: sub idput {
                    860:     my ($udom,%ids)=@_;
                    861:     my %servers=();
1.800     albertel  862:     foreach my $uname (keys(%ids)) {
                    863: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    864:         my $uhom=&homeserver($uname,$udom);
1.70      www       865:         if ($uhom ne 'no_host') {
1.800     albertel  866:             my $id=&escape($ids{$uname});
1.70      www       867:             $id=~tr/A-Z/a-z/;
1.800     albertel  868:             my $esc_unam=&escape($uname);
1.70      www       869: 	    if ($servers{$uhom}) {
1.800     albertel  870: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       871:             } else {
1.800     albertel  872:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       873:             }
                    874:         }
1.191     harris41  875:     }
1.800     albertel  876:     foreach my $server (keys(%servers)) {
                    877:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  878:     }
1.344     www       879: }
                    880: 
1.806     raeburn   881: # ------------------------------------------- get items from domain db files   
                    882: 
                    883: sub get_dom {
1.860     raeburn   884:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   885:     my $items='';
                    886:     foreach my $item (@$storearr) {
                    887:         $items.=&escape($item).'&';
                    888:     }
                    889:     $items=~s/\&$//;
1.860     raeburn   890:     if (!$udom) {
                    891:         $udom=$env{'user.domain'};
                    892:         if (defined(&domain($udom,'primary'))) {
                    893:             $uhome=&domain($udom,'primary');
                    894:         } else {
1.874     albertel  895:             undef($uhome);
1.860     raeburn   896:         }
                    897:     } else {
                    898:         if (!$uhome) {
                    899:             if (defined(&domain($udom,'primary'))) {
                    900:                 $uhome=&domain($udom,'primary');
                    901:             }
                    902:         }
                    903:     }
                    904:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   905:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   906:         my %returnhash;
1.875     albertel  907:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   908:             return %returnhash;
                    909:         }
1.806     raeburn   910:         my @pairs=split(/\&/,$rep);
                    911:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    912:             return @pairs;
                    913:         }
                    914:         my $i=0;
                    915:         foreach my $item (@$storearr) {
                    916:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    917:             $i++;
                    918:         }
                    919:         return %returnhash;
                    920:     } else {
1.880     banghart  921:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   922:     }
                    923: }
                    924: 
                    925: # -------------------------------------------- put items in domain db files 
                    926: 
                    927: sub put_dom {
1.860     raeburn   928:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    929:     if (!$udom) {
                    930:         $udom=$env{'user.domain'};
                    931:         if (defined(&domain($udom,'primary'))) {
                    932:             $uhome=&domain($udom,'primary');
                    933:         } else {
1.874     albertel  934:             undef($uhome);
1.860     raeburn   935:         }
                    936:     } else {
                    937:         if (!$uhome) {
                    938:             if (defined(&domain($udom,'primary'))) {
                    939:                 $uhome=&domain($udom,'primary');
                    940:             }
                    941:         }
                    942:     } 
                    943:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   944:         my $items='';
                    945:         foreach my $item (keys(%$storehash)) {
                    946:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    947:         }
                    948:         $items=~s/\&$//;
                    949:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    950:     } else {
1.860     raeburn   951:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   952:     }
                    953: }
                    954: 
1.837     raeburn   955: sub retrieve_inst_usertypes {
                    956:     my ($udom) = @_;
                    957:     my (%returnhash,@order);
1.846     albertel  958:     if (defined(&domain($udom,'primary'))) {
                    959:         my $uhome=&domain($udom,'primary');
1.837     raeburn   960:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960   ! raeburn   961:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
        !           962:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
        !           963:             return (\%returnhash,\@order);
        !           964:         }
1.837     raeburn   965:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    966:         my @pairs=split(/\&/,$hashitems);
                    967:         foreach my $item (@pairs) {
                    968:             my ($key,$value)=split(/=/,$item,2);
                    969:             $key = &unescape($key);
                    970:             next if ($key =~ /^error: 2 /);
                    971:             $returnhash{$key}=&thaw_unescape($value);
                    972:         }
                    973:         my @esc_order = split(/\&/,$orderitems);
                    974:         foreach my $item (@esc_order) {
                    975:             push(@order,&unescape($item));
                    976:         }
                    977:     } else {
                    978:         &logthis("get_dom failed - no primary domain server for $udom");
                    979:     }
                    980:     return (\%returnhash,\@order);
                    981: }
                    982: 
1.868     raeburn   983: sub is_domainimage {
                    984:     my ($url) = @_;
                    985:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    986:         if (&domain($1) ne '') {
                    987:             return '1';
                    988:         }
                    989:     }
                    990:     return;
                    991: }
                    992: 
1.899     raeburn   993: sub inst_directory_query {
                    994:     my ($srch) = @_;
                    995:     my $udom = $srch->{'srchdomain'};
                    996:     my %results;
                    997:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   998:     my $outcome;
1.899     raeburn   999:     if ($homeserver ne '') {
1.904     albertel 1000: 	my $queryid=&reply("querysend:instdirsearch:".
                   1001: 			   &escape($srch->{'srchby'}).':'.
                   1002: 			   &escape($srch->{'srchterm'}).':'.
                   1003: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1004: 	my $host=&hostname($homeserver);
                   1005: 	if ($queryid !~/^\Q$host\E\_/) {
                   1006: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1007: 	    return;
                   1008: 	}
                   1009: 	my $response = &get_query_reply($queryid);
                   1010: 	my $maxtries = 5;
                   1011: 	my $tries = 1;
                   1012: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1013: 	    $response = &get_query_reply($queryid);
                   1014: 	    $tries ++;
                   1015: 	}
                   1016: 
                   1017:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1018:             if ($response eq 'unavailable') {
                   1019:                 $outcome = $response;
                   1020:             } else {
                   1021:                 $outcome = 'ok';
                   1022:                 my @matches = split(/\n/,$response);
                   1023:                 foreach my $match (@matches) {
                   1024:                     my ($key,$value) = split(/=/,$match);
                   1025:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1026:                 }
1.899     raeburn  1027:             }
                   1028:         }
                   1029:     }
1.909     raeburn  1030:     return ($outcome,%results);
1.899     raeburn  1031: }
                   1032: 
                   1033: sub usersearch {
                   1034:     my ($srch) = @_;
                   1035:     my $dom = $srch->{'srchdomain'};
                   1036:     my %results;
                   1037:     my %libserv = &all_library();
                   1038:     my $query = 'usersearch';
                   1039:     foreach my $tryserver (keys(%libserv)) {
                   1040:         if (&host_domain($tryserver) eq $dom) {
                   1041:             my $host=&hostname($tryserver);
                   1042:             my $queryid=
1.911     raeburn  1043:                 &reply("querysend:".&escape($query).':'.
                   1044:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1045:                        &escape($srch->{'srchtype'}).':'.
                   1046:                        &escape($srch->{'srchterm'}),$tryserver);
                   1047:             if ($queryid !~/^\Q$host\E\_/) {
                   1048:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1049:                 next;
1.899     raeburn  1050:             }
                   1051:             my $reply = &get_query_reply($queryid);
                   1052:             my $maxtries = 1;
                   1053:             my $tries = 1;
                   1054:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1055:                 $reply = &get_query_reply($queryid);
                   1056:                 $tries ++;
                   1057:             }
                   1058:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1059:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1060:             } else {
1.911     raeburn  1061:                 my @matches;
                   1062:                 if ($reply =~ /\n/) {
                   1063:                     @matches = split(/\n/,$reply);
                   1064:                 } else {
                   1065:                     @matches = split(/\&/,$reply);
                   1066:                 }
1.899     raeburn  1067:                 foreach my $match (@matches) {
                   1068:                     my ($uname,$udom,%userhash);
1.911     raeburn  1069:                     foreach my $entry (split(/:/,$match)) {
                   1070:                         my ($key,$value) =
                   1071:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1072:                         $userhash{$key} = $value;
                   1073:                         if ($key eq 'username') {
                   1074:                             $uname = $value;
                   1075:                         } elsif ($key eq 'domain') {
                   1076:                             $udom = $value;
1.911     raeburn  1077:                         }
1.899     raeburn  1078:                     }
                   1079:                     $results{$uname.':'.$udom} = \%userhash;
                   1080:                 }
                   1081:             }
                   1082:         }
                   1083:     }
                   1084:     return %results;
                   1085: }
                   1086: 
1.912     raeburn  1087: sub get_instuser {
                   1088:     my ($udom,$uname,$id) = @_;
                   1089:     my $homeserver = &domain($udom,'primary');
                   1090:     my ($outcome,%results);
                   1091:     if ($homeserver ne '') {
                   1092:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1093:                            &escape($id).':'.&escape($udom),$homeserver);
                   1094:         my $host=&hostname($homeserver);
                   1095:         if ($queryid !~/^\Q$host\E\_/) {
                   1096:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1097:             return;
                   1098:         }
                   1099:         my $response = &get_query_reply($queryid);
                   1100:         my $maxtries = 5;
                   1101:         my $tries = 1;
                   1102:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1103:             $response = &get_query_reply($queryid);
                   1104:             $tries ++;
                   1105:         }
                   1106:         if (!&error($response) && $response ne 'refused') {
                   1107:             if ($response eq 'unavailable') {
                   1108:                 $outcome = $response;
                   1109:             } else {
                   1110:                 $outcome = 'ok';
                   1111:                 my @matches = split(/\n/,$response);
                   1112:                 foreach my $match (@matches) {
                   1113:                     my ($key,$value) = split(/=/,$match);
                   1114:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1115:                 }
                   1116:             }
                   1117:         }
                   1118:     }
                   1119:     my %userinfo;
                   1120:     if (ref($results{$uname}) eq 'HASH') {
                   1121:         %userinfo = %{$results{$uname}};
                   1122:     } 
                   1123:     return ($outcome,%userinfo);
                   1124: }
                   1125: 
                   1126: sub inst_rulecheck {
1.923     raeburn  1127:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1128:     my %returnhash;
                   1129:     if ($udom ne '') {
                   1130:         if (ref($rules) eq 'ARRAY') {
                   1131:             @{$rules} = map {&escape($_);} (@{$rules});
                   1132:             my $rulestr = join(':',@{$rules});
                   1133:             my $homeserver=&domain($udom,'primary');
                   1134:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1135:                 my $response;
                   1136:                 if ($item eq 'username') {                
                   1137:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1138:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1139:                                               $homeserver));
1.923     raeburn  1140:                 } elsif ($item eq 'id') {
                   1141:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1142:                                               ':'.&escape($id).':'.$rulestr,
                   1143:                                               $homeserver));
1.945     raeburn  1144:                 } elsif ($item eq 'selfcreate') {
                   1145:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1146:                                                &escape($udom).':'.&escape($uname).
                   1147:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1148:                 }
1.912     raeburn  1149:                 if ($response ne 'refused') {
                   1150:                     my @pairs=split(/\&/,$response);
                   1151:                     foreach my $item (@pairs) {
                   1152:                         my ($key,$value)=split(/=/,$item,2);
                   1153:                         $key = &unescape($key);
                   1154:                         next if ($key =~ /^error: 2 /);
                   1155:                         $returnhash{$key}=&thaw_unescape($value);
                   1156:                     }
                   1157:                 }
                   1158:             }
                   1159:         }
                   1160:     }
                   1161:     return %returnhash;
                   1162: }
                   1163: 
                   1164: sub inst_userrules {
1.923     raeburn  1165:     my ($udom,$check) = @_;
1.912     raeburn  1166:     my (%ruleshash,@ruleorder);
                   1167:     if ($udom ne '') {
                   1168:         my $homeserver=&domain($udom,'primary');
                   1169:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1170:             my $response;
                   1171:             if ($check eq 'id') {
                   1172:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1173:                                  $homeserver);
1.943     raeburn  1174:             } elsif ($check eq 'email') {
                   1175:                 $response=&reply('instemailrules:'.&escape($udom),
                   1176:                                  $homeserver);
1.923     raeburn  1177:             } else {
                   1178:                 $response=&reply('instuserrules:'.&escape($udom),
                   1179:                                  $homeserver);
                   1180:             }
1.912     raeburn  1181:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1182:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1183:                 ($response ne 'no_such_host')) {
                   1184:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1185:                 my @pairs=split(/\&/,$hashitems);
                   1186:                 foreach my $item (@pairs) {
                   1187:                     my ($key,$value)=split(/=/,$item,2);
                   1188:                     $key = &unescape($key);
                   1189:                     next if ($key =~ /^error: 2 /);
                   1190:                     $ruleshash{$key}=&thaw_unescape($value);
                   1191:                 }
                   1192:                 my @esc_order = split(/\&/,$orderitems);
                   1193:                 foreach my $item (@esc_order) {
                   1194:                     push(@ruleorder,&unescape($item));
                   1195:                 }
                   1196:             }
                   1197:         }
                   1198:     }
                   1199:     return (\%ruleshash,\@ruleorder);
                   1200: }
                   1201: 
1.943     raeburn  1202: # ------------------------- Get Authentication and Language Defaults for Domain
                   1203: 
                   1204: sub get_domain_defaults {
                   1205:     my ($domain) = @_;
                   1206:     my $cachetime = 60*60*24;
                   1207:     my ($defauthtype,$defautharg,$deflang);
                   1208:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1209:     if (defined($cached)) {
                   1210:         if (ref($result) eq 'HASH') {
                   1211:             return %{$result};
                   1212:         }
                   1213:     }
                   1214:     my %domdefaults;
                   1215:     my %domconfig =
                   1216:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1217:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1218:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1219:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1220:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1221:     } else {
                   1222:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1223:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1224:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1225:     }
                   1226:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1227:                                   $cachetime);
                   1228:     return %domdefaults;
                   1229: }
                   1230: 
1.344     www      1231: # --------------------------------------------------- Assign a key to a student
                   1232: 
                   1233: sub assign_access_key {
1.364     www      1234: #
                   1235: # a valid key looks like uname:udom#comments
                   1236: # comments are being appended
                   1237: #
1.498     www      1238:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1239:     $kdom=
1.620     albertel 1240:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1241:     $knum=
1.620     albertel 1242:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1243:     $cdom=
1.620     albertel 1244:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1245:     $cnum=
1.620     albertel 1246:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1247:     $udom=$env{'user.name'} unless (defined($udom));
                   1248:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1249:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1250:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1251:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1252:                                                   # assigned to this person
                   1253:                                                   # - this should not happen,
1.345     www      1254:                                                   # unless something went wrong
                   1255:                                                   # the first time around
                   1256: # ready to assign
1.364     www      1257:         $logentry=$1.'; '.$logentry;
1.496     www      1258:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1259:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1260: # key now belongs to user
1.346     www      1261: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1262:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1263:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1264:                 return 'ok';
                   1265:             } else {
                   1266:                 return 
                   1267:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1268: 	    }
                   1269:         } else {
                   1270:             return 'error: Could not assign key, try again later.';
                   1271:         }
1.364     www      1272:     } elsif (!$existing{$ckey}) {
1.345     www      1273: # the key does not exist
                   1274: 	return 'error: The key does not exist';
                   1275:     } else {
                   1276: # the key is somebody else's
                   1277: 	return 'error: The key is already in use';
                   1278:     }
1.344     www      1279: }
                   1280: 
1.364     www      1281: # ------------------------------------------ put an additional comment on a key
                   1282: 
                   1283: sub comment_access_key {
                   1284: #
                   1285: # a valid key looks like uname:udom#comments
                   1286: # comments are being appended
                   1287: #
                   1288:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1289:     $cdom=
1.620     albertel 1290:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1291:     $cnum=
1.620     albertel 1292:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1293:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1294:     if ($existing{$ckey}) {
                   1295:         $existing{$ckey}.='; '.$logentry;
                   1296: # ready to assign
1.367     www      1297:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1298:                                                  $cdom,$cnum) eq 'ok') {
                   1299: 	    return 'ok';
                   1300:         } else {
                   1301: 	    return 'error: Count not store comment.';
                   1302:         }
                   1303:     } else {
                   1304: # the key does not exist
                   1305: 	return 'error: The key does not exist';
                   1306:     }
                   1307: }
                   1308: 
1.344     www      1309: # ------------------------------------------------------ Generate a set of keys
                   1310: 
                   1311: sub generate_access_keys {
1.364     www      1312:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1313:     $cdom=
1.620     albertel 1314:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1315:     $cnum=
1.620     albertel 1316:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1317:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1318:     unless (($cdom) && ($cnum)) { return 0; }
                   1319:     if ($number>10000) { return 0; }
                   1320:     sleep(2); # make sure don't get same seed twice
                   1321:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1322:     my $total=0;
                   1323:     for (my $i=1;$i<=$number;$i++) {
                   1324:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1325:                   sprintf("%lx",int(100000*rand)).'-'.
                   1326:                   sprintf("%lx",int(100000*rand));
                   1327:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1328:        $newkey=~s/0/h/g; # and also 0 and O
                   1329:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1330:        if ($existing{$newkey}) {
                   1331:            $i--;
                   1332:        } else {
1.364     www      1333: 	  if (&put('accesskeys',
                   1334:               { $newkey => '# generated '.localtime().
1.620     albertel 1335:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1336:                            '; '.$logentry },
                   1337: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1338:               $total++;
                   1339: 	  }
                   1340:        }
                   1341:     }
1.620     albertel 1342:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1343:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1344:     return $total;
                   1345: }
                   1346: 
                   1347: # ------------------------------------------------------- Validate an accesskey
                   1348: 
                   1349: sub validate_access_key {
                   1350:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1351:     $cdom=
1.620     albertel 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1353:     $cnum=
1.620     albertel 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1355:     $udom=$env{'user.domain'} unless (defined($udom));
                   1356:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1357:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1358:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1359: }
                   1360: 
                   1361: # ------------------------------------- Find the section of student in a course
1.652     albertel 1362: sub devalidate_getsection_cache {
                   1363:     my ($udom,$unam,$courseid)=@_;
                   1364:     my $hashid="$udom:$unam:$courseid";
                   1365:     &devalidate_cache_new('getsection',$hashid);
                   1366: }
1.298     matthew  1367: 
1.815     albertel 1368: sub courseid_to_courseurl {
                   1369:     my ($courseid) = @_;
                   1370:     #already url style courseid
                   1371:     return $courseid if ($courseid =~ m{^/});
                   1372: 
                   1373:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1374: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1375: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1376: 	return "/$cdom/$cnum";
                   1377:     }
                   1378: 
                   1379:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1380:     if (exists($courseinfo{'num'})) {
                   1381: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1382:     }
                   1383: 
                   1384:     return undef;
                   1385: }
                   1386: 
1.298     matthew  1387: sub getsection {
                   1388:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1389:     my $cachetime=1800;
1.551     albertel 1390: 
                   1391:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1392:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1393:     if (defined($cached)) { return $result; }
                   1394: 
1.298     matthew  1395:     my %Pending; 
                   1396:     my %Expired;
                   1397:     #
                   1398:     # Each role can either have not started yet (pending), be active, 
                   1399:     #    or have expired.
                   1400:     #
                   1401:     # If there is an active role, we are done.
                   1402:     #
                   1403:     # If there is more than one role which has not started yet, 
                   1404:     #     choose the one which will start sooner
                   1405:     # If there is one role which has not started yet, return it.
                   1406:     #
                   1407:     # If there is more than one expired role, choose the one which ended last.
                   1408:     # If there is a role which has expired, return it.
                   1409:     #
1.815     albertel 1410:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1411:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1412:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1413:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1414:         my $section=$1;
                   1415:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1416:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1417:         my $now=time;
1.548     albertel 1418:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1419:             $Expired{$end}=$section;
                   1420:             next;
                   1421:         }
1.548     albertel 1422:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1423:             $Pending{$start}=$section;
                   1424:             next;
                   1425:         }
1.599     albertel 1426:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1427:     }
                   1428:     #
                   1429:     # Presumedly there will be few matching roles from the above
                   1430:     # loop and the sorting time will be negligible.
                   1431:     if (scalar(keys(%Pending))) {
                   1432:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1433:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1434:     } 
                   1435:     if (scalar(keys(%Expired))) {
                   1436:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1437:         my $time = pop(@sorted);
1.599     albertel 1438:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1439:     }
1.599     albertel 1440:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1441: }
1.70      www      1442: 
1.599     albertel 1443: sub save_cache {
                   1444:     &purge_remembered();
1.722     albertel 1445:     #&Apache::loncommon::validate_page();
1.620     albertel 1446:     undef(%env);
1.780     albertel 1447:     undef($env_loaded);
1.599     albertel 1448: }
1.452     albertel 1449: 
1.599     albertel 1450: my $to_remember=-1;
                   1451: my %remembered;
                   1452: my %accessed;
                   1453: my $kicks=0;
                   1454: my $hits=0;
1.849     albertel 1455: sub make_key {
                   1456:     my ($name,$id) = @_;
1.872     albertel 1457:     if (length($id) > 65 
                   1458: 	&& length(&escape($id)) > 200) {
                   1459: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1460:     }
1.849     albertel 1461:     return &escape($name.':'.$id);
                   1462: }
                   1463: 
1.599     albertel 1464: sub devalidate_cache_new {
                   1465:     my ($name,$id,$debug) = @_;
                   1466:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1467:     $id=&make_key($name,$id);
1.599     albertel 1468:     $memcache->delete($id);
                   1469:     delete($remembered{$id});
                   1470:     delete($accessed{$id});
                   1471: }
                   1472: 
                   1473: sub is_cached_new {
                   1474:     my ($name,$id,$debug) = @_;
1.849     albertel 1475:     $id=&make_key($name,$id);
1.599     albertel 1476:     if (exists($remembered{$id})) {
                   1477: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1478: 	$accessed{$id}=[&gettimeofday()];
                   1479: 	$hits++;
                   1480: 	return ($remembered{$id},1);
                   1481:     }
                   1482:     my $value = $memcache->get($id);
                   1483:     if (!(defined($value))) {
                   1484: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1485: 	return (undef,undef);
1.416     albertel 1486:     }
1.599     albertel 1487:     if ($value eq '__undef__') {
                   1488: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1489: 	$value=undef;
                   1490:     }
                   1491:     &make_room($id,$value,$debug);
                   1492:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1493:     return ($value,1);
                   1494: }
                   1495: 
                   1496: sub do_cache_new {
                   1497:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1498:     $id=&make_key($name,$id);
1.599     albertel 1499:     my $setvalue=$value;
                   1500:     if (!defined($setvalue)) {
                   1501: 	$setvalue='__undef__';
                   1502:     }
1.623     albertel 1503:     if (!defined($time) ) {
                   1504: 	$time=600;
                   1505:     }
1.599     albertel 1506:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1507:     my $result = $memcache->set($id,$setvalue,$time);
                   1508:     if (! $result) {
1.872     albertel 1509: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1510: 	$memcache->disconnect_all();
1.872     albertel 1511:     }
1.600     albertel 1512:     # need to make a copy of $value
1.919     albertel 1513:     &make_room($id,$value,$debug);
1.599     albertel 1514:     return $value;
                   1515: }
                   1516: 
                   1517: sub make_room {
                   1518:     my ($id,$value,$debug)=@_;
1.919     albertel 1519: 
                   1520:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1521:                                     : $value;
1.599     albertel 1522:     if ($to_remember<0) { return; }
                   1523:     $accessed{$id}=[&gettimeofday()];
                   1524:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1525:     my $to_kick;
                   1526:     my $max_time=0;
                   1527:     foreach my $other (keys(%accessed)) {
                   1528: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1529: 	    $to_kick=$other;
                   1530: 	    $max_time=&tv_interval($accessed{$other});
                   1531: 	}
                   1532:     }
                   1533:     delete($remembered{$to_kick});
                   1534:     delete($accessed{$to_kick});
                   1535:     $kicks++;
                   1536:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1537:     return;
                   1538: }
                   1539: 
1.599     albertel 1540: sub purge_remembered {
1.604     albertel 1541:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1542:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1543:     undef(%remembered);
                   1544:     undef(%accessed);
1.428     albertel 1545: }
1.70      www      1546: # ------------------------------------- Read an entry from a user's environment
                   1547: 
                   1548: sub userenvironment {
                   1549:     my ($udom,$unam,@what)=@_;
                   1550:     my %returnhash=();
                   1551:     my @answer=split(/\&/,
                   1552:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1553:                       &homeserver($unam,$udom)));
                   1554:     my $i;
                   1555:     for ($i=0;$i<=$#what;$i++) {
                   1556: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1557:     }
                   1558:     return %returnhash;
1.1       albertel 1559: }
                   1560: 
1.617     albertel 1561: # ---------------------------------------------------------- Get a studentphoto
                   1562: sub studentphoto {
                   1563:     my ($udom,$unam,$ext) = @_;
                   1564:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1565:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1566:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1567:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1568:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1569:             } else {
                   1570:                 my ($result,$perm_reqd)=
1.707     albertel 1571: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1572:                 if ($result eq 'ok') {
                   1573:                     if (!($perm_reqd eq 'yes')) {
                   1574:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1575:                     }
                   1576:                 }
                   1577:             }
                   1578:         }
                   1579:     } else {
                   1580:         my ($result,$perm_reqd) = 
1.707     albertel 1581: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1582:         if ($result eq 'ok') {
                   1583:             if (!($perm_reqd eq 'yes')) {
                   1584:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1585:             }
                   1586:         }
                   1587:     }
                   1588:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1589: }
                   1590: 
                   1591: sub retrievestudentphoto {
                   1592:     my ($udom,$unam,$ext,$type) = @_;
                   1593:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1594:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1595:     if ($ret eq 'ok') {
                   1596:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1597:         if ($type eq 'thumbnail') {
                   1598:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1599:         }
                   1600:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1601:         return $tokenurl;
                   1602:     } else {
                   1603:         if ($type eq 'thumbnail') {
                   1604:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1605:         } else { 
                   1606:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1607:         }
1.617     albertel 1608:     }
                   1609: }
                   1610: 
1.263     www      1611: # -------------------------------------------------------------------- New chat
                   1612: 
                   1613: sub chatsend {
1.724     raeburn  1614:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1615:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1616:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1617:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1618:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1619: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1620: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1621: }
                   1622: 
                   1623: # ------------------------------------------ Find current version of a resource
                   1624: 
                   1625: sub getversion {
                   1626:     my $fname=&clutter(shift);
                   1627:     unless ($fname=~/^\/res\//) { return -1; }
                   1628:     return &currentversion(&filelocation('',$fname));
                   1629: }
                   1630: 
                   1631: sub currentversion {
                   1632:     my $fname=shift;
1.599     albertel 1633:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1634:     if (defined($cached)) { return $result; }
1.292     www      1635:     my $author=$fname;
                   1636:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1637:     my ($udom,$uname)=split(/\//,$author);
                   1638:     my $home=homeserver($uname,$udom);
                   1639:     if ($home eq 'no_host') { 
                   1640:         return -1; 
                   1641:     }
                   1642:     my $answer=reply("currentversion:$fname",$home);
                   1643:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1644: 	return -1;
                   1645:     }
1.599     albertel 1646:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1647: }
                   1648: 
1.1       albertel 1649: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1650: 
1.1       albertel 1651: sub subscribe {
                   1652:     my $fname=shift;
1.761     raeburn  1653:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1654:     $fname=~s/[\n\r]//g;
1.1       albertel 1655:     my $author=$fname;
                   1656:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1657:     my ($udom,$uname)=split(/\//,$author);
                   1658:     my $home=homeserver($uname,$udom);
1.335     albertel 1659:     if ($home eq 'no_host') {
                   1660:         return 'not_found';
1.1       albertel 1661:     }
                   1662:     my $answer=reply("sub:$fname",$home);
1.64      www      1663:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1664: 	$answer.=' by '.$home;
                   1665:     }
1.1       albertel 1666:     return $answer;
                   1667: }
                   1668:     
1.8       www      1669: # -------------------------------------------------------------- Replicate file
                   1670: 
                   1671: sub repcopy {
                   1672:     my $filename=shift;
1.23      www      1673:     $filename=~s/\/+/\//g;
1.607     raeburn  1674:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1675:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1676:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1677: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1678: 	return &repcopy_userfile($filename);
                   1679:     }
1.532     albertel 1680:     $filename=~s/[\n\r]//g;
1.8       www      1681:     my $transname="$filename.in.transfer";
1.828     www      1682: # FIXME: this should flock
1.607     raeburn  1683:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1684:     my $remoteurl=subscribe($filename);
1.64      www      1685:     if ($remoteurl =~ /^con_lost by/) {
                   1686: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1687:            return 'unavailable';
1.8       www      1688:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1689: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1690: 	   return 'not_found';
1.64      www      1691:     } elsif ($remoteurl =~ /^rejected by/) {
                   1692: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1693:            return 'forbidden';
1.20      www      1694:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1695:            return 'ok';
1.8       www      1696:     } else {
1.290     www      1697:         my $author=$filename;
                   1698:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1699:         my ($udom,$uname)=split(/\//,$author);
                   1700:         my $home=homeserver($uname,$udom);
                   1701:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1702:            my @parts=split(/\//,$filename);
                   1703:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1704:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1705:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1706: 	       return 'bad_request';
1.8       www      1707:            }
                   1708:            my $count;
                   1709:            for ($count=5;$count<$#parts;$count++) {
                   1710:                $path.="/$parts[$count]";
                   1711:                if ((-e $path)!=1) {
                   1712: 		   mkdir($path,0777);
                   1713:                }
                   1714:            }
                   1715:            my $ua=new LWP::UserAgent;
                   1716:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1717:            my $response=$ua->request($request,$transname);
                   1718:            if ($response->is_error()) {
                   1719: 	       unlink($transname);
                   1720:                my $message=$response->status_line;
1.672     albertel 1721:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1722:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1723:                return 'unavailable';
1.8       www      1724:            } else {
1.16      www      1725: 	       if ($remoteurl!~/\.meta$/) {
                   1726:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1727:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1728:                   if ($mresponse->is_error()) {
                   1729: 		      unlink($filename.'.meta');
                   1730:                       &logthis(
1.672     albertel 1731:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1732:                   }
                   1733: 	       }
1.8       www      1734:                rename($transname,$filename);
1.607     raeburn  1735:                return 'ok';
1.8       www      1736:            }
1.290     www      1737:        }
1.8       www      1738:     }
1.330     www      1739: }
                   1740: 
                   1741: # ------------------------------------------------ Get server side include body
                   1742: sub ssi_body {
1.381     albertel 1743:     my ($filelink,%form)=@_;
1.606     matthew  1744:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1745:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1746:     }
1.953     www      1747:     my $output='';
                   1748:     my $response;
                   1749:     if ($filelink=~/^http\:/) {
1.954     raeburn  1750:        ($output,$response)=&externalssi($filelink);
1.953     www      1751:     } else {
                   1752:        ($output,$response)=&ssi($filelink,%form);
                   1753:     }
1.778     albertel 1754:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1755:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1756:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1757:     if (wantarray) {
                   1758:         return ($output, $response);
                   1759:     } else {
                   1760:         return $output;
                   1761:     }
1.8       www      1762: }
                   1763: 
1.15      www      1764: # --------------------------------------------------------- Server Side Include
                   1765: 
1.782     albertel 1766: sub absolute_url {
                   1767:     my ($host_name) = @_;
                   1768:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1769:     if ($host_name eq '') {
                   1770: 	$host_name = $ENV{'SERVER_NAME'};
                   1771:     }
                   1772:     return $protocol.$host_name;
                   1773: }
                   1774: 
1.942     foxr     1775: #
                   1776: #   Server side include.
                   1777: # Parameters:
                   1778: #  fn     Possibly encrypted resource name/id.
                   1779: #  form   Hash that describes how the rendering should be done
                   1780: #         and other things.
1.944     foxr     1781: # Returns:
1.950     raeburn  1782: #   Scalar context: The content of the response.
                   1783: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1784: #     
1.15      www      1785: sub ssi {
                   1786: 
1.944     foxr     1787:     my ($fn,%form)=@_;
1.15      www      1788:     my $ua=new LWP::UserAgent;
1.23      www      1789:     my $request;
1.711     albertel 1790: 
                   1791:     $form{'no_update_last_known'}=1;
1.895     albertel 1792:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1793:     if (%form) {
1.782     albertel 1794:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1795:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1796:     } else {
1.782     albertel 1797:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1798:     }
                   1799: 
1.15      www      1800:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1801:     my $response=$ua->request($request);
                   1802: 
1.944     foxr     1803:     if (wantarray) {
                   1804: 	return ($response->content, $response);
                   1805:     } else {
                   1806: 	return $response->content;
1.942     foxr     1807:     }
1.324     www      1808: }
                   1809: 
                   1810: sub externalssi {
                   1811:     my ($url)=@_;
                   1812:     my $ua=new LWP::UserAgent;
                   1813:     my $request=new HTTP::Request('GET',$url);
                   1814:     my $response=$ua->request($request);
1.954     raeburn  1815:     if (wantarray) {
                   1816:         return ($response->content, $response);
                   1817:     } else {
                   1818:         return $response->content;
                   1819:     }
1.15      www      1820: }
1.254     www      1821: 
1.492     albertel 1822: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1823: 
                   1824: sub allowuploaded {
                   1825:     my ($srcurl,$url)=@_;
                   1826:     $url=&clutter(&declutter($url));
                   1827:     my $dir=$url;
                   1828:     $dir=~s/\/[^\/]+$//;
                   1829:     my %httpref=();
                   1830:     my $httpurl=&hreflocation('',$url);
                   1831:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1832:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1833: }
1.477     raeburn  1834: 
1.478     albertel 1835: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1836: # input: action, courseID, current domain, intended
1.637     raeburn  1837: #        path to file, source of file, instruction to parse file for objects,
                   1838: #        ref to hash for embedded objects,
                   1839: #        ref to hash for codebase of java objects.
                   1840: #
1.485     raeburn  1841: # output: url to file (if action was uploaddoc), 
                   1842: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1843: #
1.478     albertel 1844: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1845: # course.
1.477     raeburn  1846: #
1.478     albertel 1847: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1848: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1849: #          course's home server.
1.477     raeburn  1850: #
1.478     albertel 1851: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1852: #          be copied from $source (current location) to 
                   1853: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1854: #         and will then be copied to
                   1855: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1856: #         course's home server.
1.485     raeburn  1857: #
1.481     raeburn  1858: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1859: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1860: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1861: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1862: #         in course's home server.
1.637     raeburn  1863: #
1.477     raeburn  1864: 
                   1865: sub process_coursefile {
1.638     albertel 1866:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1867:     my $fetchresult;
1.638     albertel 1868:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1869:     if ($action eq 'propagate') {
1.638     albertel 1870:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1871: 			     $home);
1.481     raeburn  1872:     } else {
1.477     raeburn  1873:         my $fpath = '';
                   1874:         my $fname = $file;
1.478     albertel 1875:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1876:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1877:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1878:         if ($action eq 'copy') {
                   1879:             if ($source eq '') {
                   1880:                 $fetchresult = 'no source file';
                   1881:                 return $fetchresult;
                   1882:             } else {
                   1883:                 my $destination = $filepath.'/'.$fname;
                   1884:                 rename($source,$destination);
                   1885:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1886:                                  $home);
1.481     raeburn  1887:             }
                   1888:         } elsif ($action eq 'uploaddoc') {
                   1889:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1890:             print $fh $env{'form.'.$source};
1.481     raeburn  1891:             close($fh);
1.637     raeburn  1892:             if ($parser eq 'parse') {
                   1893:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1894:                 unless ($parse_result eq 'ok') {
                   1895:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1896:                 }
                   1897:             }
1.477     raeburn  1898:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1899:                                  $home);
1.481     raeburn  1900:             if ($fetchresult eq 'ok') {
                   1901:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1902:             } else {
                   1903:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1904:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1905:                 return '/adm/notfound.html';
                   1906:             }
1.477     raeburn  1907:         }
                   1908:     }
1.485     raeburn  1909:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1910:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1911:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1912:     }
                   1913:     return $fetchresult;
                   1914: }
                   1915: 
1.637     raeburn  1916: sub build_filepath {
                   1917:     my ($fpath) = @_;
                   1918:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1919:     unless ($fpath eq '') {
                   1920:         my @parts=split('/',$fpath);
                   1921:         foreach my $part (@parts) {
                   1922:             $filepath.= '/'.$part;
                   1923:             if ((-e $filepath)!=1) {
                   1924:                 mkdir($filepath,0777);
                   1925:             }
                   1926:         }
                   1927:     }
                   1928:     return $filepath;
                   1929: }
                   1930: 
                   1931: sub store_edited_file {
1.638     albertel 1932:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1933:     my $file = $primary_url;
                   1934:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1935:     my $fpath = '';
                   1936:     my $fname = $file;
                   1937:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1938:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1939:     my $filepath = &build_filepath($fpath);
                   1940:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1941:     print $fh $content;
                   1942:     close($fh);
1.638     albertel 1943:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1944:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1945: 			  $home);
1.637     raeburn  1946:     if ($$fetchresult eq 'ok') {
                   1947:         return '/uploaded/'.$fpath.'/'.$fname;
                   1948:     } else {
1.638     albertel 1949:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1950: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1951:         return '/adm/notfound.html';
                   1952:     }
                   1953: }
                   1954: 
1.531     albertel 1955: sub clean_filename {
1.831     albertel 1956:     my ($fname,$args)=@_;
1.315     www      1957: # Replace Windows backslashes by forward slashes
1.257     www      1958:     $fname=~s/\\/\//g;
1.831     albertel 1959:     if (!$args->{'keep_path'}) {
                   1960:         # Get rid of everything but the actual filename
                   1961: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1962:     }
1.315     www      1963: # Replace spaces by underscores
                   1964:     $fname=~s/\s+/\_/g;
                   1965: # Replace all other weird characters by nothing
1.831     albertel 1966:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1967: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1968: # numbers
                   1969:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1970:     return $fname;
                   1971: }
                   1972: 
1.608     albertel 1973: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1974: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1975: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1976: #        $coursedoc - if true up to the current course
                   1977: #                     if false
                   1978: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1979: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1980: #        $allfiles - reference to hash for embedded objects
                   1981: #        $codebase - reference to hash for codebase of java objects
                   1982: #        $desuname - username for permanent storage of uploaded file
                   1983: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1984: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1985: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1986: # 
1.686     albertel 1987: # output: url of file in userspace, or error: <message> 
                   1988: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1989: 
                   1990: 
1.531     albertel 1991: sub userfileupload {
1.860     raeburn  1992:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1993:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1994:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1995:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1996:     $fname=&clean_filename($fname);
1.315     www      1997: # See if there is anything left
1.257     www      1998:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1999:     chop($env{'form.'.$formname});
1.523     raeburn  2000:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2001:         my $now = time;
                   2002:         my $filepath = 'tmp/helprequests/'.$now;
                   2003:         my @parts=split(/\//,$filepath);
                   2004:         my $fullpath = $perlvar{'lonDaemons'};
                   2005:         for (my $i=0;$i<@parts;$i++) {
                   2006:             $fullpath .= '/'.$parts[$i];
                   2007:             if ((-e $fullpath)!=1) {
                   2008:                 mkdir($fullpath,0777);
                   2009:             }
                   2010:         }
                   2011:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2012:         print $fh $env{'form.'.$formname};
1.523     raeburn  2013:         close($fh);
1.741     raeburn  2014:         return $fullpath.'/'.$fname;
                   2015:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2016:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2017:                        '_'.$env{'user.domain'}.'/pending';
                   2018:         my @parts=split(/\//,$filepath);
                   2019:         my $fullpath = $perlvar{'lonDaemons'};
                   2020:         for (my $i=0;$i<@parts;$i++) {
                   2021:             $fullpath .= '/'.$parts[$i];
                   2022:             if ((-e $fullpath)!=1) {
                   2023:                 mkdir($fullpath,0777);
                   2024:             }
                   2025:         }
                   2026:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2027:         print $fh $env{'form.'.$formname};
                   2028:         close($fh);
                   2029:         return $fullpath.'/'.$fname;
1.523     raeburn  2030:     }
1.719     banghart 2031:     
1.258     www      2032: # Create the directory if not present
1.493     albertel 2033:     $fname="$subdir/$fname";
1.259     www      2034:     if ($coursedoc) {
1.638     albertel 2035: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2036: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2037:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2038:             return &finishuserfileupload($docuname,$docudom,
                   2039: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2040: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2041:         } else {
1.620     albertel 2042:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2043:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2044: 				       $fname,$formname,$parser,
                   2045: 				       $allfiles,$codebase);
1.481     raeburn  2046:         }
1.719     banghart 2047:     } elsif (defined($destuname)) {
                   2048:         my $docuname=$destuname;
                   2049:         my $docudom=$destudom;
1.860     raeburn  2050: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2051: 				     $parser,$allfiles,$codebase,
                   2052:                                      $thumbwidth,$thumbheight);
1.719     banghart 2053:         
1.259     www      2054:     } else {
1.638     albertel 2055:         my $docuname=$env{'user.name'};
                   2056:         my $docudom=$env{'user.domain'};
1.714     raeburn  2057:         if (exists($env{'form.group'})) {
                   2058:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2059:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2060:         }
1.860     raeburn  2061: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2062: 				     $parser,$allfiles,$codebase,
                   2063:                                      $thumbwidth,$thumbheight);
1.259     www      2064:     }
1.271     www      2065: }
                   2066: 
                   2067: sub finishuserfileupload {
1.860     raeburn  2068:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2069:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2070:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2071:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2072:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2073:     $file=$fname;
                   2074:     if ($fname=~m|/|) {
                   2075:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2076: 	$path.=$fnamepath.'/';
                   2077:     }
1.259     www      2078:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2079:     my $count;
                   2080:     for ($count=4;$count<=$#parts;$count++) {
                   2081:         $filepath.="/$parts[$count]";
                   2082:         if ((-e $filepath)!=1) {
                   2083: 	    mkdir($filepath,0777);
                   2084:         }
                   2085:     }
                   2086: # Save the file
                   2087:     {
1.701     albertel 2088: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2089: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2090: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2091: 	    return '/adm/notfound.html';
                   2092: 	}
                   2093: 	if (!print FH ($env{'form.'.$formname})) {
                   2094: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2095: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2096: 	    return '/adm/notfound.html';
                   2097: 	}
1.570     albertel 2098: 	close(FH);
1.258     www      2099:     }
1.637     raeburn  2100:     if ($parser eq 'parse') {
1.638     albertel 2101:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2102: 						   $codebase);
1.637     raeburn  2103:         unless ($parse_result eq 'ok') {
1.638     albertel 2104:             &logthis('Failed to parse '.$filepath.$file.
                   2105: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2106:         }
                   2107:     }
1.860     raeburn  2108:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2109:         my $input = $filepath.'/'.$file;
                   2110:         my $output = $filepath.'/'.'tn-'.$file;
                   2111:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2112:         system("convert -sample $thumbsize $input $output");
                   2113:         if (-e $filepath.'/'.'tn-'.$file) {
                   2114:             $fetchthumb  = 1; 
                   2115:         }
                   2116:     }
1.858     raeburn  2117:  
1.259     www      2118: # Notify homeserver to grep it
                   2119: #
1.638     albertel 2120:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2121:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2122:     if ($fetchresult eq 'ok') {
1.860     raeburn  2123:         if ($fetchthumb) {
                   2124:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2125:             if ($thumbresult ne 'ok') {
                   2126:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2127:                          $docuhome.': '.$thumbresult);
                   2128:             }
                   2129:         }
1.259     www      2130: #
1.258     www      2131: # Return the URL to it
1.494     albertel 2132:         return '/uploaded/'.$path.$file;
1.263     www      2133:     } else {
1.494     albertel 2134:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2135: 		 ': '.$fetchresult);
1.263     www      2136:         return '/adm/notfound.html';
1.858     raeburn  2137:     }
1.493     albertel 2138: }
                   2139: 
1.637     raeburn  2140: sub extract_embedded_items {
1.648     raeburn  2141:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2142:     my @state = ();
                   2143:     my %javafiles = (
                   2144:                       codebase => '',
                   2145:                       code => '',
                   2146:                       archive => ''
                   2147:                     );
                   2148:     my %mediafiles = (
                   2149:                       src => '',
                   2150:                       movie => '',
                   2151:                      );
1.648     raeburn  2152:     my $p;
                   2153:     if ($content) {
                   2154:         $p = HTML::LCParser->new($content);
                   2155:     } else {
                   2156:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2157:     }
1.641     albertel 2158:     while (my $t=$p->get_token()) {
1.640     albertel 2159: 	if ($t->[0] eq 'S') {
                   2160: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2161: 	    push(@state, $tagname);
1.648     raeburn  2162:             if (lc($tagname) eq 'allow') {
                   2163:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2164:             }
1.640     albertel 2165: 	    if (lc($tagname) eq 'img') {
                   2166: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2167: 	    }
1.886     albertel 2168: 	    if (lc($tagname) eq 'a') {
                   2169: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2170: 	    }
1.645     raeburn  2171:             if (lc($tagname) eq 'script') {
                   2172:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2173:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2174:                 } else {
                   2175:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2176:                 }
                   2177:             }
                   2178:             if (lc($tagname) eq 'link') {
                   2179:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2180:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2181:                 }
                   2182:             }
1.640     albertel 2183: 	    if (lc($tagname) eq 'object' ||
                   2184: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2185: 		foreach my $item (keys(%javafiles)) {
                   2186: 		    $javafiles{$item} = '';
                   2187: 		}
                   2188: 	    }
                   2189: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2190: 		my $name = lc($attr->{'name'});
                   2191: 		foreach my $item (keys(%javafiles)) {
                   2192: 		    if ($name eq $item) {
                   2193: 			$javafiles{$item} = $attr->{'value'};
                   2194: 			last;
                   2195: 		    }
                   2196: 		}
                   2197: 		foreach my $item (keys(%mediafiles)) {
                   2198: 		    if ($name eq $item) {
                   2199: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2200: 			last;
                   2201: 		    }
                   2202: 		}
                   2203: 	    }
                   2204: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2205: 		foreach my $item (keys(%javafiles)) {
                   2206: 		    if ($attr->{$item}) {
                   2207: 			$javafiles{$item} = $attr->{$item};
                   2208: 			last;
                   2209: 		    }
                   2210: 		}
                   2211: 		foreach my $item (keys(%mediafiles)) {
                   2212: 		    if ($attr->{$item}) {
                   2213: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2214: 			last;
                   2215: 		    }
                   2216: 		}
                   2217: 	    }
                   2218: 	} elsif ($t->[0] eq 'E') {
                   2219: 	    my ($tagname) = ($t->[1]);
                   2220: 	    if ($javafiles{'codebase'} ne '') {
                   2221: 		$javafiles{'codebase'} .= '/';
                   2222: 	    }  
                   2223: 	    if (lc($tagname) eq 'applet' ||
                   2224: 		lc($tagname) eq 'object' ||
                   2225: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2226: 		) {
                   2227: 		foreach my $item (keys(%javafiles)) {
                   2228: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2229: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2230: 			&add_filetype($allfiles,$file,$item);
                   2231: 		    }
                   2232: 		}
                   2233: 	    } 
                   2234: 	    pop @state;
                   2235: 	}
                   2236:     }
1.637     raeburn  2237:     return 'ok';
                   2238: }
                   2239: 
1.639     albertel 2240: sub add_filetype {
                   2241:     my ($allfiles,$file,$type)=@_;
                   2242:     if (exists($allfiles->{$file})) {
                   2243: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2244: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2245: 	}
                   2246:     } else {
                   2247: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2248:     }
                   2249: }
                   2250: 
1.493     albertel 2251: sub removeuploadedurl {
                   2252:     my ($url)=@_;
                   2253:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2254:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2255: }
                   2256: 
                   2257: sub removeuserfile {
                   2258:     my ($docuname,$docudom,$fname)=@_;
                   2259:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2260:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2261:     if ($result eq 'ok') {
                   2262:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2263:             my $metafile = $fname.'.meta';
                   2264:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2265: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2266:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2267:             my $sqlresult = 
1.823     albertel 2268:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2269:                                         'portfolio_metadata',$group,
                   2270:                                         'delete');
1.798     raeburn  2271:         }
                   2272:     }
                   2273:     return $result;
1.257     www      2274: }
1.15      www      2275: 
1.530     albertel 2276: sub mkdiruserfile {
                   2277:     my ($docuname,$docudom,$dir)=@_;
                   2278:     my $home=&homeserver($docuname,$docudom);
                   2279:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2280: }
                   2281: 
1.531     albertel 2282: sub renameuserfile {
                   2283:     my ($docuname,$docudom,$old,$new)=@_;
                   2284:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2285:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2286:                         &escape("$old").':'.&escape("$new"),$home);
                   2287:     if ($result eq 'ok') {
                   2288:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2289:             my $oldmeta = $old.'.meta';
                   2290:             my $newmeta = $new.'.meta';
                   2291:             my $metaresult = 
                   2292:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2293: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2294:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2295:             my $sqlresult = 
1.823     albertel 2296:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2297:                                         'portfolio_metadata',$group,
                   2298:                                         'delete');
1.798     raeburn  2299:         }
                   2300:     }
                   2301:     return $result;
1.531     albertel 2302: }
                   2303: 
1.14      www      2304: # ------------------------------------------------------------------------- Log
                   2305: 
                   2306: sub log {
                   2307:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2308:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2309: }
                   2310: 
                   2311: # ------------------------------------------------------------------ Course Log
1.352     www      2312: #
                   2313: # This routine flushes several buffers of non-mission-critical nature
                   2314: #
1.157     www      2315: 
                   2316: sub flushcourselogs {
1.352     www      2317:     &logthis('Flushing log buffers');
                   2318: #
                   2319: # course logs
                   2320: # This is a log of all transactions in a course, which can be used
                   2321: # for data mining purposes
                   2322: #
                   2323: # It also collects the courseid database, which lists last transaction
                   2324: # times and course titles for all courseids
                   2325: #
                   2326:     my %courseidbuffer=();
1.921     raeburn  2327:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2328:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2329: 		          &escape($courselogs{$crsid}),
                   2330: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2331: 	    delete $courselogs{$crsid};
                   2332:         } else {
                   2333:             &logthis('Failed to flush log buffer for '.$crsid);
                   2334:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2335:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2336:                         " exceeded maximum size, deleting.</font>");
                   2337:                delete $courselogs{$crsid};
                   2338:             }
1.352     www      2339:         }
1.920     raeburn  2340:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2341:             'description' => $coursedescrbuf{$crsid},
                   2342:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2343:             'type'        => $coursetypebuf{$crsid},
                   2344:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2345:         };
1.191     harris41 2346:     }
1.352     www      2347: #
                   2348: # Write course id database (reverse lookup) to homeserver of courses 
                   2349: # Is used in pickcourse
                   2350: #
1.840     albertel 2351:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2352:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2353:                                     $courseidbuffer{$crs_home},
                   2354:                                     $crs_home,'timeonly');
1.352     www      2355:     }
                   2356: #
                   2357: # File accesses
                   2358: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2359: #
1.449     matthew  2360:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2361:         if ($entry =~ /___count$/) {
                   2362:             my ($dom,$name);
1.807     albertel 2363:             ($dom,$name,undef)=
1.811     albertel 2364: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2365:             if (! defined($dom) || $dom eq '' || 
                   2366:                 ! defined($name) || $name eq '') {
1.620     albertel 2367:                 my $cid = $env{'request.course.id'};
                   2368:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2369:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2370:             }
1.450     matthew  2371:             my $value = $accesshash{$entry};
                   2372:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2373:             my %temphash=($url => $value);
1.449     matthew  2374:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2375:             if ($result eq 'ok') {
                   2376:                 delete $accesshash{$entry};
                   2377:             } elsif ($result eq 'unknown_cmd') {
                   2378:                 # Target server has old code running on it.
1.450     matthew  2379:                 my %temphash=($entry => $value);
1.449     matthew  2380:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2381:                     delete $accesshash{$entry};
                   2382:                 }
                   2383:             }
                   2384:         } else {
1.811     albertel 2385:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2386:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2387:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2388:                 delete $accesshash{$entry};
                   2389:             }
1.185     www      2390:         }
1.191     harris41 2391:     }
1.352     www      2392: #
                   2393: # Roles
                   2394: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2395: #
1.800     albertel 2396:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2397:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2398: 	    split(/\:/,$entry);
                   2399:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2400:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2401:                 $rudom,$runame) eq 'ok') {
                   2402: 	    delete $userrolehash{$entry};
                   2403:         }
                   2404:     }
1.662     raeburn  2405: #
                   2406: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2407: #
                   2408:     my %domrolebuffer = ();
                   2409:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2410:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2411:         if ($domrolebuffer{$rudom}) {
                   2412:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2413:                       '='.&escape($domainrolehash{$entry});
                   2414:         } else {
                   2415:             $domrolebuffer{$rudom}.=&escape($entry).
                   2416:                       '='.&escape($domainrolehash{$entry});
                   2417:         }
                   2418:         delete $domainrolehash{$entry};
                   2419:     }
                   2420:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2421: 	my %servers = &get_servers($dom,'library');
                   2422: 	foreach my $tryserver (keys(%servers)) {
                   2423: 	    unless (&reply('domroleput:'.$dom.':'.
                   2424: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2425: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2426: 	    }
1.662     raeburn  2427:         }
                   2428:     }
1.186     www      2429:     $dumpcount++;
1.157     www      2430: }
                   2431: 
                   2432: sub courselog {
                   2433:     my $what=shift;
1.158     www      2434:     $what=time.':'.$what;
1.620     albertel 2435:     unless ($env{'request.course.id'}) { return ''; }
                   2436:     $coursedombuf{$env{'request.course.id'}}=
                   2437:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2438:     $coursenumbuf{$env{'request.course.id'}}=
                   2439:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2440:     $coursehombuf{$env{'request.course.id'}}=
                   2441:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2442:     $coursedescrbuf{$env{'request.course.id'}}=
                   2443:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2444:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2445:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2446:     $courseownerbuf{$env{'request.course.id'}}=
                   2447:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2448:     $coursetypebuf{$env{'request.course.id'}}=
                   2449:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2450:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2451: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2452:     } else {
1.620     albertel 2453: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2454:     }
1.620     albertel 2455:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2456: 	&flushcourselogs();
                   2457:     }
1.158     www      2458: }
                   2459: 
                   2460: sub courseacclog {
                   2461:     my $fnsymb=shift;
1.620     albertel 2462:     unless ($env{'request.course.id'}) { return ''; }
                   2463:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2464:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2465:         $what.=':POST';
1.583     matthew  2466:         # FIXME: Probably ought to escape things....
1.800     albertel 2467: 	foreach my $key (keys(%env)) {
                   2468:             if ($key=~/^form\.(.*)/) {
                   2469: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2470:             }
1.191     harris41 2471:         }
1.583     matthew  2472:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2473:         # FIXME: We should not be depending on a form parameter that someone
                   2474:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2475:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2476:             $what.= ':POST';
                   2477:             # FIXME: Probably ought to escape things....
                   2478:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2479:                                  'crsdiscuss') {
1.620     albertel 2480:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2481:             }
                   2482:         }
1.158     www      2483:     }
                   2484:     &courselog($what);
1.149     www      2485: }
                   2486: 
1.185     www      2487: sub countacc {
                   2488:     my $url=&declutter(shift);
1.458     matthew  2489:     return if (! defined($url) || $url eq '');
1.620     albertel 2490:     unless ($env{'request.course.id'}) { return ''; }
                   2491:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2492:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2493:     $accesshash{$key}++;
1.185     www      2494: }
1.349     www      2495: 
1.361     www      2496: sub linklog {
                   2497:     my ($from,$to)=@_;
                   2498:     $from=&declutter($from);
                   2499:     $to=&declutter($to);
                   2500:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2501:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2502: }
                   2503:   
1.349     www      2504: sub userrolelog {
                   2505:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2506:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2507:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2508:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2509:         ($trole=~/^ta/)) {
1.350     www      2510:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2511:        $userrolehash
                   2512:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2513:                     =$tend.':'.$tstart;
1.662     raeburn  2514:     }
1.898     albertel 2515:     if (($env{'request.role'} =~ /dc\./) &&
                   2516: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2517: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2518: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2519:        $userrolehash
                   2520:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2521:                     =$tend.':'.$tstart;
                   2522:     }
1.662     raeburn  2523:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2524:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2525:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2526:         ($trole=~/^sc/)) {
                   2527:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2528:        $domainrolehash
                   2529:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2530:                     = $tend.':'.$tstart;
                   2531:     }
1.351     www      2532: }
                   2533: 
1.957     raeburn  2534: sub courserolelog {
                   2535:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2536:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2537:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2538:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2539:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2540:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2541:             my $cdom = $1;
                   2542:             my $cnum = $2;
                   2543:             my $sec = $3;
                   2544:             my $namespace = 'rolelog';
                   2545:             my %storehash = (
                   2546:                                role    => $trole,
                   2547:                                start   => $tstart,
                   2548:                                end     => $tend,
                   2549:                                selfenroll => $selfenroll,
                   2550:                                context    => $context,
                   2551:                             );
                   2552:             if ($trole eq 'gr') {
                   2553:                 $namespace = 'groupslog';
                   2554:                 $storehash{'group'} = $sec;
                   2555:             } else {
                   2556:                 $storehash{'section'} = $sec;
                   2557:             }
                   2558:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2559:         }
                   2560:     }
                   2561:     return;
                   2562: }
                   2563: 
1.351     www      2564: sub get_course_adv_roles {
1.948     raeburn  2565:     my ($cid,$codes) = @_;
1.620     albertel 2566:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2567:     my %coursehash=&coursedescription($cid);
1.470     www      2568:     my %nothide=();
1.800     albertel 2569:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2570:         if ($user !~ /:/) {
                   2571: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2572:         } else {
                   2573:             $nothide{$user}=1;
                   2574:         }
1.470     www      2575:     }
1.351     www      2576:     my %returnhash=();
                   2577:     my %dumphash=
                   2578:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2579:     my $now=time;
1.800     albertel 2580:     foreach my $entry (keys %dumphash) {
                   2581: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2582:         if (($tstart) && ($tstart<0)) { next; }
                   2583:         if (($tend) && ($tend<$now)) { next; }
                   2584:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2585:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2586: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2587: 	if ((&privileged($username,$domain)) && 
                   2588: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2589: 	if ($role eq 'cr') { next; }
1.948     raeburn  2590:         if ($codes) {
                   2591:             if ($section) { $role .= ':'.$section; }
                   2592:             if ($returnhash{$role}) {
                   2593:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2594:             } else {
                   2595:                 $returnhash{$role}=$username.':'.$domain;
                   2596:             }
1.351     www      2597:         } else {
1.948     raeburn  2598:             my $key=&plaintext($role);
                   2599:             if ($section) { $key.=' (Section '.$section.')'; }
                   2600:             if ($returnhash{$key}) {
                   2601: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2602:             } else {
                   2603:                 $returnhash{$key}=$username.':'.$domain;
                   2604:             }
1.351     www      2605:         }
1.948     raeburn  2606:     }
1.400     www      2607:     return %returnhash;
                   2608: }
                   2609: 
                   2610: sub get_my_roles {
1.937     raeburn  2611:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2612:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2613:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2614:     my (%dumphash,%nothide);
1.858     raeburn  2615:     if ($context eq 'userroles') { 
                   2616:         %dumphash = &dump('roles',$udom,$uname);
                   2617:     } else {
                   2618:         %dumphash=
1.400     www      2619:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2620:         if ($hidepriv) {
                   2621:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2622:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2623:                 if ($user !~ /:/) {
                   2624:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2625:                 } else {
                   2626:                     $nothide{$user} = 1;
                   2627:                 }
                   2628:             }
                   2629:         }
1.858     raeburn  2630:     }
1.400     www      2631:     my %returnhash=();
                   2632:     my $now=time;
1.800     albertel 2633:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2634:         my ($role,$tend,$tstart);
                   2635:         if ($context eq 'userroles') {
                   2636: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2637:         } else {
                   2638:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2639:         }
1.400     www      2640:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2641:         my $status = 'active';
1.939     raeburn  2642:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2643:             $status = 'previous';
                   2644:         } 
                   2645:         if (($tstart) && ($now<$tstart)) {
                   2646:             $status = 'future';
                   2647:         }
                   2648:         if (ref($types) eq 'ARRAY') {
                   2649:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2650:                 next;
                   2651:             } 
                   2652:         } else {
                   2653:             if ($status ne 'active') {
                   2654:                 next;
                   2655:             }
                   2656:         }
1.867     raeburn  2657:         my ($rolecode,$username,$domain,$section,$area);
                   2658:         if ($context eq 'userroles') {
                   2659:             ($area,$rolecode) = split(/_/,$entry);
                   2660:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2661:         } else {
                   2662:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2663:         }
1.832     raeburn  2664:         if (ref($roledoms) eq 'ARRAY') {
                   2665:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2666:                 next;
                   2667:             }
                   2668:         }
                   2669:         if (ref($roles) eq 'ARRAY') {
                   2670:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2671:                 if ($role =~ /^cr\//) {
                   2672:                     if (!grep(/^cr$/,@{$roles})) {
                   2673:                         next;
                   2674:                     }
                   2675:                 } else {
                   2676:                     next;
                   2677:                 }
1.832     raeburn  2678:             }
1.867     raeburn  2679:         }
1.937     raeburn  2680:         if ($hidepriv) {
                   2681:             if ((&privileged($username,$domain)) &&
                   2682:                 (!$nothide{$username.':'.$domain})) { 
                   2683:                 next;
                   2684:             }
                   2685:         }
1.933     raeburn  2686:         if ($withsec) {
                   2687:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2688:                 $tstart.':'.$tend;
                   2689:         } else {
                   2690:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2691:         }
1.832     raeburn  2692:     }
1.373     www      2693:     return %returnhash;
1.399     www      2694: }
                   2695: 
                   2696: # ----------------------------------------------------- Frontpage Announcements
                   2697: #
                   2698: #
                   2699: 
                   2700: sub postannounce {
                   2701:     my ($server,$text)=@_;
1.844     albertel 2702:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2703:     unless ($text=~/\w/) { $text=''; }
                   2704:     return &reply('setannounce:'.&escape($text),$server);
                   2705: }
                   2706: 
                   2707: sub getannounce {
1.448     albertel 2708: 
                   2709:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2710: 	my $announcement='';
1.800     albertel 2711: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2712: 	close($fh);
1.399     www      2713: 	if ($announcement=~/\w/) { 
                   2714: 	    return 
                   2715:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2716:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2717: 	} else {
                   2718: 	    return '';
                   2719: 	}
                   2720:     } else {
                   2721: 	return '';
                   2722:     }
1.351     www      2723: }
1.353     www      2724: 
                   2725: # ---------------------------------------------------------- Course ID routines
                   2726: # Deal with domain's nohist_courseid.db files
                   2727: #
                   2728: 
                   2729: sub courseidput {
1.921     raeburn  2730:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2731:     my $outcome;
                   2732:     if ($caller eq 'timeonly') {
                   2733:         my $cids = '';
                   2734:         foreach my $item (keys(%$storehash)) {
                   2735:             $cids.=&escape($item).'&';
                   2736:         }
                   2737:         $cids=~s/\&$//;
                   2738:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2739:                           $coursehome);       
                   2740:     } else {
                   2741:         my $items = '';
                   2742:         foreach my $item (keys(%$storehash)) {
                   2743:             $items.= &escape($item).'='.
                   2744:                      &freeze_escape($$storehash{$item}).'&';
                   2745:         }
                   2746:         $items=~s/\&$//;
                   2747:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2748:                           $coursehome);
1.918     raeburn  2749:     }
                   2750:     if ($outcome eq 'unknown_cmd') {
                   2751:         my $what;
                   2752:         foreach my $cid (keys(%$storehash)) {
                   2753:             $what .= &escape($cid).'=';
1.921     raeburn  2754:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2755:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2756:             }
                   2757:             $what =~ s/\:$/&/;
                   2758:         }
                   2759:         $what =~ s/\&$//;  
                   2760:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2761:     } else {
                   2762:         return $outcome;
                   2763:     }
1.353     www      2764: }
                   2765: 
                   2766: sub courseiddump {
1.921     raeburn  2767:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2768:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.959     raeburn  2769:         $selfenrollonly,$catfilter)=@_;
1.918     raeburn  2770:     my $as_hash = 1;
                   2771:     my %returnhash;
                   2772:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2773:     my %libserv = &all_library();
                   2774:     foreach my $tryserver (keys(%libserv)) {
                   2775:         if ( (  $hostidflag == 1 
                   2776: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2777: 	     || (!defined($hostidflag)) ) {
                   2778: 
1.918     raeburn  2779: 	    if (($domfilter eq '') ||
                   2780: 		(&host_domain($tryserver) eq $domfilter)) {
                   2781:                 my $rep = 
                   2782:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2783:                          $sincefilter.':'.&escape($descfilter).':'.
                   2784:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2785:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2786:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.959     raeburn  2787:                          &escape($selfenrollonly).':'.&escape($catfilter),$tryserver);
1.918     raeburn  2788:                 my @pairs=split(/\&/,$rep);
                   2789:                 foreach my $item (@pairs) {
                   2790:                     my ($key,$value)=split(/\=/,$item,2);
                   2791:                     $key = &unescape($key);
                   2792:                     next if ($key =~ /^error: 2 /);
                   2793:                     my $result = &thaw_unescape($value);
                   2794:                     if (ref($result) eq 'HASH') {
                   2795:                         $returnhash{$key}=$result;
                   2796:                     } else {
1.921     raeburn  2797:                         my @responses = split(/:/,$value);
                   2798:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2799:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2800:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2801:                         }
                   2802:                     } 
1.353     www      2803:                 }
                   2804:             }
                   2805:         }
                   2806:     }
                   2807:     return %returnhash;
                   2808: }
                   2809: 
1.658     raeburn  2810: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2811: 
                   2812: sub dcmailput {
1.685     raeburn  2813:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2814:     my $status = &Apache::lonnet::critical(
1.740     www      2815:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2816:        &escape($message),$server);
1.662     raeburn  2817:     return $status;
                   2818: }
                   2819: 
1.658     raeburn  2820: sub dcmaildump {
                   2821:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2822:     my %returnhash=();
1.846     albertel 2823: 
                   2824:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2825:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2826:                                                          &escape($enddate).':';
                   2827: 	my @esc_senders=map { &escape($_)} @$senders;
                   2828: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2829: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2830:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2831:             if (($key) && ($value)) {
                   2832:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2833:             }
                   2834:         }
                   2835:     }
                   2836:     return %returnhash;
                   2837: }
1.662     raeburn  2838: # ---------------------------------------------------------- Domain roles
                   2839: 
                   2840: sub get_domain_roles {
                   2841:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2842:     if (undef($startdate) || $startdate eq '') {
                   2843:         $startdate = '.';
                   2844:     }
                   2845:     if (undef($enddate) || $enddate eq '') {
                   2846:         $enddate = '.';
                   2847:     }
1.922     raeburn  2848:     my $rolelist;
                   2849:     if (ref($roles) eq 'ARRAY') {
                   2850:         $rolelist = join(':',@{$roles});
                   2851:     }
1.662     raeburn  2852:     my %personnel = ();
1.841     albertel 2853: 
                   2854:     my %servers = &get_servers($dom,'library');
                   2855:     foreach my $tryserver (keys(%servers)) {
                   2856: 	%{$personnel{$tryserver}}=();
                   2857: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2858: 					    &escape($startdate).':'.
                   2859: 					    &escape($enddate).':'.
                   2860: 					    &escape($rolelist), $tryserver))) {
                   2861: 	    my ($key,$value) = split(/\=/,$line,2);
                   2862: 	    if (($key) && ($value)) {
                   2863: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2864: 	    }
                   2865: 	}
1.662     raeburn  2866:     }
                   2867:     return %personnel;
                   2868: }
1.658     raeburn  2869: 
1.149     www      2870: # ----------------------------------------------------------- Check out an item
                   2871: 
1.504     albertel 2872: sub get_first_access {
                   2873:     my ($type,$argsymb)=@_;
1.790     albertel 2874:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2875:     if ($argsymb) { $symb=$argsymb; }
                   2876:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2877:     if ($type eq 'course') {
                   2878: 	$res='course';
                   2879:     } elsif ($type eq 'map') {
1.588     albertel 2880: 	$res=&symbread($map);
                   2881:     } else {
                   2882: 	$res=$symb;
                   2883:     }
                   2884:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2885:     return $times{"$courseid\0$res"};
1.504     albertel 2886: }
                   2887: 
                   2888: sub set_first_access {
                   2889:     my ($type)=@_;
1.790     albertel 2890:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2891:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2892:     if ($type eq 'course') {
                   2893: 	$res='course';
                   2894:     } elsif ($type eq 'map') {
1.588     albertel 2895: 	$res=&symbread($map);
                   2896:     } else {
                   2897: 	$res=$symb;
                   2898:     }
                   2899:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2900:     if (!$firstaccess) {
1.588     albertel 2901: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2902:     }
                   2903:     return 'already_set';
1.504     albertel 2904: }
                   2905: 
1.149     www      2906: sub checkout {
                   2907:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2908:     my $now=time;
                   2909:     my $lonhost=$perlvar{'lonHostID'};
                   2910:     my $infostr=&escape(
1.234     www      2911:                  'CHECKOUTTOKEN&'.
1.149     www      2912:                  $tuname.'&'.
                   2913:                  $tudom.'&'.
                   2914:                  $tcrsid.'&'.
                   2915:                  $symb.'&'.
                   2916: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2917:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2918:     if ($token=~/^error\:/) { 
1.672     albertel 2919:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2920:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2921:                  "</font>");
                   2922:         return ''; 
                   2923:     }
                   2924: 
1.149     www      2925:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2926:     $token=~tr/a-z/A-Z/;
                   2927: 
1.153     www      2928:     my %infohash=('resource.0.outtoken' => $token,
                   2929:                   'resource.0.checkouttime' => $now,
                   2930:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2931: 
                   2932:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2933:        return '';
1.151     www      2934:     } else {
1.672     albertel 2935:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2936:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2937:                  "</font>");
1.149     www      2938:     }    
                   2939: 
                   2940:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2941:                          &escape('Checkout '.$infostr.' - '.
                   2942:                                                  $token)) ne 'ok') {
                   2943: 	return '';
1.151     www      2944:     } else {
1.672     albertel 2945:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2946:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2947:                  "</font>");
1.149     www      2948:     }
1.151     www      2949:     return $token;
1.149     www      2950: }
                   2951: 
                   2952: # ------------------------------------------------------------ Check in an item
                   2953: 
                   2954: sub checkin {
                   2955:     my $token=shift;
1.150     www      2956:     my $now=time;
                   2957:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2958:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2959:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2960:     $dtoken=~s/\W/\_/g;
1.234     www      2961:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2962:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2963: 
1.154     www      2964:     unless (($tuname) && ($tudom)) {
                   2965:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2966:         return '';
                   2967:     }
                   2968:     
                   2969:     unless (&allowed('mgr',$tcrsid)) {
                   2970:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2971:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2972:         return '';
                   2973:     }
                   2974: 
1.153     www      2975:     my %infohash=('resource.0.intoken' => $token,
                   2976:                   'resource.0.checkintime' => $now,
                   2977:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2978: 
                   2979:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2980:        return '';
                   2981:     }    
                   2982: 
                   2983:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2984:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2985: 	return '';
                   2986:     }
                   2987: 
                   2988:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2989: }
                   2990: 
                   2991: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2992: 
                   2993: sub expirespread {
                   2994:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2995:     my $cid=$env{'request.course.id'}; 
1.110     www      2996:     if ($cid) {
                   2997:        my $now=time;
                   2998:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2999:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3000:                             $env{'course.'.$cid.'.num'}.
1.110     www      3001: 	        	    ':nohist_expirationdates:'.
                   3002:                             &escape($key).'='.$now,
1.620     albertel 3003:                             $env{'course.'.$cid.'.home'})
1.110     www      3004:     }
                   3005:     return 'ok';
1.14      www      3006: }
                   3007: 
1.109     www      3008: # ----------------------------------------------------- Devalidate Spreadsheets
                   3009: 
                   3010: sub devalidate {
1.325     www      3011:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3012:     my $cid=$env{'request.course.id'}; 
1.109     www      3013:     if ($cid) {
1.391     matthew  3014:         # delete the stored spreadsheets for
                   3015:         # - the student level sheet of this user in course's homespace
                   3016:         # - the assessment level sheet for this resource 
                   3017:         #   for this user in user's homespace
1.553     albertel 3018: 	# - current conditional state info
1.325     www      3019: 	my $key=$uname.':'.$udom.':';
1.109     www      3020:         my $status=
1.299     matthew  3021: 	    &del('nohist_calculatedsheets',
1.391     matthew  3022: 		 [$key.'studentcalc:'],
1.620     albertel 3023: 		 $env{'course.'.$cid.'.domain'},
                   3024: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3025: 		.' '.
                   3026: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3027: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3028:         unless ($status eq 'ok ok') {
                   3029:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3030:                     $uname.' at '.$udom.' for '.
1.109     www      3031: 		    $symb.': '.$status);
1.133     albertel 3032:         }
1.553     albertel 3033: 	&delenv('user.state.'.$cid);
1.109     www      3034:     }
                   3035: }
                   3036: 
1.265     albertel 3037: sub get_scalar {
                   3038:     my ($string,$end) = @_;
                   3039:     my $value;
                   3040:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3041: 	$value = $1;
                   3042:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3043: 	$value = $1;
                   3044:     }
                   3045:     return &unescape($value);
                   3046: }
                   3047: 
                   3048: sub array2str {
                   3049:   my (@array) = @_;
                   3050:   my $result=&arrayref2str(\@array);
                   3051:   $result=~s/^__ARRAY_REF__//;
                   3052:   $result=~s/__END_ARRAY_REF__$//;
                   3053:   return $result;
                   3054: }
                   3055: 
1.204     albertel 3056: sub arrayref2str {
                   3057:   my ($arrayref) = @_;
1.265     albertel 3058:   my $result='__ARRAY_REF__';
1.204     albertel 3059:   foreach my $elem (@$arrayref) {
1.265     albertel 3060:     if(ref($elem) eq 'ARRAY') {
                   3061:       $result.=&arrayref2str($elem).'&';
                   3062:     } elsif(ref($elem) eq 'HASH') {
                   3063:       $result.=&hashref2str($elem).'&';
                   3064:     } elsif(ref($elem)) {
                   3065:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3066:     } else {
                   3067:       $result.=&escape($elem).'&';
                   3068:     }
                   3069:   }
                   3070:   $result=~s/\&$//;
1.265     albertel 3071:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3072:   return $result;
                   3073: }
                   3074: 
1.168     albertel 3075: sub hash2str {
1.204     albertel 3076:   my (%hash) = @_;
                   3077:   my $result=&hashref2str(\%hash);
1.265     albertel 3078:   $result=~s/^__HASH_REF__//;
                   3079:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3080:   return $result;
                   3081: }
                   3082: 
                   3083: sub hashref2str {
                   3084:   my ($hashref)=@_;
1.265     albertel 3085:   my $result='__HASH_REF__';
1.800     albertel 3086:   foreach my $key (sort(keys(%$hashref))) {
                   3087:     if (ref($key) eq 'ARRAY') {
                   3088:       $result.=&arrayref2str($key).'=';
                   3089:     } elsif (ref($key) eq 'HASH') {
                   3090:       $result.=&hashref2str($key).'=';
                   3091:     } elsif (ref($key)) {
1.265     albertel 3092:       $result.='=';
1.800     albertel 3093:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3094:     } else {
1.800     albertel 3095: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3096:     }
                   3097: 
1.800     albertel 3098:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3099:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3100:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3101:       $result.=&hashref2str($hashref->{$key}).'&';
                   3102:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3103:        $result.='&';
1.800     albertel 3104:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3105:     } else {
1.800     albertel 3106:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3107:     }
                   3108:   }
1.168     albertel 3109:   $result=~s/\&$//;
1.265     albertel 3110:   $result .= '__END_HASH_REF__';
1.168     albertel 3111:   return $result;
                   3112: }
                   3113: 
                   3114: sub str2hash {
1.265     albertel 3115:     my ($string)=@_;
                   3116:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3117:     return %$hash;
                   3118: }
                   3119: 
                   3120: sub str2hashref {
1.168     albertel 3121:   my ($string) = @_;
1.265     albertel 3122: 
                   3123:   my %hash;
                   3124: 
                   3125:   if($string !~ /^__HASH_REF__/) {
                   3126:       if (! ($string eq '' || !defined($string))) {
                   3127: 	  $hash{'error'}='Not hash reference';
                   3128:       }
                   3129:       return (\%hash, $string);
                   3130:   }
                   3131: 
                   3132:   $string =~ s/^__HASH_REF__//;
                   3133: 
                   3134:   while($string !~ /^__END_HASH_REF__/) {
                   3135:       #key
                   3136:       my $key='';
                   3137:       if($string =~ /^__HASH_REF__/) {
                   3138:           ($key, $string)=&str2hashref($string);
                   3139:           if(defined($key->{'error'})) {
                   3140:               $hash{'error'}='Bad data';
                   3141:               return (\%hash, $string);
                   3142:           }
                   3143:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3144:           ($key, $string)=&str2arrayref($string);
                   3145:           if($key->[0] eq 'Array reference error') {
                   3146:               $hash{'error'}='Bad data';
                   3147:               return (\%hash, $string);
                   3148:           }
                   3149:       } else {
                   3150:           $string =~ s/^(.*?)=//;
1.267     albertel 3151: 	  $key=&unescape($1);
1.265     albertel 3152:       }
                   3153:       $string =~ s/^=//;
                   3154: 
                   3155:       #value
                   3156:       my $value='';
                   3157:       if($string =~ /^__HASH_REF__/) {
                   3158:           ($value, $string)=&str2hashref($string);
                   3159:           if(defined($value->{'error'})) {
                   3160:               $hash{'error'}='Bad data';
                   3161:               return (\%hash, $string);
                   3162:           }
                   3163:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3164:           ($value, $string)=&str2arrayref($string);
                   3165:           if($value->[0] eq 'Array reference error') {
                   3166:               $hash{'error'}='Bad data';
                   3167:               return (\%hash, $string);
                   3168:           }
                   3169:       } else {
                   3170: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3171:       }
                   3172:       $string =~ s/^&//;
                   3173: 
                   3174:       $hash{$key}=$value;
1.204     albertel 3175:   }
1.265     albertel 3176: 
                   3177:   $string =~ s/^__END_HASH_REF__//;
                   3178: 
                   3179:   return (\%hash, $string);
1.204     albertel 3180: }
                   3181: 
                   3182: sub str2array {
1.265     albertel 3183:     my ($string)=@_;
                   3184:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3185:     return @$array;
                   3186: }
                   3187: 
                   3188: sub str2arrayref {
1.204     albertel 3189:   my ($string) = @_;
1.265     albertel 3190:   my @array;
                   3191: 
                   3192:   if($string !~ /^__ARRAY_REF__/) {
                   3193:       if (! ($string eq '' || !defined($string))) {
                   3194: 	  $array[0]='Array reference error';
                   3195:       }
                   3196:       return (\@array, $string);
                   3197:   }
                   3198: 
                   3199:   $string =~ s/^__ARRAY_REF__//;
                   3200: 
                   3201:   while($string !~ /^__END_ARRAY_REF__/) {
                   3202:       my $value='';
                   3203:       if($string =~ /^__HASH_REF__/) {
                   3204:           ($value, $string)=&str2hashref($string);
                   3205:           if(defined($value->{'error'})) {
                   3206:               $array[0] ='Array reference error';
                   3207:               return (\@array, $string);
                   3208:           }
                   3209:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3210:           ($value, $string)=&str2arrayref($string);
                   3211:           if($value->[0] eq 'Array reference error') {
                   3212:               $array[0] ='Array reference error';
                   3213:               return (\@array, $string);
                   3214:           }
                   3215:       } else {
                   3216: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3217:       }
                   3218:       $string =~ s/^&//;
                   3219: 
                   3220:       push(@array, $value);
1.191     harris41 3221:   }
1.265     albertel 3222: 
                   3223:   $string =~ s/^__END_ARRAY_REF__//;
                   3224: 
                   3225:   return (\@array, $string);
1.168     albertel 3226: }
                   3227: 
1.167     albertel 3228: # -------------------------------------------------------------------Temp Store
                   3229: 
1.168     albertel 3230: sub tmpreset {
                   3231:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3232:   if (!$symb) {
                   3233:     $symb=&symbread();
1.620     albertel 3234:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3235:   }
                   3236:   $symb=escape($symb);
                   3237: 
1.620     albertel 3238:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3239:   $namespace=~s/\//\_/g;
                   3240:   $namespace=~s/\W//g;
                   3241: 
1.620     albertel 3242:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3243:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3244:   if ($domain eq 'public' && $stuname eq 'public') {
                   3245:       $stuname=$ENV{'REMOTE_ADDR'};
                   3246:   }
1.168     albertel 3247:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3248:   my %hash;
                   3249:   if (tie(%hash,'GDBM_File',
                   3250: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3251: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3252:     foreach my $key (keys %hash) {
1.180     albertel 3253:       if ($key=~ /:$symb/) {
1.168     albertel 3254: 	delete($hash{$key});
                   3255:       }
                   3256:     }
                   3257:   }
                   3258: }
                   3259: 
1.167     albertel 3260: sub tmpstore {
1.168     albertel 3261:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3262: 
                   3263:   if (!$symb) {
                   3264:     $symb=&symbread();
1.620     albertel 3265:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3266:   }
                   3267:   $symb=escape($symb);
                   3268: 
                   3269:   if (!$namespace) {
                   3270:     # I don't think we would ever want to store this for a course.
                   3271:     # it seems this will only be used if we don't have a course.
1.620     albertel 3272:     #$namespace=$env{'request.course.id'};
1.168     albertel 3273:     #if (!$namespace) {
1.620     albertel 3274:       $namespace=$env{'request.state'};
1.168     albertel 3275:     #}
                   3276:   }
                   3277:   $namespace=~s/\//\_/g;
                   3278:   $namespace=~s/\W//g;
1.620     albertel 3279:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3280:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3281:   if ($domain eq 'public' && $stuname eq 'public') {
                   3282:       $stuname=$ENV{'REMOTE_ADDR'};
                   3283:   }
1.168     albertel 3284:   my $now=time;
                   3285:   my %hash;
                   3286:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3287:   if (tie(%hash,'GDBM_File',
                   3288: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3289: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3290:     $hash{"version:$symb"}++;
                   3291:     my $version=$hash{"version:$symb"};
                   3292:     my $allkeys=''; 
                   3293:     foreach my $key (keys(%$storehash)) {
                   3294:       $allkeys.=$key.':';
1.591     albertel 3295:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3296:     }
                   3297:     $hash{"$version:$symb:timestamp"}=$now;
                   3298:     $allkeys.='timestamp';
                   3299:     $hash{"$version:keys:$symb"}=$allkeys;
                   3300:     if (untie(%hash)) {
                   3301:       return 'ok';
                   3302:     } else {
                   3303:       return "error:$!";
                   3304:     }
                   3305:   } else {
                   3306:     return "error:$!";
                   3307:   }
                   3308: }
1.167     albertel 3309: 
1.168     albertel 3310: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3311: 
1.168     albertel 3312: sub tmprestore {
                   3313:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3314: 
1.168     albertel 3315:   if (!$symb) {
                   3316:     $symb=&symbread();
1.620     albertel 3317:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3318:   }
                   3319:   $symb=escape($symb);
                   3320: 
1.620     albertel 3321:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3322: 
1.620     albertel 3323:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3324:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3325:   if ($domain eq 'public' && $stuname eq 'public') {
                   3326:       $stuname=$ENV{'REMOTE_ADDR'};
                   3327:   }
1.168     albertel 3328:   my %returnhash;
                   3329:   $namespace=~s/\//\_/g;
                   3330:   $namespace=~s/\W//g;
                   3331:   my %hash;
                   3332:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3333:   if (tie(%hash,'GDBM_File',
                   3334: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3335: 	  &GDBM_READER(),0640)) {
1.168     albertel 3336:     my $version=$hash{"version:$symb"};
                   3337:     $returnhash{'version'}=$version;
                   3338:     my $scope;
                   3339:     for ($scope=1;$scope<=$version;$scope++) {
                   3340:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3341:       my @keys=split(/:/,$vkeys);
                   3342:       my $key;
                   3343:       $returnhash{"$scope:keys"}=$vkeys;
                   3344:       foreach $key (@keys) {
1.591     albertel 3345: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3346: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3347:       }
                   3348:     }
1.168     albertel 3349:     if (!(untie(%hash))) {
                   3350:       return "error:$!";
                   3351:     }
                   3352:   } else {
                   3353:     return "error:$!";
                   3354:   }
                   3355:   return %returnhash;
1.167     albertel 3356: }
                   3357: 
1.9       www      3358: # ----------------------------------------------------------------------- Store
                   3359: 
                   3360: sub store {
1.124     www      3361:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3362:     my $home='';
                   3363: 
1.168     albertel 3364:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3365: 
1.213     www      3366:     $symb=&symbclean($symb);
1.122     albertel 3367:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3368: 
1.620     albertel 3369:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3370:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3371: 
                   3372:     &devalidate($symb,$stuname,$domain);
1.109     www      3373: 
                   3374:     $symb=escape($symb);
1.187     www      3375:     if (!$namespace) { 
1.620     albertel 3376:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3377:           return ''; 
                   3378:        } 
                   3379:     }
1.620     albertel 3380:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3381: 
                   3382:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3383:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3384: 
1.12      www      3385:     my $namevalue='';
1.800     albertel 3386:     foreach my $key (keys(%$storehash)) {
                   3387:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3388:     }
1.12      www      3389:     $namevalue=~s/\&$//;
1.187     www      3390:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3391:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3392: }
                   3393: 
1.47      www      3394: # -------------------------------------------------------------- Critical Store
                   3395: 
                   3396: sub cstore {
1.124     www      3397:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3398:     my $home='';
                   3399: 
1.168     albertel 3400:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3401: 
1.213     www      3402:     $symb=&symbclean($symb);
1.122     albertel 3403:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3404: 
1.620     albertel 3405:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3406:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3407: 
                   3408:     &devalidate($symb,$stuname,$domain);
1.109     www      3409: 
                   3410:     $symb=escape($symb);
1.187     www      3411:     if (!$namespace) { 
1.620     albertel 3412:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3413:           return ''; 
                   3414:        } 
                   3415:     }
1.620     albertel 3416:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3417: 
                   3418:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3419:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3420: 
1.47      www      3421:     my $namevalue='';
1.800     albertel 3422:     foreach my $key (keys(%$storehash)) {
                   3423:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3424:     }
1.47      www      3425:     $namevalue=~s/\&$//;
1.187     www      3426:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3427:     return critical
                   3428:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3429: }
                   3430: 
1.9       www      3431: # --------------------------------------------------------------------- Restore
                   3432: 
                   3433: sub restore {
1.124     www      3434:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3435:     my $home='';
                   3436: 
1.168     albertel 3437:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3438: 
1.122     albertel 3439:     if (!$symb) {
                   3440:       unless ($symb=escape(&symbread())) { return ''; }
                   3441:     } else {
1.213     www      3442:       $symb=&escape(&symbclean($symb));
1.122     albertel 3443:     }
1.188     www      3444:     if (!$namespace) { 
1.620     albertel 3445:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3446:           return ''; 
                   3447:        } 
                   3448:     }
1.620     albertel 3449:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3450:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3451:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3452:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3453: 
1.12      www      3454:     my %returnhash=();
1.800     albertel 3455:     foreach my $line (split(/\&/,$answer)) {
                   3456: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3457:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3458:     }
1.75      www      3459:     my $version;
                   3460:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3461:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3462:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3463:        }
1.75      www      3464:     }
1.13      www      3465:     return %returnhash;
1.34      www      3466: }
                   3467: 
                   3468: # ---------------------------------------------------------- Course Description
                   3469: 
                   3470: sub coursedescription {
1.731     albertel 3471:     my ($courseid,$args)=@_;
1.34      www      3472:     $courseid=~s/^\///;
1.49      www      3473:     $courseid=~s/\_/\//g;
1.34      www      3474:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3475:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3476:     my $normalid=$cdomain.'_'.$cnum;
                   3477:     # need to always cache even if we get errors otherwise we keep 
                   3478:     # trying and trying and trying to get the course description.
                   3479:     my %envhash=();
                   3480:     my %returnhash=();
1.731     albertel 3481:     
                   3482:     my $expiretime=600;
                   3483:     if ($env{'request.course.id'} eq $normalid) {
                   3484: 	$expiretime=120;
                   3485:     }
                   3486: 
                   3487:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3488:     if (!$args->{'freshen_cache'}
                   3489: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3490: 	foreach my $key (keys(%env)) {
                   3491: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3492: 	    my ($setting) = $1;
                   3493: 	    $returnhash{$setting} = $env{$key};
                   3494: 	}
                   3495: 	return %returnhash;
                   3496:     }
                   3497: 
                   3498:     # get the data agin
                   3499:     if (!$args->{'one_time'}) {
                   3500: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3501:     }
1.811     albertel 3502: 
1.34      www      3503:     if ($chome ne 'no_host') {
1.302     albertel 3504:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3505:        if (!exists($returnhash{'con_lost'})) {
                   3506:            $returnhash{'home'}= $chome;
                   3507: 	   $returnhash{'domain'} = $cdomain;
                   3508: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3509:            if (!defined($returnhash{'type'})) {
                   3510:                $returnhash{'type'} = 'Course';
                   3511:            }
1.130     albertel 3512:            while (my ($name,$value) = each %returnhash) {
1.53      www      3513:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3514:            }
1.270     www      3515:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3516:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3517: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3518:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3519:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3520:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3521:        }
                   3522:     }
1.731     albertel 3523:     if (!$args->{'one_time'}) {
1.949     raeburn  3524: 	&appenv(\%envhash);
1.731     albertel 3525:     }
1.302     albertel 3526:     return %returnhash;
1.461     www      3527: }
                   3528: 
                   3529: # -------------------------------------------------See if a user is privileged
                   3530: 
                   3531: sub privileged {
                   3532:     my ($username,$domain)=@_;
                   3533:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3534: 			&homeserver($username,$domain));
                   3535:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3536:     my $now=time;
                   3537:     if ($rolesdump ne '') {
1.800     albertel 3538:         foreach my $entry (split(/&/,$rolesdump)) {
                   3539: 	    if ($entry!~/^rolesdef_/) {
                   3540: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3541: 		$area=~s/\_\w\w$//;
                   3542: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3543: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3544: 		    my $active=1;
                   3545: 		    if ($tend) {
                   3546: 			if ($tend<$now) { $active=0; }
                   3547: 		    }
                   3548: 		    if ($tstart) {
                   3549: 			if ($tstart>$now) { $active=0; }
                   3550: 		    }
                   3551: 		    if ($active) { return 1; }
                   3552: 		}
                   3553: 	    }
                   3554: 	}
                   3555:     }
                   3556:     return 0;
1.9       www      3557: }
1.1       albertel 3558: 
1.103     harris41 3559: # -------------------------------------------------------- Get user privileges
1.11      www      3560: 
                   3561: sub rolesinit {
                   3562:     my ($domain,$username,$authhost)=@_;
                   3563:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3564:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3565:     my %allroles=();
1.678     raeburn  3566:     my %allgroups=();   
1.11      www      3567:     my $now=time;
1.743     albertel 3568:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3569:     my $group_privs;
1.11      www      3570: 
                   3571:     if ($rolesdump ne '') {
1.800     albertel 3572:         foreach my $entry (split(/&/,$rolesdump)) {
                   3573: 	  if ($entry!~/^rolesdef_/) {
                   3574:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3575: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3576:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3577: 	    if ($role=~/^cr/) { 
1.807     albertel 3578: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3579: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3580: 		    ($tend,$tstart)=split('_',$trest);
                   3581: 		} else {
                   3582: 		    $trole=$role;
                   3583: 		}
1.678     raeburn  3584:             } elsif ($role =~ m|^gr/|) {
                   3585:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3586:                 ($trole,$group_privs) = split(/\//,$trole);
                   3587:                 $group_privs = &unescape($group_privs);
1.587     albertel 3588: 	    } else {
                   3589: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3590: 	    }
1.743     albertel 3591: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3592: 					 $username);
                   3593: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3594:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3595:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3596:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3597: 		my $spec=$trole.'.'.$area;
                   3598: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3599: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3600:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3601:                 } elsif ($trole eq 'gr') {
                   3602:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3603: 		} else {
1.567     raeburn  3604:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3605: 		}
1.12      www      3606:             }
1.662     raeburn  3607:           }
1.191     harris41 3608:         }
1.743     albertel 3609:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3610:         $userroles{'user.adv'}    = $adv;
                   3611: 	$userroles{'user.author'} = $author;
1.620     albertel 3612:         $env{'user.adv'}=$adv;
1.11      www      3613:     }
1.743     albertel 3614:     return \%userroles;  
1.11      www      3615: }
                   3616: 
1.567     raeburn  3617: sub set_arearole {
                   3618:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3619: # log the associated role with the area
                   3620:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3621:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3622: }
                   3623: 
                   3624: sub custom_roleprivs {
                   3625:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3626:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3627:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3628:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3629:         my ($rdummy,$roledef)=
                   3630:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3631:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3632:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3633:             if (defined($syspriv)) {
                   3634:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3635:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3636:             }
                   3637:             if ($tdomain ne '') {
                   3638:                 if (defined($dompriv)) {
                   3639:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3640:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3641:                 }
                   3642:                 if (($trest ne '') && (defined($coursepriv))) {
                   3643:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3644:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3645:                 }
                   3646:             }
                   3647:         }
                   3648:     }
                   3649: }
                   3650: 
1.678     raeburn  3651: sub group_roleprivs {
                   3652:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3653:     my $access = 1;
                   3654:     my $now = time;
                   3655:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3656:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3657:     if ($access) {
1.811     albertel 3658:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3659:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3660:     }
                   3661: }
1.567     raeburn  3662: 
                   3663: sub standard_roleprivs {
                   3664:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3665:     if (defined($pr{$trole.':s'})) {
                   3666:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3667:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3668:     }
                   3669:     if ($tdomain ne '') {
                   3670:         if (defined($pr{$trole.':d'})) {
                   3671:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3672:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3673:         }
                   3674:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3675:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3676:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3677:         }
                   3678:     }
                   3679: }
                   3680: 
                   3681: sub set_userprivs {
1.678     raeburn  3682:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3683:     my $author=0;
                   3684:     my $adv=0;
1.678     raeburn  3685:     my %grouproles = ();
                   3686:     if (keys(%{$allgroups}) > 0) {
                   3687:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3688:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3689:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3690:                 $trole = $1;
                   3691:                 $area = $2;
1.681     raeburn  3692:                 $sec = $3;
                   3693:                 $extendedarea = $area.$sec;
                   3694:                 if (exists($$allgroups{$area})) {
                   3695:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3696:                         my $spec = $trole.'.'.$extendedarea;
                   3697:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3698:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3699:                     }
                   3700:                 }
                   3701:             }
                   3702:         }
                   3703:     }
1.800     albertel 3704:     foreach my $group (keys(%grouproles)) {
                   3705:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3706:     }
1.800     albertel 3707:     foreach my $role (keys(%{$allroles})) {
                   3708:         my %thesepriv;
1.941     raeburn  3709:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3710:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3711:             if ($item ne '') {
                   3712:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3713:                 if ($restrictions eq '') {
                   3714:                     $thesepriv{$privilege}='F';
                   3715:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3716:                     $thesepriv{$privilege}.=$restrictions;
                   3717:                 }
                   3718:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3719:             }
                   3720:         }
                   3721:         my $thesestr='';
1.800     albertel 3722:         foreach my $priv (keys(%thesepriv)) {
                   3723: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3724: 	}
                   3725:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3726:     }
                   3727:     return ($author,$adv);
                   3728: }
                   3729: 
1.12      www      3730: # --------------------------------------------------------------- get interface
                   3731: 
                   3732: sub get {
1.131     albertel 3733:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3734:    my $items='';
1.800     albertel 3735:    foreach my $item (@$storearr) {
                   3736:        $items.=&escape($item).'&';
1.191     harris41 3737:    }
1.12      www      3738:    $items=~s/\&$//;
1.620     albertel 3739:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3740:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3741:    my $uhome=&homeserver($uname,$udomain);
                   3742: 
1.133     albertel 3743:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3744:    my @pairs=split(/\&/,$rep);
1.273     albertel 3745:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3746:      return @pairs;
                   3747:    }
1.15      www      3748:    my %returnhash=();
1.42      www      3749:    my $i=0;
1.800     albertel 3750:    foreach my $item (@$storearr) {
                   3751:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3752:       $i++;
1.191     harris41 3753:    }
1.15      www      3754:    return %returnhash;
1.27      www      3755: }
                   3756: 
                   3757: # --------------------------------------------------------------- del interface
                   3758: 
                   3759: sub del {
1.133     albertel 3760:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3761:    my $items='';
1.800     albertel 3762:    foreach my $item (@$storearr) {
                   3763:        $items.=&escape($item).'&';
1.191     harris41 3764:    }
1.27      www      3765:    $items=~s/\&$//;
1.620     albertel 3766:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3767:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3768:    my $uhome=&homeserver($uname,$udomain);
                   3769: 
                   3770:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3771: }
                   3772: 
                   3773: # -------------------------------------------------------------- dump interface
                   3774: 
                   3775: sub dump {
1.755     albertel 3776:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3777:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3778:     if (!$uname) { $uname=$env{'user.name'}; }
                   3779:     my $uhome=&homeserver($uname,$udomain);
                   3780:     if ($regexp) {
                   3781: 	$regexp=&escape($regexp);
                   3782:     } else {
                   3783: 	$regexp='.';
                   3784:     }
                   3785:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3786:     my @pairs=split(/\&/,$rep);
                   3787:     my %returnhash=();
                   3788:     foreach my $item (@pairs) {
                   3789: 	my ($key,$value)=split(/=/,$item,2);
                   3790: 	$key = &unescape($key);
                   3791: 	next if ($key =~ /^error: 2 /);
                   3792: 	$returnhash{$key}=&thaw_unescape($value);
                   3793:     }
                   3794:     return %returnhash;
1.407     www      3795: }
                   3796: 
1.717     albertel 3797: # --------------------------------------------------------- dumpstore interface
                   3798: 
                   3799: sub dumpstore {
                   3800:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3801:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3802:    if (!$uname) { $uname=$env{'user.name'}; }
                   3803:    my $uhome=&homeserver($uname,$udomain);
                   3804:    if ($regexp) {
                   3805:        $regexp=&escape($regexp);
                   3806:    } else {
                   3807:        $regexp='.';
                   3808:    }
                   3809:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3810:    my @pairs=split(/\&/,$rep);
                   3811:    my %returnhash=();
                   3812:    foreach my $item (@pairs) {
                   3813:        my ($key,$value)=split(/=/,$item,2);
                   3814:        next if ($key =~ /^error: 2 /);
                   3815:        $returnhash{$key}=&thaw_unescape($value);
                   3816:    }
                   3817:    return %returnhash;
1.717     albertel 3818: }
                   3819: 
1.407     www      3820: # -------------------------------------------------------------- keys interface
                   3821: 
                   3822: sub getkeys {
                   3823:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3824:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3825:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3826:    my $uhome=&homeserver($uname,$udomain);
                   3827:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3828:    my @keyarray=();
1.800     albertel 3829:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3830:       next if ($key =~ /^error: 2 /);
1.800     albertel 3831:       push(@keyarray,&unescape($key));
1.407     www      3832:    }
                   3833:    return @keyarray;
1.318     matthew  3834: }
                   3835: 
1.319     matthew  3836: # --------------------------------------------------------------- currentdump
                   3837: sub currentdump {
1.328     matthew  3838:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3839:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3840:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3841:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3842:    my $uhome = &homeserver($sname,$sdom);
                   3843:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3844:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3845:    #
1.318     matthew  3846:    my %returnhash=();
1.319     matthew  3847:    #
                   3848:    if ($rep eq "unknown_cmd") { 
                   3849:        # an old lond will not know currentdump
                   3850:        # Do a dump and make it look like a currentdump
1.822     albertel 3851:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3852:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3853:        my %hash = @tmp;
                   3854:        @tmp=();
1.424     matthew  3855:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3856:    } else {
                   3857:        my @pairs=split(/\&/,$rep);
1.800     albertel 3858:        foreach my $pair (@pairs) {
                   3859:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3860:            my ($symb,$param) = split(/:/,$key);
                   3861:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3862:                                                         &thaw_unescape($value);
1.319     matthew  3863:        }
1.191     harris41 3864:    }
1.12      www      3865:    return %returnhash;
1.424     matthew  3866: }
                   3867: 
                   3868: sub convert_dump_to_currentdump{
                   3869:     my %hash = %{shift()};
                   3870:     my %returnhash;
                   3871:     # Code ripped from lond, essentially.  The only difference
                   3872:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3873:     # we might run in to problems with parameter names =~ /^v\./
                   3874:     while (my ($key,$value) = each(%hash)) {
                   3875:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3876: 	$symb  = &unescape($symb);
                   3877: 	$param = &unescape($param);
1.424     matthew  3878:         next if ($v eq 'version' || $symb eq 'keys');
                   3879:         next if (exists($returnhash{$symb}) &&
                   3880:                  exists($returnhash{$symb}->{$param}) &&
                   3881:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3882:         $returnhash{$symb}->{$param}=$value;
                   3883:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3884:     }
                   3885:     #
                   3886:     # Remove all of the keys in the hashes which keep track of
                   3887:     # the version of the parameter.
                   3888:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3889:         # use a foreach because we are going to delete from the hash.
                   3890:         foreach my $key (keys(%$param_hash)) {
                   3891:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3892:         }
                   3893:     }
                   3894:     return \%returnhash;
1.12      www      3895: }
                   3896: 
1.627     albertel 3897: # ------------------------------------------------------ critical inc interface
                   3898: 
                   3899: sub cinc {
                   3900:     return &inc(@_,'critical');
                   3901: }
                   3902: 
1.449     matthew  3903: # --------------------------------------------------------------- inc interface
                   3904: 
                   3905: sub inc {
1.627     albertel 3906:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3907:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3908:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3909:     my $uhome=&homeserver($uname,$udomain);
                   3910:     my $items='';
                   3911:     if (! ref($store)) {
                   3912:         # got a single value, so use that instead
                   3913:         $items = &escape($store).'=&';
                   3914:     } elsif (ref($store) eq 'SCALAR') {
                   3915:         $items = &escape($$store).'=&';        
                   3916:     } elsif (ref($store) eq 'ARRAY') {
                   3917:         $items = join('=&',map {&escape($_);} @{$store});
                   3918:     } elsif (ref($store) eq 'HASH') {
                   3919:         while (my($key,$value) = each(%{$store})) {
                   3920:             $items.= &escape($key).'='.&escape($value).'&';
                   3921:         }
                   3922:     }
                   3923:     $items=~s/\&$//;
1.627     albertel 3924:     if ($critical) {
                   3925: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3926:     } else {
                   3927: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3928:     }
1.449     matthew  3929: }
                   3930: 
1.12      www      3931: # --------------------------------------------------------------- put interface
                   3932: 
                   3933: sub put {
1.134     albertel 3934:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3935:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3936:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3937:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3938:    my $items='';
1.800     albertel 3939:    foreach my $item (keys(%$storehash)) {
                   3940:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3941:    }
1.12      www      3942:    $items=~s/\&$//;
1.134     albertel 3943:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3944: }
                   3945: 
1.631     albertel 3946: # ------------------------------------------------------------ newput interface
                   3947: 
                   3948: sub newput {
                   3949:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3950:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3951:    if (!$uname) { $uname=$env{'user.name'}; }
                   3952:    my $uhome=&homeserver($uname,$udomain);
                   3953:    my $items='';
                   3954:    foreach my $key (keys(%$storehash)) {
                   3955:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3956:    }
                   3957:    $items=~s/\&$//;
                   3958:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3959: }
                   3960: 
                   3961: # ---------------------------------------------------------  putstore interface
                   3962: 
1.524     raeburn  3963: sub putstore {
1.715     albertel 3964:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3965:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3966:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3967:    my $uhome=&homeserver($uname,$udomain);
                   3968:    my $items='';
1.715     albertel 3969:    foreach my $key (keys(%$storehash)) {
                   3970:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3971:    }
1.715     albertel 3972:    $items=~s/\&$//;
1.716     albertel 3973:    my $esc_symb=&escape($symb);
                   3974:    my $esc_v=&escape($version);
1.715     albertel 3975:    my $reply =
1.716     albertel 3976:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3977: 	      $uhome);
                   3978:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3979:        # gfall back to way things use to be done
1.715     albertel 3980:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3981: 			    $uname);
1.524     raeburn  3982:    }
1.715     albertel 3983:    return $reply;
                   3984: }
                   3985: 
                   3986: sub old_putstore {
1.716     albertel 3987:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3988:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3989:     if (!$uname) { $uname=$env{'user.name'}; }
                   3990:     my $uhome=&homeserver($uname,$udomain);
                   3991:     my %newstorehash;
1.800     albertel 3992:     foreach my $item (keys(%$storehash)) {
                   3993: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3994: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3995:     }
                   3996:     my $items='';
                   3997:     my %allitems = ();
1.800     albertel 3998:     foreach my $item (keys(%newstorehash)) {
                   3999: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4000: 	    my $key = $1.':keys:'.$2;
                   4001: 	    $allitems{$key} .= $3.':';
                   4002: 	}
1.800     albertel 4003: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4004:     }
1.800     albertel 4005:     foreach my $item (keys(%allitems)) {
                   4006: 	$allitems{$item} =~ s/\:$//;
                   4007: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4008:     }
                   4009:     $items=~s/\&$//;
                   4010:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4011: }
                   4012: 
1.47      www      4013: # ------------------------------------------------------ critical put interface
                   4014: 
                   4015: sub cput {
1.134     albertel 4016:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4017:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4018:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4019:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4020:    my $items='';
1.800     albertel 4021:    foreach my $item (keys(%$storehash)) {
                   4022:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4023:    }
1.47      www      4024:    $items=~s/\&$//;
1.134     albertel 4025:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4026: }
                   4027: 
                   4028: # -------------------------------------------------------------- eget interface
                   4029: 
                   4030: sub eget {
1.133     albertel 4031:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4032:    my $items='';
1.800     albertel 4033:    foreach my $item (@$storearr) {
                   4034:        $items.=&escape($item).'&';
1.191     harris41 4035:    }
1.12      www      4036:    $items=~s/\&$//;
1.620     albertel 4037:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4038:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4039:    my $uhome=&homeserver($uname,$udomain);
                   4040:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4041:    my @pairs=split(/\&/,$rep);
                   4042:    my %returnhash=();
1.42      www      4043:    my $i=0;
1.800     albertel 4044:    foreach my $item (@$storearr) {
                   4045:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4046:       $i++;
1.191     harris41 4047:    }
1.12      www      4048:    return %returnhash;
                   4049: }
                   4050: 
1.667     albertel 4051: # ------------------------------------------------------------ tmpput interface
                   4052: sub tmpput {
1.802     raeburn  4053:     my ($storehash,$server,$context)=@_;
1.667     albertel 4054:     my $items='';
1.800     albertel 4055:     foreach my $item (keys(%$storehash)) {
                   4056: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4057:     }
                   4058:     $items=~s/\&$//;
1.802     raeburn  4059:     if (defined($context)) {
                   4060:         $items .= ':'.&escape($context);
                   4061:     }
1.667     albertel 4062:     return &reply("tmpput:$items",$server);
                   4063: }
                   4064: 
                   4065: # ------------------------------------------------------------ tmpget interface
                   4066: sub tmpget {
1.688     albertel 4067:     my ($token,$server)=@_;
                   4068:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4069:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4070:     my %returnhash;
                   4071:     foreach my $item (split(/\&/,$rep)) {
                   4072: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4073:         next if ($key =~ /^error: 2 /);
1.667     albertel 4074: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4075:     }
                   4076:     return %returnhash;
                   4077: }
                   4078: 
1.688     albertel 4079: # ------------------------------------------------------------ tmpget interface
                   4080: sub tmpdel {
                   4081:     my ($token,$server)=@_;
                   4082:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4083:     return &reply("tmpdel:$token",$server);
                   4084: }
                   4085: 
1.765     albertel 4086: # -------------------------------------------------- portfolio access checking
                   4087: 
                   4088: sub portfolio_access {
1.766     albertel 4089:     my ($requrl) = @_;
1.765     albertel 4090:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4091:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4092:     if ($result) {
                   4093:         my %setters;
                   4094:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4095:             my ($startblock,$endblock) =
                   4096:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4097:             if ($startblock && $endblock) {
                   4098:                 return 'B';
                   4099:             }
                   4100:         } else {
                   4101:             my ($startblock,$endblock) =
                   4102:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4103:             if ($startblock && $endblock) {
                   4104:                 return 'B';
                   4105:             }
                   4106:         }
                   4107:     }
1.765     albertel 4108:     if ($result eq 'ok') {
1.766     albertel 4109:        return 'F';
1.765     albertel 4110:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4111:        return 'A';
1.765     albertel 4112:     }
1.766     albertel 4113:     return '';
1.765     albertel 4114: }
                   4115: 
                   4116: sub get_portfolio_access {
1.767     albertel 4117:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4118: 
                   4119:     if (!ref($access_hash)) {
                   4120: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4121: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4122: 						   $file_name);
                   4123: 	$access_hash = $access_controls{$file_name};
                   4124:     }
                   4125: 
1.765     albertel 4126:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4127:     my $now = time;
                   4128:     if (ref($access_hash) eq 'HASH') {
                   4129:         foreach my $key (keys(%{$access_hash})) {
                   4130:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4131:             if ($start > $now) {
                   4132:                 next;
                   4133:             }
                   4134:             if ($end && $end<$now) {
                   4135:                 next;
                   4136:             }
                   4137:             if ($scope eq 'public') {
                   4138:                 $public = $key;
                   4139:                 last;
                   4140:             } elsif ($scope eq 'guest') {
                   4141:                 $guest = $key;
                   4142:             } elsif ($scope eq 'domains') {
                   4143:                 push(@domains,$key);
                   4144:             } elsif ($scope eq 'users') {
                   4145:                 push(@users,$key);
                   4146:             } elsif ($scope eq 'course') {
                   4147:                 push(@courses,$key);
                   4148:             } elsif ($scope eq 'group') {
                   4149:                 push(@groups,$key);
                   4150:             }
                   4151:         }
                   4152:         if ($public) {
                   4153:             return 'ok';
                   4154:         }
                   4155:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4156:             if ($guest) {
                   4157:                 return $guest;
                   4158:             }
                   4159:         } else {
                   4160:             if (@domains > 0) {
                   4161:                 foreach my $domkey (@domains) {
                   4162:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4163:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4164:                             return 'ok';
                   4165:                         }
                   4166:                     }
                   4167:                 }
                   4168:             }
                   4169:             if (@users > 0) {
                   4170:                 foreach my $userkey (@users) {
1.865     raeburn  4171:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4172:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4173:                             if (ref($item) eq 'HASH') {
                   4174:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4175:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4176:                                     return 'ok';
                   4177:                                 }
                   4178:                             }
                   4179:                         }
                   4180:                     } 
1.765     albertel 4181:                 }
                   4182:             }
                   4183:             my %roleshash;
                   4184:             my @courses_and_groups = @courses;
                   4185:             push(@courses_and_groups,@groups); 
                   4186:             if (@courses_and_groups > 0) {
                   4187:                 my (%allgroups,%allroles); 
                   4188:                 my ($start,$end,$role,$sec,$group);
                   4189:                 foreach my $envkey (%env) {
1.811     albertel 4190:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4191:                         my $cid = $2.'_'.$3; 
                   4192:                         if ($1 eq 'gr') {
                   4193:                             $group = $4;
                   4194:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4195:                         } else {
                   4196:                             if ($4 eq '') {
                   4197:                                 $sec = 'none';
                   4198:                             } else {
                   4199:                                 $sec = $4;
                   4200:                             }
                   4201:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4202:                         }
1.811     albertel 4203:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4204:                         my $cid = $2.'_'.$3;
                   4205:                         if ($4 eq '') {
                   4206:                             $sec = 'none';
                   4207:                         } else {
                   4208:                             $sec = $4;
                   4209:                         }
                   4210:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4211:                     }
                   4212:                 }
                   4213:                 if (keys(%allroles) == 0) {
                   4214:                     return;
                   4215:                 }
                   4216:                 foreach my $key (@courses_and_groups) {
                   4217:                     my %content = %{$$access_hash{$key}};
                   4218:                     my $cnum = $content{'number'};
                   4219:                     my $cdom = $content{'domain'};
                   4220:                     my $cid = $cdom.'_'.$cnum;
                   4221:                     if (!exists($allroles{$cid})) {
                   4222:                         next;
                   4223:                     }    
                   4224:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4225:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4226:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4227:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4228:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4229:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4230:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4231:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4232:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4233:                                         if (grep/^all$/,@sections) {
                   4234:                                             return 'ok';
                   4235:                                         } else {
                   4236:                                             if (grep/^$sec$/,@sections) {
                   4237:                                                 return 'ok';
                   4238:                                             }
                   4239:                                         }
                   4240:                                     }
                   4241:                                 }
                   4242:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4243:                                     if (grep/^none$/,@groups) {
                   4244:                                         return 'ok';
                   4245:                                     }
                   4246:                                 } else {
                   4247:                                     if (grep/^all$/,@groups) {
                   4248:                                         return 'ok';
                   4249:                                     } 
                   4250:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4251:                                         if (grep/^$group$/,@groups) {
                   4252:                                             return 'ok';
                   4253:                                         }
                   4254:                                     }
                   4255:                                 } 
                   4256:                             }
                   4257:                         }
                   4258:                     }
                   4259:                 }
                   4260:             }
                   4261:             if ($guest) {
                   4262:                 return $guest;
                   4263:             }
                   4264:         }
                   4265:     }
                   4266:     return;
                   4267: }
                   4268: 
                   4269: sub course_group_datechecker {
                   4270:     my ($dates,$now,$status) = @_;
                   4271:     my ($start,$end) = split(/\./,$dates);
                   4272:     if (!$start && !$end) {
                   4273:         return 'ok';
                   4274:     }
                   4275:     if (grep/^active$/,@{$status}) {
                   4276:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4277:             return 'ok';
                   4278:         }
                   4279:     }
                   4280:     if (grep/^previous$/,@{$status}) {
                   4281:         if ($end > $now ) {
                   4282:             return 'ok';
                   4283:         }
                   4284:     }
                   4285:     if (grep/^future$/,@{$status}) {
                   4286:         if ($start > $now) {
                   4287:             return 'ok';
                   4288:         }
                   4289:     }
                   4290:     return; 
                   4291: }
                   4292: 
                   4293: sub parse_portfolio_url {
                   4294:     my ($url) = @_;
                   4295: 
                   4296:     my ($type,$udom,$unum,$group,$file_name);
                   4297:     
1.823     albertel 4298:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4299: 	$type = 1;
                   4300:         $udom = $1;
                   4301:         $unum = $2;
                   4302:         $file_name = $3;
1.823     albertel 4303:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4304: 	$type = 2;
                   4305:         $udom = $1;
                   4306:         $unum = $2;
                   4307:         $group = $3;
                   4308:         $file_name = $3.'/'.$4;
                   4309:     }
                   4310:     if (wantarray) {
                   4311: 	return ($type,$udom,$unum,$file_name,$group);
                   4312:     }
                   4313:     return $type;
                   4314: }
                   4315: 
                   4316: sub is_portfolio_url {
                   4317:     my ($url) = @_;
                   4318:     return scalar(&parse_portfolio_url($url));
                   4319: }
                   4320: 
1.798     raeburn  4321: sub is_portfolio_file {
                   4322:     my ($file) = @_;
1.820     raeburn  4323:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4324:         return 1;
                   4325:     }
                   4326:     return;
                   4327: }
                   4328: 
                   4329: 
1.341     www      4330: # ---------------------------------------------- Custom access rule evaluation
                   4331: 
                   4332: sub customaccess {
                   4333:     my ($priv,$uri)=@_;
1.807     albertel 4334:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4335:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4336:     $udom = &LONCAPA::clean_domain($udom);
                   4337:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4338:     my $access=0;
1.800     albertel 4339:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4340: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4341: 	if ($type eq 'user') {
                   4342: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4343: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4344: 		if ($tdom) {
                   4345: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4346: 		}
1.896     albertel 4347: 		if ($tuname) {
                   4348: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4349: 		}
                   4350: 		$access=($effect eq 'allow');
                   4351: 		last;
                   4352: 	    }
                   4353: 	} else {
                   4354: 	    if ($role) {
                   4355: 		if ($role ne $urole) { next; }
                   4356: 	    }
                   4357: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4358: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4359: 		if ($tdom) {
                   4360: 		    if ($tdom ne $udom) { next; }
                   4361: 		}
                   4362: 		if ($tcrs) {
                   4363: 		    if ($tcrs ne $ucrs) { next; }
                   4364: 		}
                   4365: 		if ($tsec) {
                   4366: 		    if ($tsec ne $usec) { next; }
                   4367: 		}
                   4368: 		$access=($effect eq 'allow');
                   4369: 		last;
                   4370: 	    }
                   4371: 	    if ($realm eq '' && $role eq '') {
                   4372: 		$access=($effect eq 'allow');
                   4373: 	    }
1.402     bowersj2 4374: 	}
1.341     www      4375:     }
                   4376:     return $access;
                   4377: }
                   4378: 
1.103     harris41 4379: # ------------------------------------------------- Check for a user privilege
1.12      www      4380: 
                   4381: sub allowed {
1.810     raeburn  4382:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4383:     my $ver_orguri=$uri;
1.439     www      4384:     $uri=&deversion($uri);
1.152     www      4385:     my $orguri=$uri;
1.52      www      4386:     $uri=&declutter($uri);
1.809     raeburn  4387: 
1.810     raeburn  4388:     if ($priv eq 'evb') {
                   4389: # Evade communication block restrictions for specified role in a course
                   4390:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4391:             return $1;
                   4392:         } else {
                   4393:             return;
                   4394:         }
                   4395:     }
                   4396: 
1.620     albertel 4397:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4398: # Free bre access to adm and meta resources
1.775     albertel 4399:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4400: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4401: 	&& ($priv eq 'bre')) {
1.14      www      4402: 	return 'F';
1.159     www      4403:     }
                   4404: 
1.545     banghart 4405: # Free bre access to user's own portfolio contents
1.714     raeburn  4406:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4407:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4408: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4409:         my %setters;
                   4410:         my ($startblock,$endblock) = 
                   4411:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4412:         if ($startblock && $endblock) {
                   4413:             return 'B';
                   4414:         } else {
                   4415:             return 'F';
                   4416:         }
1.545     banghart 4417:     }
                   4418: 
1.762     raeburn  4419: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4420:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4421:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4422:         if (exists($env{'request.course.id'})) {
                   4423:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4424:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4425:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4426:                 my $courseprivid=$env{'request.course.id'};
                   4427:                 $courseprivid=~s/\_/\//;
                   4428:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4429:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4430:                     return $1; 
1.762     raeburn  4431:                 } else {
                   4432:                     if ($env{'request.course.sec'}) {
                   4433:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4434:                     }
                   4435:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4436:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4437:                         return $2;
                   4438:                     }
1.714     raeburn  4439:                 }
                   4440:             }
                   4441:         }
                   4442:     }
                   4443: 
1.159     www      4444: # Free bre to public access
                   4445: 
                   4446:     if ($priv eq 'bre') {
1.238     www      4447:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4448: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4449:            return 'F'; 
                   4450:         }
1.238     www      4451:         if ($copyright eq 'priv') {
                   4452:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4453: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4454: 		return '';
                   4455:             }
                   4456:         }
                   4457:         if ($copyright eq 'domain') {
                   4458:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4459: 	    unless (($env{'user.domain'} eq $1) ||
                   4460:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4461: 		return '';
                   4462:             }
1.262     matthew  4463:         }
1.620     albertel 4464:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4465:             # Library role, so allow browsing of resources in this domain.
                   4466:             return 'F';
1.238     www      4467:         }
1.341     www      4468:         if ($copyright eq 'custom') {
                   4469: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4470:         }
1.14      www      4471:     }
1.264     matthew  4472:     # Domain coordinator is trying to create a course
1.620     albertel 4473:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4474:         # uri is the requested domain in this case.
                   4475:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4476:         # a role of dc for the domain in question.
1.620     albertel 4477:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4478:     }
1.29      www      4479: 
1.52      www      4480:     my $thisallowed='';
                   4481:     my $statecond=0;
                   4482:     my $courseprivid='';
                   4483: 
                   4484: # Course
                   4485: 
1.620     albertel 4486:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4487:        $thisallowed.=$1;
                   4488:     }
1.29      www      4489: 
1.52      www      4490: # Domain
                   4491: 
1.620     albertel 4492:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4493:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4494:        $thisallowed.=$1;
                   4495:     }
1.52      www      4496: 
                   4497: # Course: uri itself is a course
1.66      www      4498:     my $courseuri=$uri;
                   4499:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4500:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4501: 
1.620     albertel 4502:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4503:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4504:        $thisallowed.=$1;
                   4505:     }
1.29      www      4506: 
1.665     albertel 4507: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4508: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4509:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4510: 	$thisallowed='';
1.671     raeburn  4511:         my ($match)=&is_on_map($uri);
                   4512:         if ($match) {
                   4513:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4514:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4515:                 $thisallowed.=$1;
                   4516:             }
                   4517:         } else {
1.705     albertel 4518:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4519:             if ($refuri) {
                   4520:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4521:                     $thisallowed='F';
1.671     raeburn  4522:                 } else {
                   4523:                     $refuri=&declutter($refuri);
                   4524:                     my ($match) = &is_on_map($refuri);
                   4525:                     if ($match) {
                   4526:                         $thisallowed='F';
                   4527:                     }
1.669     raeburn  4528:                 }
1.671     raeburn  4529:             }
                   4530:         }
1.314     www      4531:     }
1.492     albertel 4532: 
1.766     albertel 4533:     if ($priv eq 'bre'
                   4534: 	&& $thisallowed ne 'F' 
                   4535: 	&& $thisallowed ne '2'
                   4536: 	&& &is_portfolio_url($uri)) {
                   4537: 	$thisallowed = &portfolio_access($uri);
                   4538:     }
                   4539:     
1.52      www      4540: # Full access at system, domain or course-wide level? Exit.
1.29      www      4541:     if ($thisallowed=~/F/) {
                   4542: 	return 'F';
                   4543:     }
                   4544: 
1.52      www      4545: # If this is generating or modifying users, exit with special codes
1.29      www      4546: 
1.643     www      4547:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4548: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4549: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4550: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4551: 	    unless ($auname) { return $thisallowed; }
                   4552: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4553: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4554: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4555: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4556: 	}
1.52      www      4557: 	return $thisallowed;
                   4558:     }
                   4559: #
1.103     harris41 4560: # Gathered so far: system, domain and course wide privileges
1.52      www      4561: #
                   4562: # Course: See if uri or referer is an individual resource that is part of 
                   4563: # the course
                   4564: 
1.620     albertel 4565:     if ($env{'request.course.id'}) {
1.232     www      4566: 
1.620     albertel 4567:        $courseprivid=$env{'request.course.id'};
                   4568:        if ($env{'request.course.sec'}) {
                   4569:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4570:        }
                   4571:        $courseprivid=~s/\_/\//;
                   4572:        my $checkreferer=1;
1.232     www      4573:        my ($match,$cond)=&is_on_map($uri);
                   4574:        if ($match) {
                   4575:            $statecond=$cond;
1.620     albertel 4576:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4577:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4578:                $thisallowed.=$1;
                   4579:                $checkreferer=0;
                   4580:            }
1.29      www      4581:        }
1.83      www      4582:        
1.148     www      4583:        if ($checkreferer) {
1.620     albertel 4584: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4585:             unless ($refuri) {
1.800     albertel 4586:                 foreach my $key (keys(%env)) {
                   4587: 		    if ($key=~/^httpref\..*\*/) {
                   4588: 			my $pattern=$key;
1.156     www      4589:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4590:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4591:                         $pattern=~s/\//\\\//g;
1.152     www      4592:                         if ($orguri=~/$pattern/) {
1.800     albertel 4593: 			    $refuri=$env{$key};
1.148     www      4594:                         }
                   4595:                     }
1.191     harris41 4596:                 }
1.148     www      4597:             }
1.232     www      4598: 
1.148     www      4599:          if ($refuri) { 
1.152     www      4600: 	  $refuri=&declutter($refuri);
1.232     www      4601:           my ($match,$cond)=&is_on_map($refuri);
                   4602:             if ($match) {
                   4603:               my $refstatecond=$cond;
1.620     albertel 4604:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4605:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4606:                   $thisallowed.=$1;
1.53      www      4607:                   $uri=$refuri;
                   4608:                   $statecond=$refstatecond;
1.52      www      4609:               }
                   4610:           }
1.148     www      4611:         }
1.29      www      4612:        }
1.52      www      4613:    }
1.29      www      4614: 
1.52      www      4615: #
1.103     harris41 4616: # Gathered now: all privileges that could apply, and condition number
1.52      www      4617: # 
                   4618: #
                   4619: # Full or no access?
                   4620: #
1.29      www      4621: 
1.52      www      4622:     if ($thisallowed=~/F/) {
                   4623: 	return 'F';
                   4624:     }
1.29      www      4625: 
1.52      www      4626:     unless ($thisallowed) {
                   4627:         return '';
                   4628:     }
1.29      www      4629: 
1.52      www      4630: # Restrictions exist, deal with them
                   4631: #
                   4632: #   C:according to course preferences
                   4633: #   R:according to resource settings
                   4634: #   L:unless locked
                   4635: #   X:according to user session state
                   4636: #
                   4637: 
                   4638: # Possibly locked functionality, check all courses
1.54      www      4639: # Locks might take effect only after 10 minutes cache expiration for other
                   4640: # courses, and 2 minutes for current course
1.52      www      4641: 
                   4642:     my $envkey;
                   4643:     if ($thisallowed=~/L/) {
1.620     albertel 4644:         foreach $envkey (keys %env) {
1.54      www      4645:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4646:                my $courseid=$2;
                   4647:                my $roleid=$1.'.'.$2;
1.92      www      4648:                $courseid=~s/^\///;
1.54      www      4649:                my $expiretime=600;
1.620     albertel 4650:                if ($env{'request.role'} eq $roleid) {
1.54      www      4651: 		  $expiretime=120;
                   4652:                }
                   4653: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4654:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4655:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4656: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4657:                }
1.620     albertel 4658:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4659:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4660: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4661:                        &log($env{'user.domain'},$env{'user.name'},
                   4662:                             $env{'user.home'},
1.57      www      4663:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4664:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4665:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4666: 		       return '';
                   4667:                    }
                   4668:                }
1.620     albertel 4669:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4670:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4671: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4672:                        &log($env{'user.domain'},$env{'user.name'},
                   4673:                             $env{'user.home'},
1.57      www      4674:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4675:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4676:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4677: 		       return '';
                   4678:                    }
                   4679:                }
                   4680: 	   }
1.29      www      4681:        }
1.52      www      4682:     }
                   4683:    
                   4684: #
                   4685: # Rest of the restrictions depend on selected course
                   4686: #
                   4687: 
1.620     albertel 4688:     unless ($env{'request.course.id'}) {
1.766     albertel 4689: 	if ($thisallowed eq 'A') {
                   4690: 	    return 'A';
1.814     raeburn  4691:         } elsif ($thisallowed eq 'B') {
                   4692:             return 'B';
1.766     albertel 4693: 	} else {
                   4694: 	    return '1';
                   4695: 	}
1.52      www      4696:     }
1.29      www      4697: 
1.52      www      4698: #
                   4699: # Now user is definitely in a course
                   4700: #
1.53      www      4701: 
                   4702: 
                   4703: # Course preferences
                   4704: 
                   4705:    if ($thisallowed=~/C/) {
1.620     albertel 4706:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4707:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4708:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4709: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4710: 	   if ($priv ne 'pch') { 
                   4711: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4712: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4713: 			$env{'request.course.id'});
                   4714: 	   }
1.237     www      4715:            return '';
                   4716:        }
                   4717: 
1.620     albertel 4718:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4719: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4720: 	   if ($priv ne 'pch') { 
                   4721: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4722: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4723: 			$env{'request.course.id'});
                   4724: 	   }
1.54      www      4725:            return '';
                   4726:        }
1.53      www      4727:    }
                   4728: 
                   4729: # Resource preferences
                   4730: 
                   4731:    if ($thisallowed=~/R/) {
1.620     albertel 4732:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4733:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4734: 	   if ($priv ne 'pch') { 
                   4735: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4736: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4737: 	   }
                   4738: 	   return '';
1.54      www      4739:        }
1.53      www      4740:    }
1.30      www      4741: 
1.246     www      4742: # Restricted by state or randomout?
1.30      www      4743: 
1.52      www      4744:    if ($thisallowed=~/X/) {
1.620     albertel 4745:       if ($env{'acc.randomout'}) {
1.579     albertel 4746: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4747:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4748:             return ''; 
                   4749:          }
1.247     www      4750:       }
                   4751:       if (&condval($statecond)) {
1.52      www      4752: 	 return '2';
                   4753:       } else {
                   4754:          return '';
                   4755:       }
                   4756:    }
1.30      www      4757: 
1.766     albertel 4758:     if ($thisallowed eq 'A') {
                   4759: 	return 'A';
1.814     raeburn  4760:     } elsif ($thisallowed eq 'B') {
                   4761:         return 'B';
1.766     albertel 4762:     }
1.52      www      4763:    return 'F';
1.232     www      4764: }
                   4765: 
1.710     albertel 4766: sub split_uri_for_cond {
                   4767:     my $uri=&deversion(&declutter(shift));
                   4768:     my @uriparts=split(/\//,$uri);
                   4769:     my $filename=pop(@uriparts);
                   4770:     my $pathname=join('/',@uriparts);
                   4771:     return ($pathname,$filename);
                   4772: }
1.232     www      4773: # --------------------------------------------------- Is a resource on the map?
                   4774: 
                   4775: sub is_on_map {
1.710     albertel 4776:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4777:     #Trying to find the conditional for the file
1.620     albertel 4778:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4779: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4780:     if ($match) {
1.289     bowersj2 4781: 	return (1,$1);
                   4782:     } else {
1.434     www      4783: 	return (0,0);
1.289     bowersj2 4784:     }
1.12      www      4785: }
                   4786: 
1.427     www      4787: # --------------------------------------------------------- Get symb from alias
                   4788: 
                   4789: sub get_symb_from_alias {
                   4790:     my $symb=shift;
                   4791:     my ($map,$resid,$url)=&decode_symb($symb);
                   4792: # Already is a symb
                   4793:     if ($url) { return $symb; }
                   4794: # Must be an alias
                   4795:     my $aliassymb='';
                   4796:     my %bighash;
1.620     albertel 4797:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4798:                             &GDBM_READER(),0640)) {
                   4799:         my $rid=$bighash{'mapalias_'.$symb};
                   4800: 	if ($rid) {
                   4801: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4802: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4803: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4804: 	}
                   4805:         untie %bighash;
                   4806:     }
                   4807:     return $aliassymb;
                   4808: }
                   4809: 
1.12      www      4810: # ----------------------------------------------------------------- Define Role
                   4811: 
                   4812: sub definerole {
                   4813:   if (allowed('mcr','/')) {
                   4814:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4815:     foreach my $role (split(':',$sysrole)) {
                   4816: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4817:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4818:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4819: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4820:                return "refused:s:$crole&$cqual"; 
                   4821:             }
                   4822:         }
1.191     harris41 4823:     }
1.800     albertel 4824:     foreach my $role (split(':',$domrole)) {
                   4825: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4826:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4827:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4828: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4829:                return "refused:d:$crole&$cqual"; 
                   4830:             }
                   4831:         }
1.191     harris41 4832:     }
1.800     albertel 4833:     foreach my $role (split(':',$courole)) {
                   4834: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4835:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4836:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4837: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4838:                return "refused:c:$crole&$cqual"; 
                   4839:             }
                   4840:         }
1.191     harris41 4841:     }
1.620     albertel 4842:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4843:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4844: 	        "rolesdef_$rolename=".
                   4845:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4846:     return reply($command,$env{'user.home'});
1.12      www      4847:   } else {
                   4848:     return 'refused';
                   4849:   }
1.105     harris41 4850: }
                   4851: 
                   4852: # ---------------- Make a metadata query against the network of library servers
                   4853: 
                   4854: sub metadata_query {
1.244     matthew  4855:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4856:     my %rhash;
1.845     albertel 4857:     my %libserv = &all_library();
1.244     matthew  4858:     my @server_list = (defined($server_array) ? @$server_array
                   4859:                                               : keys(%libserv) );
                   4860:     for my $server (@server_list) {
1.118     harris41 4861: 	unless ($custom or $customshow) {
                   4862: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4863: 	    $rhash{$server}=$reply;
                   4864: 	}
                   4865: 	else {
                   4866: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4867: 			     &escape($custom).':'.&escape($customshow),
                   4868: 			     $server);
                   4869: 	    $rhash{$server}=$reply;
                   4870: 	}
1.112     harris41 4871:     }
1.118     harris41 4872:     return \%rhash;
1.240     www      4873: }
                   4874: 
                   4875: # ----------------------------------------- Send log queries and wait for reply
                   4876: 
                   4877: sub log_query {
                   4878:     my ($uname,$udom,$query,%filters)=@_;
                   4879:     my $uhome=&homeserver($uname,$udom);
                   4880:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4881:     my $uhost=&hostname($uhome);
1.800     albertel 4882:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4883:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4884:                        $uhome);
1.479     albertel 4885:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4886:     return get_query_reply($queryid);
                   4887: }
                   4888: 
1.818     raeburn  4889: # -------------------------- Update MySQL table for portfolio file
                   4890: 
                   4891: sub update_portfolio_table {
1.821     raeburn  4892:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4893:     my $homeserver = &homeserver($uname,$udom);
                   4894:     my $queryid=
1.821     raeburn  4895:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4896:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4897:     my $reply = &get_query_reply($queryid);
                   4898:     return $reply;
                   4899: }
                   4900: 
1.899     raeburn  4901: # -------------------------- Update MySQL allusers table
                   4902: 
                   4903: sub update_allusers_table {
                   4904:     my ($uname,$udom,$names) = @_;
                   4905:     my $homeserver = &homeserver($uname,$udom);
                   4906:     my $queryid=
                   4907:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4908:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4909:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4910:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4911:                'generation='.&escape($names->{'generation'}).'%%'.
                   4912:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4913:                'id='.&escape($names->{'id'}),$homeserver);
                   4914:     my $reply = &get_query_reply($queryid);
                   4915:     return $reply;
                   4916: }
                   4917: 
1.508     raeburn  4918: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4919: 
                   4920: sub fetch_enrollment_query {
1.511     raeburn  4921:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4922:     my $homeserver;
1.547     raeburn  4923:     my $maxtries = 1;
1.508     raeburn  4924:     if ($context eq 'automated') {
                   4925:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4926:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4927:     } else {
                   4928:         $homeserver = &homeserver($cnum,$dom);
                   4929:     }
1.838     albertel 4930:     my $host=&hostname($homeserver);
1.506     raeburn  4931:     my $cmd = '';
1.800     albertel 4932:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4933:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4934:     }
                   4935:     $cmd =~ s/%%$//;
                   4936:     $cmd = &escape($cmd);
                   4937:     my $query = 'fetchenrollment';
1.620     albertel 4938:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4939:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4940:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4941:         return 'error: '.$queryid;
                   4942:     }
1.506     raeburn  4943:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4944:     my $tries = 1;
                   4945:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4946:         $reply = &get_query_reply($queryid);
                   4947:         $tries ++;
                   4948:     }
1.526     raeburn  4949:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4950:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4951:     } else {
1.901     albertel 4952:         my @responses = split(/:/,$reply);
1.515     raeburn  4953:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4954:             foreach my $line (@responses) {
                   4955:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4956:                 $$replyref{$key} = $value;
                   4957:             }
                   4958:         } else {
1.506     raeburn  4959:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4960:             foreach my $line (@responses) {
                   4961:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4962:                 $$replyref{$key} = $value;
                   4963:                 if ($value > 0) {
1.800     albertel 4964:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4965:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4966:                         my $destname = $pathname.'/'.$filename;
                   4967:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4968:                         if ($xml_classlist =~ /^error/) {
                   4969:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4970:                         } else {
1.506     raeburn  4971:                             if ( open(FILE,">$destname") ) {
                   4972:                                 print FILE &unescape($xml_classlist);
                   4973:                                 close(FILE);
1.526     raeburn  4974:                             } else {
                   4975:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4976:                             }
                   4977:                         }
                   4978:                     }
                   4979:                 }
                   4980:             }
                   4981:         }
                   4982:         return 'ok';
                   4983:     }
                   4984:     return 'error';
                   4985: }
                   4986: 
1.242     www      4987: sub get_query_reply {
                   4988:     my $queryid=shift;
1.240     www      4989:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4990:     my $reply='';
                   4991:     for (1..100) {
                   4992: 	sleep 2;
                   4993:         if (-e $replyfile.'.end') {
1.448     albertel 4994: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4995: 		$reply = join('',<$fh>);
                   4996: 		close($fh);
1.240     www      4997: 	   } else { return 'error: reply_file_error'; }
1.242     www      4998:            return &unescape($reply);
                   4999: 	}
1.240     www      5000:     }
1.242     www      5001:     return 'timeout:'.$queryid;
1.240     www      5002: }
                   5003: 
                   5004: sub courselog_query {
1.241     www      5005: #
                   5006: # possible filters:
                   5007: # url: url or symb
                   5008: # username
                   5009: # domain
                   5010: # action: view, submit, grade
                   5011: # start: timestamp
                   5012: # end: timestamp
                   5013: #
1.240     www      5014:     my (%filters)=@_;
1.620     albertel 5015:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5016:     if ($filters{'url'}) {
                   5017: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5018:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5019:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5020:     }
1.620     albertel 5021:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5022:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5023:     return &log_query($cname,$cdom,'courselog',%filters);
                   5024: }
                   5025: 
                   5026: sub userlog_query {
1.858     raeburn  5027: #
                   5028: # possible filters:
                   5029: # action: log check role
                   5030: # start: timestamp
                   5031: # end: timestamp
                   5032: #
1.240     www      5033:     my ($uname,$udom,%filters)=@_;
                   5034:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5035: }
                   5036: 
1.506     raeburn  5037: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5038: 
                   5039: sub auto_run {
1.508     raeburn  5040:     my ($cnum,$cdom) = @_;
1.876     raeburn  5041:     my $response = 0;
                   5042:     my $settings;
                   5043:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5044:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5045:         $settings = $domconfig{'autoenroll'};
                   5046:         if ($settings->{'run'} eq '1') {
                   5047:             $response = 1;
                   5048:         }
                   5049:     } else {
1.934     raeburn  5050:         my $homeserver;
                   5051:         if (&is_course($cdom,$cnum)) {
                   5052:             $homeserver = &homeserver($cnum,$cdom);
                   5053:         } else {
                   5054:             $homeserver = &domain($cdom,'primary');
                   5055:         }
                   5056:         if ($homeserver ne 'no_host') {
                   5057:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5058:         }
1.876     raeburn  5059:     }
1.506     raeburn  5060:     return $response;
                   5061: }
1.776     albertel 5062: 
1.506     raeburn  5063: sub auto_get_sections {
1.508     raeburn  5064:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5065:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5066:     my @secs = ();
1.511     raeburn  5067:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5068:     unless ($response eq 'refused') {
1.901     albertel 5069:         @secs = split(/:/,$response);
1.506     raeburn  5070:     }
                   5071:     return @secs;
                   5072: }
1.776     albertel 5073: 
1.506     raeburn  5074: sub auto_new_course {
1.508     raeburn  5075:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5076:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5077:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5078:     return $response;
                   5079: }
1.776     albertel 5080: 
1.506     raeburn  5081: sub auto_validate_courseID {
1.508     raeburn  5082:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5083:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5084:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5085:     return $response;
                   5086: }
1.776     albertel 5087: 
1.506     raeburn  5088: sub auto_create_password {
1.873     raeburn  5089:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5090:     my ($homeserver,$response);
1.506     raeburn  5091:     my $create_passwd = 0;
                   5092:     my $authchk = '';
1.873     raeburn  5093:     if ($udom =~ /^$match_domain$/) {
                   5094:         $homeserver = &domain($udom,'primary');
                   5095:     }
                   5096:     if ($homeserver eq '') {
                   5097:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5098:             $homeserver = &homeserver($cnum,$cdom);
                   5099:         }
                   5100:     }
                   5101:     if ($homeserver eq '') {
                   5102:         $authchk = 'nodomain';
1.506     raeburn  5103:     } else {
1.873     raeburn  5104:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5105:         if ($response eq 'refused') {
                   5106:             $authchk = 'refused';
                   5107:         } else {
1.901     albertel 5108:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5109:         }
1.506     raeburn  5110:     }
                   5111:     return ($authparam,$create_passwd,$authchk);
                   5112: }
                   5113: 
1.706     raeburn  5114: sub auto_photo_permission {
                   5115:     my ($cnum,$cdom,$students) = @_;
                   5116:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5117:     my ($outcome,$perm_reqd,$conditions) = 
                   5118: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5119:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5120: 	return (undef,undef);
                   5121:     }
1.706     raeburn  5122:     return ($outcome,$perm_reqd,$conditions);
                   5123: }
                   5124: 
                   5125: sub auto_checkphotos {
                   5126:     my ($uname,$udom,$pid) = @_;
                   5127:     my $homeserver = &homeserver($uname,$udom);
                   5128:     my ($result,$resulttype);
                   5129:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5130: 				   &escape($uname).':'.&escape($pid),
                   5131: 				   $homeserver));
1.709     albertel 5132:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5133: 	return (undef,undef);
                   5134:     }
1.706     raeburn  5135:     if ($outcome) {
                   5136:         ($result,$resulttype) = split(/:/,$outcome);
                   5137:     } 
                   5138:     return ($result,$resulttype);
                   5139: }
                   5140: 
                   5141: sub auto_photochoice {
                   5142:     my ($cnum,$cdom) = @_;
                   5143:     my $homeserver = &homeserver($cnum,$cdom);
                   5144:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5145: 						       &escape($cdom),
                   5146: 						       $homeserver)));
1.709     albertel 5147:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5148: 	return (undef,undef);
                   5149:     }
1.706     raeburn  5150:     return ($update,$comment);
                   5151: }
                   5152: 
                   5153: sub auto_photoupdate {
                   5154:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5155:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5156:     my $host=&hostname($homeserver);
1.706     raeburn  5157:     my $cmd = '';
                   5158:     my $maxtries = 1;
1.800     albertel 5159:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5160:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5161:     }
                   5162:     $cmd =~ s/%%$//;
                   5163:     $cmd = &escape($cmd);
                   5164:     my $query = 'institutionalphotos';
                   5165:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5166:     unless ($queryid=~/^\Q$host\E\_/) {
                   5167:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5168:         return 'error: '.$queryid;
                   5169:     }
                   5170:     my $reply = &get_query_reply($queryid);
                   5171:     my $tries = 1;
                   5172:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5173:         $reply = &get_query_reply($queryid);
                   5174:         $tries ++;
                   5175:     }
                   5176:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5177:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5178:     } else {
                   5179:         my @responses = split(/:/,$reply);
                   5180:         my $outcome = shift(@responses); 
                   5181:         foreach my $item (@responses) {
                   5182:             my ($key,$value) = split(/=/,$item);
                   5183:             $$photo{$key} = $value;
                   5184:         }
                   5185:         return $outcome;
                   5186:     }
                   5187:     return 'error';
                   5188: }
                   5189: 
1.521     raeburn  5190: sub auto_instcode_format {
1.793     albertel 5191:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5192: 	$cat_order) = @_;
1.521     raeburn  5193:     my $courses = '';
1.772     raeburn  5194:     my @homeservers;
1.521     raeburn  5195:     if ($caller eq 'global') {
1.841     albertel 5196: 	my %servers = &get_servers($codedom,'library');
                   5197: 	foreach my $tryserver (keys(%servers)) {
                   5198: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5199: 		push(@homeservers,$tryserver);
                   5200: 	    }
1.584     raeburn  5201:         }
1.521     raeburn  5202:     } else {
1.772     raeburn  5203:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5204:     }
1.793     albertel 5205:     foreach my $code (keys(%{$instcodes})) {
                   5206:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5207:     }
                   5208:     chop($courses);
1.772     raeburn  5209:     my $ok_response = 0;
                   5210:     my $response;
                   5211:     while (@homeservers > 0 && $ok_response == 0) {
                   5212:         my $server = shift(@homeservers); 
                   5213:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5214:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5215:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5216: 		split(/:/,$response);
1.772     raeburn  5217:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5218:             push(@{$codetitles},&str2array($codetitles_str));
                   5219:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5220:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5221:             $ok_response = 1;
                   5222:         }
                   5223:     }
                   5224:     if ($ok_response) {
1.521     raeburn  5225:         return 'ok';
1.772     raeburn  5226:     } else {
                   5227:         return $response;
1.521     raeburn  5228:     }
                   5229: }
                   5230: 
1.792     raeburn  5231: sub auto_instcode_defaults {
                   5232:     my ($domain,$returnhash,$code_order) = @_;
                   5233:     my @homeservers;
1.841     albertel 5234: 
                   5235:     my %servers = &get_servers($domain,'library');
                   5236:     foreach my $tryserver (keys(%servers)) {
                   5237: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5238: 	    push(@homeservers,$tryserver);
                   5239: 	}
1.792     raeburn  5240:     }
1.841     albertel 5241: 
1.792     raeburn  5242:     my $response;
1.841     albertel 5243:     foreach my $server (@homeservers) {
1.792     raeburn  5244:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5245:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5246: 	
                   5247: 	foreach my $pair (split(/\&/,$response)) {
                   5248: 	    my ($name,$value)=split(/\=/,$pair);
                   5249: 	    if ($name eq 'code_order') {
                   5250: 		@{$code_order} = split(/\&/,&unescape($value));
                   5251: 	    } else {
                   5252: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5253: 	    }
                   5254: 	}
                   5255: 	return 'ok';
1.792     raeburn  5256:     }
1.841     albertel 5257: 
                   5258:     return $response;
1.792     raeburn  5259: } 
                   5260: 
1.777     albertel 5261: sub auto_validate_class_sec {
1.918     raeburn  5262:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5263:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5264:     my $ownerlist;
                   5265:     if (ref($owners) eq 'ARRAY') {
                   5266:         $ownerlist = join(',',@{$owners});
                   5267:     } else {
                   5268:         $ownerlist = $owners;
                   5269:     }
1.773     raeburn  5270:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5271:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5272:     return $response;
                   5273: }
                   5274: 
1.679     raeburn  5275: # ------------------------------------------------------- Course Group routines
                   5276: 
                   5277: sub get_coursegroups {
1.809     raeburn  5278:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5279:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5280: }
                   5281: 
1.679     raeburn  5282: sub modify_coursegroup {
                   5283:     my ($cdom,$cnum,$groupsettings) = @_;
                   5284:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5285: }
                   5286: 
1.809     raeburn  5287: sub toggle_coursegroup_status {
                   5288:     my ($cdom,$cnum,$group,$action) = @_;
                   5289:     my ($from_namespace,$to_namespace);
                   5290:     if ($action eq 'delete') {
                   5291:         $from_namespace = 'coursegroups';
                   5292:         $to_namespace = 'deleted_groups';
                   5293:     } else {
                   5294:         $from_namespace = 'deleted_groups';
                   5295:         $to_namespace = 'coursegroups';
                   5296:     }
                   5297:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5298:     if (my $tmp = &error(%curr_group)) {
                   5299:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5300:         return ('read error',$tmp);
                   5301:     } else {
                   5302:         my %savedsettings = %curr_group; 
1.809     raeburn  5303:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5304:         my $deloutcome;
                   5305:         if ($result eq 'ok') {
1.809     raeburn  5306:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5307:         } else {
                   5308:             return ('write error',$result);
                   5309:         }
                   5310:         if ($deloutcome eq 'ok') {
                   5311:             return 'ok';
                   5312:         } else {
                   5313:             return ('delete error',$deloutcome);
                   5314:         }
                   5315:     }
                   5316: }
                   5317: 
1.679     raeburn  5318: sub modify_group_roles {
1.957     raeburn  5319:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5320:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5321:     my $role = 'gr/'.&escape($userprivs);
                   5322:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5323:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5324:     if ($result eq 'ok') {
                   5325:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5326:     }
1.679     raeburn  5327:     return $result;
                   5328: }
                   5329: 
                   5330: sub modify_coursegroup_membership {
                   5331:     my ($cdom,$cnum,$membership) = @_;
                   5332:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5333:     return $result;
                   5334: }
                   5335: 
1.682     raeburn  5336: sub get_active_groups {
                   5337:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5338:     my $now = time;
                   5339:     my %groups = ();
                   5340:     foreach my $key (keys(%env)) {
1.811     albertel 5341:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5342:             my ($start,$end) = split(/\./,$env{$key});
                   5343:             if (($end!=0) && ($end<$now)) { next; }
                   5344:             if (($start!=0) && ($start>$now)) { next; }
                   5345:             if ($1 eq $cdom && $2 eq $cnum) {
                   5346:                 $groups{$3} = $env{$key} ;
                   5347:             }
                   5348:         }
                   5349:     }
                   5350:     return %groups;
                   5351: }
                   5352: 
1.683     raeburn  5353: sub get_group_membership {
                   5354:     my ($cdom,$cnum,$group) = @_;
                   5355:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5356: }
                   5357: 
                   5358: sub get_users_groups {
                   5359:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5360:     my @usersgroups;
1.683     raeburn  5361:     my $cachetime=1800;
                   5362: 
                   5363:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5364:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5365:     if (defined($cached)) {
1.734     albertel 5366:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5367:     } else {  
                   5368:         $grouplist = '';
1.816     raeburn  5369:         my $courseurl = &courseid_to_courseurl($courseid);
                   5370:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5371:         my $access_end = $env{'course.'.$courseid.
                   5372:                               '.default_enrollment_end_date'};
                   5373:         my $now = time;
                   5374:         foreach my $key (keys(%roleshash)) {
                   5375:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5376:                 my $group = $1;
                   5377:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5378:                     my $start = $2;
                   5379:                     my $end = $1;
                   5380:                     if ($start == -1) { next; } # deleted from group
                   5381:                     if (($start!=0) && ($start>$now)) { next; }
                   5382:                     if (($end!=0) && ($end<$now)) {
                   5383:                         if ($access_end && $access_end < $now) {
                   5384:                             if ($access_end - $end < 86400) {
                   5385:                                 push(@usersgroups,$group);
1.733     raeburn  5386:                             }
                   5387:                         }
1.817     raeburn  5388:                         next;
1.733     raeburn  5389:                     }
1.817     raeburn  5390:                     push(@usersgroups,$group);
1.683     raeburn  5391:                 }
                   5392:             }
                   5393:         }
1.817     raeburn  5394:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5395:         $grouplist = join(':',@usersgroups);
                   5396:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5397:     }
1.733     raeburn  5398:     return @usersgroups;
1.683     raeburn  5399: }
                   5400: 
                   5401: sub devalidate_getgroups_cache {
                   5402:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5403:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5404: 
1.683     raeburn  5405:     my $hashid="$udom:$uname:$courseid";
                   5406:     &devalidate_cache_new('getgroups',$hashid);
                   5407: }
                   5408: 
1.12      www      5409: # ------------------------------------------------------------------ Plain Text
                   5410: 
                   5411: sub plaintext {
1.742     raeburn  5412:     my ($short,$type,$cid) = @_;
1.758     albertel 5413:     if ($short =~ /^cr/) {
                   5414: 	return (split('/',$short))[-1];
                   5415:     }
1.742     raeburn  5416:     if (!defined($cid)) {
                   5417:         $cid = $env{'request.course.id'};
                   5418:     }
                   5419:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5420:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5421:                                           '.plaintext'});
                   5422:     }
                   5423:     my %rolenames = (
                   5424:                       Course => 'std',
                   5425:                       Group => 'alt1',
                   5426:                     );
                   5427:     if (defined($type) && 
                   5428:          defined($rolenames{$type}) && 
                   5429:          defined($prp{$short}{$rolenames{$type}})) {
                   5430:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5431:     } else {
                   5432:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5433:     }
1.12      www      5434: }
                   5435: 
                   5436: # ----------------------------------------------------------------- Assign Role
                   5437: 
                   5438: sub assignrole {
1.957     raeburn  5439:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5440:         $context)=@_;
1.21      www      5441:     my $mrole;
                   5442:     if ($role =~ /^cr\//) {
1.393     www      5443:         my $cwosec=$url;
1.811     albertel 5444:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5445: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5446:            &logthis('Refused custom assignrole: '.
                   5447:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5448: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5449:            return 'refused'; 
                   5450:         }
1.21      www      5451:         $mrole='cr';
1.678     raeburn  5452:     } elsif ($role =~ /^gr\//) {
                   5453:         my $cwogrp=$url;
1.811     albertel 5454:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5455:         unless (&allowed('mdg',$cwogrp)) {
                   5456:             &logthis('Refused group assignrole: '.
                   5457:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5458:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5459:             return 'refused';
                   5460:         }
                   5461:         $mrole='gr';
1.21      www      5462:     } else {
1.82      www      5463:         my $cwosec=$url;
1.811     albertel 5464:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5465:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5466:             my $refused;
                   5467:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5468:                 if (!(&allowed('c'.$role,$url))) {
                   5469:                     $refused = 1;
                   5470:                 }
                   5471:             } else {
                   5472:                 $refused = 1;
                   5473:             }
1.947     raeburn  5474:             if ($refused) {
                   5475:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5476:                     $refused = '';
                   5477:                 } else {
                   5478:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5479:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5480: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5481:                     return 'refused';
                   5482:                 }
1.932     raeburn  5483:             }
1.104     www      5484:         }
1.21      www      5485:         $mrole=$role;
                   5486:     }
1.620     albertel 5487:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5488:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5489:     if ($end) { $command.='_'.$end; }
1.21      www      5490:     if ($start) {
                   5491: 	if ($end) { 
1.81      www      5492:            $command.='_'.$start; 
1.21      www      5493:         } else {
1.81      www      5494:            $command.='_0_'.$start;
1.21      www      5495:         }
                   5496:     }
1.739     raeburn  5497:     my $origstart = $start;
                   5498:     my $origend = $end;
1.957     raeburn  5499:     my $delflag;
1.357     www      5500: # actually delete
                   5501:     if ($deleteflag) {
1.373     www      5502: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5503: # modify command to delete the role
1.620     albertel 5504:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5505:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5506: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5507: # set start and finish to negative values for userrolelog
                   5508:            $start=-1;
                   5509:            $end=-1;
1.957     raeburn  5510:            $delflag = 1;
1.357     www      5511:         }
                   5512:     }
                   5513: # send command
1.349     www      5514:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5515: # log new user role if status is ok
1.349     www      5516:     if ($answer eq 'ok') {
1.663     raeburn  5517: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5518: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5519:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5520:         unless ($role =~ /^gr/) {
                   5521:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5522:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5523:         }
1.349     www      5524:     }
                   5525:     return $answer;
1.169     harris41 5526: }
                   5527: 
                   5528: # -------------------------------------------------- Modify user authentication
1.197     www      5529: # Overrides without validation
                   5530: 
1.169     harris41 5531: sub modifyuserauth {
                   5532:     my ($udom,$uname,$umode,$upass)=@_;
                   5533:     my $uhome=&homeserver($uname,$udom);
1.197     www      5534:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5535:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5536:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5537:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5538:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5539: 		     &escape($upass),$uhome);
1.620     albertel 5540:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5541:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5542:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5543:     &log($udom,,$uname,$uhome,
1.620     albertel 5544:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5545:                                      $env{'user.name'}.', '.$umode.
1.197     www      5546:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5547:     unless ($reply eq 'ok') {
1.197     www      5548:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5549: 	return 'error: '.$reply;
                   5550:     }   
1.170     harris41 5551:     return 'ok';
1.80      www      5552: }
                   5553: 
1.81      www      5554: # --------------------------------------------------------------- Modify a user
1.80      www      5555: 
1.81      www      5556: sub modifyuser {
1.206     matthew  5557:     my ($udom,    $uname, $uid,
                   5558:         $umode,   $upass, $first,
                   5559:         $middle,  $last,  $gene,
1.387     www      5560:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5561:     $udom= &LONCAPA::clean_domain($udom);
                   5562:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5563:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5564:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5565: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5566:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5567:                                      ' desiredhome not specified'). 
1.620     albertel 5568:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5569:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5570:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5571: # ----------------------------------------------------------------- Create User
1.406     albertel 5572:     if (($uhome eq 'no_host') && 
                   5573: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5574:         my $unhome='';
1.844     albertel 5575:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5576:             $unhome = $desiredhome;
1.620     albertel 5577: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5578: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5579:         } else { # load balancing routine for determining $unhome
1.81      www      5580:             my $loadm=10000000;
1.841     albertel 5581: 	    my %servers = &get_servers($udom,'library');
                   5582: 	    foreach my $tryserver (keys(%servers)) {
                   5583: 		my $answer=reply('load',$tryserver);
                   5584: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5585: 		    $loadm=$answer;
                   5586: 		    $unhome=$tryserver;
                   5587: 		}
1.80      www      5588: 	    }
                   5589:         }
                   5590:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5591: 	    return 'error: unable to find a home server for '.$uname.
                   5592:                    ' in domain '.$udom;
1.80      www      5593:         }
                   5594:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5595:                          &escape($upass),$unhome);
                   5596: 	unless ($reply eq 'ok') {
                   5597:             return 'error: '.$reply;
                   5598:         }   
1.230     stredwic 5599:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5600:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5601: 	    return 'error: unable verify users home machine.';
1.80      www      5602:         }
1.209     matthew  5603:     }   # End of creation of new user
1.80      www      5604: # ---------------------------------------------------------------------- Add ID
                   5605:     if ($uid) {
                   5606:        $uid=~tr/A-Z/a-z/;
                   5607:        my %uidhash=&idrget($udom,$uname);
1.196     www      5608:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5609:          && (!$forceid)) {
1.80      www      5610: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5611: 	      return 'error: user id "'.$uid.'" does not match '.
                   5612:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5613:           }
                   5614:        } else {
                   5615: 	  &idput($udom,($uname => $uid));
                   5616:        }
                   5617:     }
                   5618: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5619:     my @tmp=&get('environment',
1.899     raeburn  5620: 		   ['firstname','middlename','lastname','generation','id',
                   5621:                     'permanentemail'],
1.134     albertel 5622: 		   $udom,$uname);
1.313     matthew  5623:     my %names;
                   5624:     if ($tmp[0] =~ m/^error:.*/) { 
                   5625:         %names=(); 
                   5626:     } else {
                   5627:         %names = @tmp;
                   5628:     }
1.388     www      5629: #
                   5630: # Make sure to not trash student environment if instructor does not bother
                   5631: # to supply name and email information
                   5632: #
                   5633:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5634:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5635:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5636:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5637:     if ($email) {
                   5638:        $email=~s/[^\w\@\.\-\,]//gs;
                   5639:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5640: 			   $names{'critnotification'} = $email;
                   5641: 			   $names{'permanentemail'} = $email; }
                   5642:     }
1.899     raeburn  5643:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5644:     my $reply = &put('environment', \%names, $udom,$uname);
                   5645:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5646:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5647:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5648:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5649:              $umode.', '.$first.', '.$middle.', '.
                   5650: 	     $last.', '.$gene.' by '.
1.620     albertel 5651:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5652:     return 'ok';
1.80      www      5653: }
                   5654: 
1.81      www      5655: # -------------------------------------------------------------- Modify student
1.80      www      5656: 
1.81      www      5657: sub modifystudent {
                   5658:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5659:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5660:         $selfenroll,$context)=@_;
1.455     albertel 5661:     if (!$cid) {
1.620     albertel 5662: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5663: 	    return 'not_in_class';
                   5664: 	}
1.80      www      5665:     }
                   5666: # --------------------------------------------------------------- Make the user
1.81      www      5667:     my $reply=&modifyuser
1.209     matthew  5668: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5669:          $desiredhome,$email);
1.80      www      5670:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5671:     # This will cause &modify_student_enrollment to get the uid from the
                   5672:     # students environment
                   5673:     $uid = undef if (!$forceid);
1.455     albertel 5674:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5675: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5676:     return $reply;
                   5677: }
                   5678: 
                   5679: sub modify_student_enrollment {
1.957     raeburn  5680:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5681:     my ($cdom,$cnum,$chome);
                   5682:     if (!$cid) {
1.620     albertel 5683: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5684: 	    return 'not_in_class';
                   5685: 	}
1.620     albertel 5686: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5687: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5688:     } else {
                   5689: 	($cdom,$cnum)=split(/_/,$cid);
                   5690:     }
1.620     albertel 5691:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5692:     if (!$chome) {
1.457     raeburn  5693: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5694:     }
1.455     albertel 5695:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5696:     # Make sure the user exists
1.81      www      5697:     my $uhome=&homeserver($uname,$udom);
                   5698:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5699: 	return 'error: no such user';
                   5700:     }
1.297     matthew  5701:     # Get student data if we were not given enough information
                   5702:     if (!defined($first)  || $first  eq '' || 
                   5703:         !defined($last)   || $last   eq '' || 
                   5704:         !defined($uid)    || $uid    eq '' || 
                   5705:         !defined($middle) || $middle eq '' || 
                   5706:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5707:         # They did not supply us with enough data to enroll the student, so
                   5708:         # we need to pick up more information.
1.297     matthew  5709:         my %tmp = &get('environment',
1.294     matthew  5710:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5711:                        ,$udom,$uname);
                   5712: 
1.800     albertel 5713:         #foreach my $key (keys(%tmp)) {
                   5714:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5715:         #}
1.294     matthew  5716:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5717:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5718:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5719:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5720:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5721:     }
1.556     albertel 5722:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5723:     my $reply=cput('classlist',
                   5724: 		   {"$uname:$udom" => 
1.515     raeburn  5725: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5726: 		   $cdom,$cnum);
1.81      www      5727:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5728: 	return 'error: '.$reply;
1.652     albertel 5729:     } else {
                   5730: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5731:     }
1.297     matthew  5732:     # Add student role to user
1.83      www      5733:     my $uurl='/'.$cid;
1.81      www      5734:     $uurl=~s/\_/\//g;
                   5735:     if ($usec) {
                   5736: 	$uurl.='/'.$usec;
                   5737:     }
1.957     raeburn  5738:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5739: }
                   5740: 
1.556     albertel 5741: sub format_name {
                   5742:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5743:     my $name;
                   5744:     if ($first ne 'lastname') {
                   5745: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5746:     } else {
                   5747: 	if ($lastname=~/\S/) {
                   5748: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5749: 	    $name=~s/\s+,/,/;
                   5750: 	} else {
                   5751: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5752: 	}
                   5753:     }
                   5754:     $name=~s/^\s+//;
                   5755:     $name=~s/\s+$//;
                   5756:     $name=~s/\s+/ /g;
                   5757:     return $name;
                   5758: }
                   5759: 
1.84      www      5760: # ------------------------------------------------- Write to course preferences
                   5761: 
                   5762: sub writecoursepref {
                   5763:     my ($courseid,%prefs)=@_;
                   5764:     $courseid=~s/^\///;
                   5765:     $courseid=~s/\_/\//g;
                   5766:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5767:     my $chome=homeserver($cnum,$cdomain);
                   5768:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5769: 	return 'error: no such course';
                   5770:     }
                   5771:     my $cstring='';
1.800     albertel 5772:     foreach my $pref (keys(%prefs)) {
                   5773: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5774:     }
1.84      www      5775:     $cstring=~s/\&$//;
                   5776:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5777: }
                   5778: 
                   5779: # ---------------------------------------------------------- Make/modify course
                   5780: 
                   5781: sub createcourse {
1.741     raeburn  5782:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5783:         $course_owner,$crstype)=@_;
1.84      www      5784:     $url=&declutter($url);
                   5785:     my $cid='';
1.264     matthew  5786:     unless (&allowed('ccc',$udom)) {
1.84      www      5787:         return 'refused';
                   5788:     }
                   5789: # ------------------------------------------------------------------- Create ID
1.674     www      5790:    my $uname=int(1+rand(9)).
                   5791:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5792:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5793:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5794: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5795:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5796:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5797:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5798:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5799:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5800:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5801:            return 'error: unable to generate unique course-ID';
                   5802:        } 
                   5803:    }
1.264     matthew  5804: # ------------------------------------------------ Check supplied server name
1.620     albertel 5805:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5806:     if (! &is_library($course_server)) {
1.264     matthew  5807:         return 'error:bad server name '.$course_server;
                   5808:     }
1.84      www      5809: # ------------------------------------------------------------- Make the course
                   5810:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5811:                       $course_server);
1.84      www      5812:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5813:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5814:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5815: 	return 'error: no such course';
                   5816:     }
1.271     www      5817: # ----------------------------------------------------------------- Course made
1.516     raeburn  5818: # log existence
1.918     raeburn  5819:     my $newcourse = {
                   5820:                     $udom.'_'.$uname => {
1.921     raeburn  5821:                                      description => $description,
                   5822:                                      inst_code   => $inst_code,
                   5823:                                      owner       => $course_owner,
                   5824:                                      type        => $crstype,
1.918     raeburn  5825:                                                 },
                   5826:                     };
1.921     raeburn  5827:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5828: # set toplevel url
1.271     www      5829:     my $topurl=$url;
                   5830:     unless ($nonstandard) {
                   5831: # ------------------------------------------ For standard courses, make top url
                   5832:         my $mapurl=&clutter($url);
1.278     www      5833:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5834:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5835: <map>
                   5836: <resource id="1" type="start"></resource>
                   5837: <resource id="2" src="$mapurl"></resource>
                   5838: <resource id="3" type="finish"></resource>
                   5839: <link index="1" from="1" to="2"></link>
                   5840: <link index="2" from="2" to="3"></link>
                   5841: </map>
                   5842: ENDINITMAP
                   5843:         $topurl=&declutter(
1.638     albertel 5844:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5845:                           );
                   5846:     }
                   5847: # ----------------------------------------------------------- Write preferences
1.84      www      5848:     &writecoursepref($udom.'_'.$uname,
                   5849:                      ('description' => $description,
1.271     www      5850:                       'url'         => $topurl));
1.84      www      5851:     return '/'.$udom.'/'.$uname;
                   5852: }
                   5853: 
1.813     albertel 5854: sub is_course {
                   5855:     my ($cdom,$cnum) = @_;
                   5856:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5857: 				undef,'.');
1.813     albertel 5858:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5859:         return 1;
                   5860:     }
                   5861:     return 0;
                   5862: }
                   5863: 
1.21      www      5864: # ---------------------------------------------------------- Assign Custom Role
                   5865: 
                   5866: sub assigncustomrole {
1.957     raeburn  5867:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5868:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  5869:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      5870: }
                   5871: 
                   5872: # ----------------------------------------------------------------- Revoke Role
                   5873: 
                   5874: sub revokerole {
1.957     raeburn  5875:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5876:     my $now=time;
1.957     raeburn  5877:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag,$selfenroll,$context);
1.21      www      5878: }
                   5879: 
                   5880: # ---------------------------------------------------------- Revoke Custom Role
                   5881: 
                   5882: sub revokecustomrole {
1.957     raeburn  5883:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5884:     my $now=time;
1.357     www      5885:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  5886:            $deleteflag,$selfenroll,$context);
1.17      www      5887: }
                   5888: 
1.533     banghart 5889: # ------------------------------------------------------------ Disk usage
1.535     albertel 5890: sub diskusage {
1.955     raeburn  5891:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   5892:     $directorypath =~ s/\/$//;
                   5893:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   5894:                        .&escape($getpropath).':'.&escape($uname).':'
                   5895:                        .&escape($udom),homeserver($uname,$udom));
                   5896:     if ($listing eq 'unknown_cmd') {
                   5897:         if ($getpropath) {
                   5898:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   5899:         }
                   5900:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   5901:     }
1.514     albertel 5902:     return $listing;
1.512     banghart 5903: }
                   5904: 
1.566     banghart 5905: sub is_locked {
                   5906:     my ($file_name, $domain, $user) = @_;
                   5907:     my @check;
                   5908:     my $is_locked;
                   5909:     push @check, $file_name;
1.613     albertel 5910:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5911: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5912:     my ($tmp)=keys(%locked);
                   5913:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5914:     
1.566     banghart 5915:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5916:         $is_locked = 'false';
                   5917:         foreach my $entry (@{$locked{$file_name}}) {
                   5918:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5919:                $is_locked = 'true';
                   5920:                last;
1.745     raeburn  5921:            }
                   5922:        }
1.566     banghart 5923:     } else {
                   5924:         $is_locked = 'false';
                   5925:     }
                   5926: }
                   5927: 
1.759     albertel 5928: sub declutter_portfile {
                   5929:     my ($file) = @_;
1.833     albertel 5930:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5931:     return $file;
                   5932: }
                   5933: 
1.559     banghart 5934: # ------------------------------------------------------------- Mark as Read Only
                   5935: 
                   5936: sub mark_as_readonly {
                   5937:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5938:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5939:     my ($tmp)=keys(%current_permissions);
                   5940:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5941:     foreach my $file (@{$files}) {
1.759     albertel 5942: 	$file = &declutter_portfile($file);
1.561     banghart 5943:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5944:     }
1.613     albertel 5945:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5946:     return;
                   5947: }
                   5948: 
1.572     banghart 5949: # ------------------------------------------------------------Save Selected Files
                   5950: 
                   5951: sub save_selected_files {
                   5952:     my ($user, $path, @files) = @_;
                   5953:     my $filename = $user."savedfiles";
1.573     banghart 5954:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5955:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5956:     foreach my $file (@files) {
1.620     albertel 5957:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5958:     }
                   5959:     foreach my $file (@other_files) {
1.574     banghart 5960:         print (OUT $file."\n");
1.572     banghart 5961:     }
1.574     banghart 5962:     close (OUT);
1.572     banghart 5963:     return 'ok';
                   5964: }
                   5965: 
1.574     banghart 5966: sub clear_selected_files {
                   5967:     my ($user) = @_;
                   5968:     my $filename = $user."savedfiles";
                   5969:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5970:     print (OUT undef);
                   5971:     close (OUT);
                   5972:     return ("ok");    
                   5973: }
                   5974: 
1.572     banghart 5975: sub files_in_path {
                   5976:     my ($user, $path) = @_;
                   5977:     my $filename = $user."savedfiles";
                   5978:     my %return_files;
1.574     banghart 5979:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5980:     while (my $line_in = <IN>) {
1.574     banghart 5981:         chomp ($line_in);
                   5982:         my @paths_and_file = split (m!/!, $line_in);
                   5983:         my $file_part = pop (@paths_and_file);
                   5984:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5985:         $path_part.='/';
                   5986:         my $path_and_file = $path_part.$file_part;
                   5987:         if ($path_part eq $path) {
                   5988:             $return_files{$file_part}= 'selected';
                   5989:         }
                   5990:     }
1.574     banghart 5991:     close (IN);
                   5992:     return (\%return_files);
1.572     banghart 5993: }
                   5994: 
                   5995: # called in portfolio select mode, to show files selected NOT in current directory
                   5996: sub files_not_in_path {
                   5997:     my ($user, $path) = @_;
                   5998:     my $filename = $user."savedfiles";
                   5999:     my @return_files;
                   6000:     my $path_part;
1.800     albertel 6001:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6002:     while (my $line = <IN>) {
1.572     banghart 6003:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6004:         my @paths_and_file = split(m|/|, $line);
                   6005:         my $file_part = pop(@paths_and_file);
                   6006:         chomp($file_part);
                   6007:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6008:         $path_part .= '/';
                   6009:         my $path_and_file = $path_part.$file_part;
                   6010:         if ($path_part ne $path) {
1.800     albertel 6011:             push(@return_files, ($path_and_file));
1.572     banghart 6012:         }
                   6013:     }
1.800     albertel 6014:     close(OUT);
1.574     banghart 6015:     return (@return_files);
1.572     banghart 6016: }
                   6017: 
1.745     raeburn  6018: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6019: 
1.745     raeburn  6020: sub get_portfile_permissions {
                   6021:     my ($domain,$user) = @_;
1.613     albertel 6022:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6023:     my ($tmp)=keys(%current_permissions);
                   6024:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6025:     return \%current_permissions;
                   6026: }
                   6027: 
                   6028: #---------------------------------------------Get portfolio file access controls
                   6029: 
1.749     raeburn  6030: sub get_access_controls {
1.745     raeburn  6031:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6032:     my %access;
                   6033:     my $real_file = $file;
                   6034:     $file =~ s/\.meta$//;
1.745     raeburn  6035:     if (defined($file)) {
1.749     raeburn  6036:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6037:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6038:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6039:             }
                   6040:         }
1.745     raeburn  6041:     } else {
1.749     raeburn  6042:         foreach my $key (keys(%{$current_permissions})) {
                   6043:             if ($key =~ /\0accesscontrol$/) {
                   6044:                 if (defined($group)) {
                   6045:                     if ($key !~ m-^\Q$group\E/-) {
                   6046:                         next;
                   6047:                     }
                   6048:                 }
                   6049:                 my ($fullpath) = split(/\0/,$key);
                   6050:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6051:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6052:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6053:                     }
                   6054:                 }
                   6055:             }
                   6056:         }
                   6057:     }
                   6058:     return %access;
                   6059: }
                   6060: 
                   6061: sub modify_access_controls {
                   6062:     my ($file_name,$changes,$domain,$user)=@_;
                   6063:     my ($outcome,$deloutcome);
                   6064:     my %store_permissions;
                   6065:     my %new_values;
                   6066:     my %new_control;
                   6067:     my %translation;
                   6068:     my @deletions = ();
                   6069:     my $now = time;
                   6070:     if (exists($$changes{'activate'})) {
                   6071:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6072:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6073:             my $numnew = scalar(@newitems);
                   6074:             for (my $i=0; $i<$numnew; $i++) {
                   6075:                 my $newkey = $newitems[$i];
                   6076:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6077:                 if ($newkey =~ /^\d+:/) { 
                   6078:                     $newkey =~ s/^(\d+)/$newid/;
                   6079:                     $translation{$1} = $newid;
                   6080:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6081:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6082:                     $translation{$1} = $newid;
                   6083:                 }
1.749     raeburn  6084:                 $new_values{$file_name."\0".$newkey} = 
                   6085:                                           $$changes{'activate'}{$newitems[$i]};
                   6086:                 $new_control{$newkey} = $now;
                   6087:             }
                   6088:         }
                   6089:     }
                   6090:     my %todelete;
                   6091:     my %changed_items;
                   6092:     foreach my $action ('delete','update') {
                   6093:         if (exists($$changes{$action})) {
                   6094:             if (ref($$changes{$action}) eq 'HASH') {
                   6095:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6096:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6097:                     if ($action eq 'delete') { 
                   6098:                         $todelete{$itemnum} = 1;
                   6099:                     } else {
                   6100:                         $changed_items{$itemnum} = $key;
                   6101:                     }
                   6102:                 }
1.745     raeburn  6103:             }
                   6104:         }
1.749     raeburn  6105:     }
                   6106:     # get lock on access controls for file.
                   6107:     my $lockhash = {
                   6108:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6109:                                                        ':'.$env{'user.domain'},
                   6110:                    }; 
                   6111:     my $tries = 0;
                   6112:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6113:    
                   6114:     while (($gotlock ne 'ok') && $tries <3) {
                   6115:         $tries ++;
                   6116:         sleep 1;
                   6117:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6118:     }
                   6119:     if ($gotlock eq 'ok') {
                   6120:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6121:         my ($tmp)=keys(%curr_permissions);
                   6122:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6123:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6124:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6125:             if (ref($curr_controls) eq 'HASH') {
                   6126:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6127:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6128:                     if (defined($todelete{$itemnum})) {
                   6129:                         push(@deletions,$file_name."\0".$control_item);
                   6130:                     } else {
                   6131:                         if (defined($changed_items{$itemnum})) {
                   6132:                             $new_control{$changed_items{$itemnum}} = $now;
                   6133:                             push(@deletions,$file_name."\0".$control_item);
                   6134:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6135:                         } else {
                   6136:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6137:                         }
                   6138:                     }
1.745     raeburn  6139:                 }
                   6140:             }
                   6141:         }
1.749     raeburn  6142:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6143:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6144:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6145:         #  remove lock
                   6146:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6147:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6148:         my ($file,$group);
                   6149:         if (&is_course($domain,$user)) {
                   6150:             ($group,$file) = split(/\//,$file_name,2);
                   6151:         } else {
                   6152:             $file = $file_name;
                   6153:         }
                   6154:         my $sqlresult =
                   6155:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6156:                                     $group);
1.749     raeburn  6157:     } else {
                   6158:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6159:     }
1.749     raeburn  6160:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6161: }
                   6162: 
1.827     raeburn  6163: sub make_public_indefinitely {
                   6164:     my ($requrl) = @_;
                   6165:     my $now = time;
                   6166:     my $action = 'activate';
                   6167:     my $aclnum = 0;
                   6168:     if (&is_portfolio_url($requrl)) {
                   6169:         my (undef,$udom,$unum,$file_name,$group) =
                   6170:             &parse_portfolio_url($requrl);
                   6171:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6172:         my %access_controls = &get_access_controls($current_perms,
                   6173:                                                    $group,$file_name);
                   6174:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6175:             my ($num,$scope,$end,$start) = 
                   6176:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6177:             if ($scope eq 'public') {
                   6178:                 if ($start <= $now && $end == 0) {
                   6179:                     $action = 'none';
                   6180:                 } else {
                   6181:                     $action = 'update';
                   6182:                     $aclnum = $num;
                   6183:                 }
                   6184:                 last;
                   6185:             }
                   6186:         }
                   6187:         if ($action eq 'none') {
                   6188:              return 'ok';
                   6189:         } else {
                   6190:             my %changes;
                   6191:             my $newend = 0;
                   6192:             my $newstart = $now;
                   6193:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6194:             $changes{$action}{$newkey} = {
                   6195:                 type => 'public',
                   6196:                 time => {
                   6197:                     start => $newstart,
                   6198:                     end   => $newend,
                   6199:                 },
                   6200:             };
                   6201:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6202:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6203:             return $outcome;
                   6204:         }
                   6205:     } else {
                   6206:         return 'invalid';
                   6207:     }
                   6208: }
                   6209: 
1.745     raeburn  6210: #------------------------------------------------------Get Marked as Read Only
                   6211: 
                   6212: sub get_marked_as_readonly {
                   6213:     my ($domain,$user,$what,$group) = @_;
                   6214:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6215:     my @readonly_files;
1.629     banghart 6216:     my $cmp1=$what;
                   6217:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6218:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6219:         if (defined($group)) {
                   6220:             if ($file_name !~ m-^\Q$group\E/-) {
                   6221:                 next;
                   6222:             }
                   6223:         }
1.561     banghart 6224:         if (ref($value) eq "ARRAY"){
                   6225:             foreach my $stored_what (@{$value}) {
1.629     banghart 6226:                 my $cmp2=$stored_what;
1.759     albertel 6227:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6228:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6229:                 }
1.629     banghart 6230:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6231:                     push(@readonly_files, $file_name);
1.745     raeburn  6232:                     last;
1.563     banghart 6233:                 } elsif (!defined($what)) {
                   6234:                     push(@readonly_files, $file_name);
1.745     raeburn  6235:                     last;
1.561     banghart 6236:                 }
                   6237:             }
1.745     raeburn  6238:         }
1.561     banghart 6239:     }
                   6240:     return @readonly_files;
                   6241: }
1.577     banghart 6242: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6243: 
1.577     banghart 6244: sub get_marked_as_readonly_hash {
1.745     raeburn  6245:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6246:     my %readonly_files;
1.745     raeburn  6247:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6248:         if (defined($group)) {
                   6249:             if ($file_name !~ m-^\Q$group\E/-) {
                   6250:                 next;
                   6251:             }
                   6252:         }
1.577     banghart 6253:         if (ref($value) eq "ARRAY"){
                   6254:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6255:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6256:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6257:                         if ($lock_descriptor eq 'graded') {
                   6258:                             $readonly_files{$file_name} = 'graded';
                   6259:                         } elsif ($lock_descriptor eq 'handback') {
                   6260:                             $readonly_files{$file_name} = 'handback';
                   6261:                         } else {
                   6262:                             if (!exists($readonly_files{$file_name})) {
                   6263:                                 $readonly_files{$file_name} = 'locked';
                   6264:                             }
                   6265:                         }
1.745     raeburn  6266:                     }
1.750     banghart 6267:                 } 
1.577     banghart 6268:             }
                   6269:         } 
                   6270:     }
                   6271:     return %readonly_files;
                   6272: }
1.559     banghart 6273: # ------------------------------------------------------------ Unmark as Read Only
                   6274: 
                   6275: sub unmark_as_readonly {
1.629     banghart 6276:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6277:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6278:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6279:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6280:     my $symb_crs = $what;
                   6281:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6282:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6283:     my ($tmp)=keys(%current_permissions);
                   6284:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6285:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6286:     foreach my $file (@readonly_files) {
1.759     albertel 6287: 	my $clean_file = &declutter_portfile($file);
                   6288: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6289: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6290:         my @new_locks;
                   6291:         my @del_keys;
                   6292:         if (ref($current_locks) eq "ARRAY"){
                   6293:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6294:                 my $compare=$locker;
1.749     raeburn  6295:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6296:                     $compare=join('',@{$locker});
1.746     raeburn  6297:                     if ($compare ne $symb_crs) {
                   6298:                         push(@new_locks, $locker);
                   6299:                     }
1.563     banghart 6300:                 }
                   6301:             }
1.650     albertel 6302:             if (scalar(@new_locks) > 0) {
1.563     banghart 6303:                 $current_permissions{$file} = \@new_locks;
                   6304:             } else {
                   6305:                 push(@del_keys, $file);
1.613     albertel 6306:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6307:                 delete($current_permissions{$file});
1.563     banghart 6308:             }
                   6309:         }
1.561     banghart 6310:     }
1.613     albertel 6311:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6312:     return;
                   6313: }
1.512     banghart 6314: 
1.17      www      6315: # ------------------------------------------------------------ Directory lister
                   6316: 
                   6317: sub dirlist {
1.955     raeburn  6318:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6319:     $uri=~s/^\///;
                   6320:     $uri=~s/\/$//;
1.253     stredwic 6321:     my ($udom, $uname);
1.955     raeburn  6322:     if ($getuserdir) {
1.253     stredwic 6323:         $udom = $userdomain;
                   6324:         $uname = $username;
1.955     raeburn  6325:     } else {
                   6326:         (undef,$udom,$uname)=split(/\//,$uri);
                   6327:         if(defined($userdomain)) {
                   6328:             $udom = $userdomain;
                   6329:         }
                   6330:         if(defined($username)) {
                   6331:             $uname = $username;
                   6332:         }
1.253     stredwic 6333:     }
1.955     raeburn  6334:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6335: 
1.955     raeburn  6336:     $dirRoot = $perlvar{'lonDocRoot'};
                   6337:     if (defined($getpropath)) {
                   6338:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6339:         $dirRoot =~ s/\/$//;
1.955     raeburn  6340:     } elsif (defined($getuserdir)) {
                   6341:         my $subdir=$uname.'__';
                   6342:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6343:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6344:                    ."/$udom/$subdir/$uname";
                   6345:     } elsif (defined($alternateRoot)) {
                   6346:         $dirRoot = $alternateRoot;
1.751     banghart 6347:     }
1.253     stredwic 6348: 
                   6349:     if($udom) {
                   6350:         if($uname) {
1.955     raeburn  6351:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6352:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6353:                               .':'.&escape($uname).':'.&escape($udom),
                   6354:                               &homeserver($uname,$udom));
                   6355:             if ($listing eq 'unknown_cmd') {
                   6356:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6357:                                   &homeserver($uname,$udom));
                   6358:             } else {
                   6359:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6360:             }
1.605     matthew  6361:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6362:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6363: 				  &homeserver($uname,$udom));
1.605     matthew  6364:                 @listing_results = split(/:/,$listing);
                   6365:             } else {
                   6366:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6367:             }
                   6368:             return @listing_results;
1.955     raeburn  6369:         } elsif(!$alternateRoot) {
1.800     albertel 6370:             my %allusers;
1.841     albertel 6371: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6372:  	    foreach my $tryserver (keys(%servers)) {
                   6373:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6374:                                   &escape($udom),$tryserver);
                   6375:                 if ($listing eq 'unknown_cmd') {
                   6376: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6377: 				      $udom, $tryserver);
                   6378:                 } else {
                   6379:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6380:                 }
1.841     albertel 6381: 		if ($listing eq 'unknown_cmd') {
                   6382: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6383: 				      $udom, $tryserver);
                   6384: 		    @listing_results = split(/:/,$listing);
                   6385: 		} else {
                   6386: 		    @listing_results =
                   6387: 			map { &unescape($_); } split(/:/,$listing);
                   6388: 		}
                   6389: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6390: 		    $listing_results[0] ne 'empty'       &&
                   6391: 		    $listing_results[0] ne 'con_lost') {
                   6392: 		    foreach my $line (@listing_results) {
                   6393: 			my ($entry) = split(/&/,$line,2);
                   6394: 			$allusers{$entry} = 1;
                   6395: 		    }
                   6396: 		}
1.253     stredwic 6397:             }
                   6398:             my $alluserstr='';
1.800     albertel 6399:             foreach my $user (sort(keys(%allusers))) {
                   6400:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6401:             }
                   6402:             $alluserstr=~s/:$//;
                   6403:             return split(/:/,$alluserstr);
                   6404:         } else {
1.800     albertel 6405:             return ('missing user name');
1.253     stredwic 6406:         }
1.955     raeburn  6407:     } elsif(!defined($getpropath)) {
1.841     albertel 6408:         my @all_domains = sort(&all_domains());
1.955     raeburn  6409:         foreach my $domain (@all_domains) {
                   6410:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6411:         }
                   6412:         return @all_domains;
                   6413:     } else {
1.800     albertel 6414:         return ('missing domain');
1.275     stredwic 6415:     }
                   6416: }
                   6417: 
                   6418: # --------------------------------------------- GetFileTimestamp
                   6419: # This function utilizes dirlist and returns the date stamp for
                   6420: # when it was last modified.  It will also return an error of -1
                   6421: # if an error occurs
                   6422: 
                   6423: sub GetFileTimestamp {
1.955     raeburn  6424:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6425:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6426:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6427:     my ($fileStat) = 
                   6428:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6429:                                  undef,$getuserdir);
1.275     stredwic 6430:     my @stats = split('&', $fileStat);
                   6431:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6432:         # @stats contains first the filename, then the stat output
                   6433:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6434:     } else {
                   6435:         return -1;
1.253     stredwic 6436:     }
1.26      www      6437: }
                   6438: 
1.712     albertel 6439: sub stat_file {
                   6440:     my ($uri) = @_;
1.787     albertel 6441:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6442: 
1.955     raeburn  6443:     my ($udom,$uname,$file);
1.712     albertel 6444:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6445: 	($udom,$uname,$file) =
1.811     albertel 6446: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6447: 	$file = 'userfiles/'.$file;
                   6448:     }
                   6449:     if ($uri =~ m-^/res/-) {
                   6450: 	($udom,$uname) = 
1.807     albertel 6451: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6452: 	$file = $uri;
                   6453:     }
                   6454: 
                   6455:     if (!$udom || !$uname || !$file) {
                   6456: 	# unable to handle the uri
                   6457: 	return ();
                   6458:     }
1.956     raeburn  6459:     my $getpropath;
                   6460:     if ($file =~ /^userfiles\//) {
                   6461:         $getpropath = 1;
                   6462:     }
1.955     raeburn  6463:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6464:     my @stats = split('&', $result);
1.721     banghart 6465:     
1.712     albertel 6466:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6467: 	shift(@stats); #filename is first
                   6468: 	return @stats;
                   6469:     }
                   6470:     return ();
                   6471: }
                   6472: 
1.26      www      6473: # -------------------------------------------------------- Value of a Condition
                   6474: 
1.713     albertel 6475: # gets the value of a specific preevaluated condition
                   6476: #    stored in the string  $env{user.state.<cid>}
                   6477: # or looks up a condition reference in the bighash and if if hasn't
                   6478: # already been evaluated recurses into docondval to get the value of
                   6479: # the condition, then memoizing it to 
                   6480: #   $env{user.state.<cid>.<condition>}
1.40      www      6481: sub directcondval {
                   6482:     my $number=shift;
1.620     albertel 6483:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6484: 	&Apache::lonuserstate::evalstate();
                   6485:     }
1.713     albertel 6486:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6487: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6488:     } elsif ($number =~ /^_/) {
                   6489: 	my $sub_condition;
                   6490: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6491: 		&GDBM_READER(),0640)) {
                   6492: 	    $sub_condition=$bighash{'conditions'.$number};
                   6493: 	    untie(%bighash);
                   6494: 	}
                   6495: 	my $value = &docondval($sub_condition);
1.949     raeburn  6496: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6497: 	return $value;
                   6498:     }
1.620     albertel 6499:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6500:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6501:     } else {
                   6502:        return 2;
                   6503:     }
                   6504: }
                   6505: 
1.713     albertel 6506: # get the collection of conditions for this resource
1.26      www      6507: sub condval {
                   6508:     my $condidx=shift;
1.54      www      6509:     my $allpathcond='';
1.713     albertel 6510:     foreach my $cond (split(/\|/,$condidx)) {
                   6511: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6512: 	    $allpathcond.=
                   6513: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6514: 	}
1.191     harris41 6515:     }
1.54      www      6516:     $allpathcond=~s/\|$//;
1.713     albertel 6517:     return &docondval($allpathcond);
                   6518: }
                   6519: 
                   6520: #evaluates an expression of conditions
                   6521: sub docondval {
                   6522:     my ($allpathcond) = @_;
                   6523:     my $result=0;
                   6524:     if ($env{'request.course.id'}
                   6525: 	&& defined($allpathcond)) {
                   6526: 	my $operand='|';
                   6527: 	my @stack;
                   6528: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6529: 	    if ($chunk eq '(') {
                   6530: 		push @stack,($operand,$result);
                   6531: 	    } elsif ($chunk eq ')') {
                   6532: 		my $before=pop @stack;
                   6533: 		if (pop @stack eq '&') {
                   6534: 		    $result=$result>$before?$before:$result;
                   6535: 		} else {
                   6536: 		    $result=$result>$before?$result:$before;
                   6537: 		}
                   6538: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6539: 		$operand=$chunk;
                   6540: 	    } else {
                   6541: 		my $new=directcondval($chunk);
                   6542: 		if ($operand eq '&') {
                   6543: 		    $result=$result>$new?$new:$result;
                   6544: 		} else {
                   6545: 		    $result=$result>$new?$result:$new;
                   6546: 		}
                   6547: 	    }
                   6548: 	}
1.26      www      6549:     }
                   6550:     return $result;
1.421     albertel 6551: }
                   6552: 
                   6553: # ---------------------------------------------------- Devalidate courseresdata
                   6554: 
                   6555: sub devalidatecourseresdata {
                   6556:     my ($coursenum,$coursedomain)=@_;
                   6557:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6558:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6559: }
                   6560: 
1.763     www      6561: 
1.200     www      6562: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6563: #
                   6564: #  Parameters:
                   6565: #      $coursenum    - Number of the course.
                   6566: #      $coursedomain - Domain at which the course was created.
                   6567: #  Returns:
                   6568: #     A hash of the course parameters along (I think) with timestamps
                   6569: #     and version info.
1.877     foxr     6570: 
1.624     albertel 6571: sub get_courseresdata {
                   6572:     my ($coursenum,$coursedomain)=@_;
1.200     www      6573:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6574:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6575:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6576:     my %dumpreply;
1.417     albertel 6577:     unless (defined($cached)) {
1.624     albertel 6578: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6579: 	$result=\%dumpreply;
1.251     albertel 6580: 	my ($tmp) = keys(%dumpreply);
                   6581: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6582: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6583: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6584: 	    return $tmp;
1.416     albertel 6585: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6586: 	    $result=undef;
1.599     albertel 6587: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6588: 	}
                   6589:     }
1.624     albertel 6590:     return $result;
                   6591: }
                   6592: 
1.633     albertel 6593: sub devalidateuserresdata {
                   6594:     my ($uname,$udom)=@_;
                   6595:     my $hashid="$udom:$uname";
                   6596:     &devalidate_cache_new('userres',$hashid);
                   6597: }
                   6598: 
1.624     albertel 6599: sub get_userresdata {
                   6600:     my ($uname,$udom)=@_;
                   6601:     #most student don\'t have any data set, check if there is some data
                   6602:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6603: 
                   6604:     my $hashid="$udom:$uname";
                   6605:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6606:     if (!defined($cached)) {
                   6607: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6608: 	$result=\%resourcedata;
                   6609: 	&do_cache_new('userres',$hashid,$result,600);
                   6610:     }
                   6611:     my ($tmp)=keys(%$result);
                   6612:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6613: 	return $result;
                   6614:     }
                   6615:     #error 2 occurs when the .db doesn't exist
                   6616:     if ($tmp!~/error: 2 /) {
1.672     albertel 6617: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6618: 		 " Trying to get resource data for ".
                   6619: 		 $uname." at ".$udom.": ".
                   6620: 		 $tmp."</font>");
                   6621:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6622: 	#&EXT_cache_set($udom,$uname);
                   6623: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6624: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6625:     }
                   6626:     return $tmp;
                   6627: }
1.879     foxr     6628: #----------------------------------------------- resdata - return resource data
                   6629: #  Purpose:
                   6630: #    Return resource data for either users or for a course.
                   6631: #  Parameters:
                   6632: #     $name      - Course/user name.
                   6633: #     $domain    - Name of the domain the user/course is registered on.
                   6634: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6635: #     @which     - Array of names of resources desired.
                   6636: #  Returns:
                   6637: #     The value of the first reasource in @which that is found in the
                   6638: #     resource hash.
                   6639: #  Exceptional Conditions:
                   6640: #     If the $type passed in is not valid (not the string 'course' or 
                   6641: #     'user', an undefined  reference is returned.
                   6642: #     If none of the resources are found, an undef is returned
1.624     albertel 6643: sub resdata {
                   6644:     my ($name,$domain,$type,@which)=@_;
                   6645:     my $result;
                   6646:     if ($type eq 'course') {
                   6647: 	$result=&get_courseresdata($name,$domain);
                   6648:     } elsif ($type eq 'user') {
                   6649: 	$result=&get_userresdata($name,$domain);
                   6650:     }
                   6651:     if (!ref($result)) { return $result; }    
1.251     albertel 6652:     foreach my $item (@which) {
1.927     albertel 6653: 	if (defined($result->{$item->[0]})) {
                   6654: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6655: 	}
1.250     albertel 6656:     }
1.291     albertel 6657:     return undef;
1.200     www      6658: }
                   6659: 
1.379     matthew  6660: #
                   6661: # EXT resource caching routines
                   6662: #
                   6663: 
                   6664: sub clear_EXT_cache_status {
1.383     albertel 6665:     &delenv('cache.EXT.');
1.379     matthew  6666: }
                   6667: 
                   6668: sub EXT_cache_status {
                   6669:     my ($target_domain,$target_user) = @_;
1.383     albertel 6670:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6671:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6672:         # We know already the user has no data
                   6673:         return 1;
                   6674:     } else {
                   6675:         return 0;
                   6676:     }
                   6677: }
                   6678: 
                   6679: sub EXT_cache_set {
                   6680:     my ($target_domain,$target_user) = @_;
1.383     albertel 6681:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6682:     #&appenv({$cachename => time});
1.379     matthew  6683: }
                   6684: 
1.28      www      6685: # --------------------------------------------------------- Value of a Variable
1.58      www      6686: sub EXT {
1.715     albertel 6687: 
1.395     albertel 6688:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6689:     unless ($varname) { return ''; }
1.218     albertel 6690:     #get real user name/domain, courseid and symb
                   6691:     my $courseid;
1.359     albertel 6692:     my $publicuser;
1.427     www      6693:     if ($symbparm) {
                   6694: 	$symbparm=&get_symb_from_alias($symbparm);
                   6695:     }
1.218     albertel 6696:     if (!($uname && $udom)) {
1.790     albertel 6697:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6698:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6699:     } else {
1.620     albertel 6700: 	$courseid=$env{'request.course.id'};
1.218     albertel 6701:     }
1.48      www      6702:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6703:     my $rest;
1.320     albertel 6704:     if (defined($therest[0])) {
1.48      www      6705:        $rest=join('.',@therest);
                   6706:     } else {
                   6707:        $rest='';
                   6708:     }
1.320     albertel 6709: 
1.57      www      6710:     my $qualifierrest=$qualifier;
                   6711:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6712:     my $spacequalifierrest=$space;
                   6713:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6714:     if ($realm eq 'user') {
1.48      www      6715: # --------------------------------------------------------------- user.resource
                   6716: 	if ($space eq 'resource') {
1.651     albertel 6717: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6718: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6719: 		 &&
1.744     albertel 6720: 		 ($symbparm eq &symbread()) ) {	
                   6721: 		# if we are in the middle of processing the resource the
                   6722: 		# get the value we are planning on committing
                   6723:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6724:                     return $Apache::lonhomework::results{$qualifierrest};
                   6725:                 } else {
                   6726:                     return $Apache::lonhomework::history{$qualifierrest};
                   6727:                 }
1.335     albertel 6728: 	    } else {
1.359     albertel 6729: 		my %restored;
1.620     albertel 6730: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6731: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6732: 		} else {
                   6733: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6734: 		}
1.335     albertel 6735: 		return $restored{$qualifierrest};
                   6736: 	    }
1.48      www      6737: # ----------------------------------------------------------------- user.access
                   6738:         } elsif ($space eq 'access') {
1.218     albertel 6739: 	    # FIXME - not supporting calls for a specific user
1.48      www      6740:             return &allowed($qualifier,$rest);
                   6741: # ------------------------------------------ user.preferences, user.environment
                   6742:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6743: 	    if (($uname eq $env{'user.name'}) &&
                   6744: 		($udom eq $env{'user.domain'})) {
                   6745: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6746: 	    } else {
1.359     albertel 6747: 		my %returnhash;
                   6748: 		if (!$publicuser) {
                   6749: 		    %returnhash=&userenvironment($udom,$uname,
                   6750: 						 $qualifierrest);
                   6751: 		}
1.218     albertel 6752: 		return $returnhash{$qualifierrest};
                   6753: 	    }
1.48      www      6754: # ----------------------------------------------------------------- user.course
                   6755:         } elsif ($space eq 'course') {
1.218     albertel 6756: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6757:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6758: # ------------------------------------------------------------------- user.role
                   6759:         } elsif ($space eq 'role') {
1.218     albertel 6760: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6761:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6762:             if ($qualifier eq 'value') {
                   6763: 		return $role;
                   6764:             } elsif ($qualifier eq 'extent') {
                   6765:                 return $where;
                   6766:             }
                   6767: # ----------------------------------------------------------------- user.domain
                   6768:         } elsif ($space eq 'domain') {
1.218     albertel 6769:             return $udom;
1.48      www      6770: # ------------------------------------------------------------------- user.name
                   6771:         } elsif ($space eq 'name') {
1.218     albertel 6772:             return $uname;
1.48      www      6773: # ---------------------------------------------------- Any other user namespace
1.29      www      6774:         } else {
1.359     albertel 6775: 	    my %reply;
                   6776: 	    if (!$publicuser) {
                   6777: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6778: 	    }
                   6779: 	    return $reply{$qualifierrest};
1.48      www      6780:         }
1.236     www      6781:     } elsif ($realm eq 'query') {
                   6782: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6783:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6784: 						[$spacequalifierrest]);
1.620     albertel 6785: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6786:    } elsif ($realm eq 'request') {
1.48      www      6787: # ------------------------------------------------------------- request.browser
                   6788:         if ($space eq 'browser') {
1.430     www      6789: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6790: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6791: 		    return 1;
                   6792: 		} else {
                   6793: 		    return 0;
                   6794: 		}
                   6795: 	    } else {
1.620     albertel 6796: 		return $env{'browser.'.$qualifier};
1.430     www      6797: 	    }
1.57      www      6798: # ------------------------------------------------------------ request.filename
                   6799:         } else {
1.620     albertel 6800:             return $env{'request.'.$spacequalifierrest};
1.29      www      6801:         }
1.28      www      6802:     } elsif ($realm eq 'course') {
1.48      www      6803: # ---------------------------------------------------------- course.description
1.620     albertel 6804:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6805:     } elsif ($realm eq 'resource') {
1.165     www      6806: 
1.620     albertel 6807: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6808: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6809: 	}
1.693     albertel 6810: 
                   6811: 	if ($space eq 'title') {
                   6812: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6813: 	    return &gettitle($symbparm);
                   6814: 	}
                   6815: 	
                   6816: 	if ($space eq 'map') {
                   6817: 	    my ($map) = &decode_symb($symbparm);
                   6818: 	    return &symbread($map);
                   6819: 	}
1.905     albertel 6820: 	if ($space eq 'filename') {
                   6821: 	    if ($symbparm) {
                   6822: 		return &clutter((&decode_symb($symbparm))[2]);
                   6823: 	    }
                   6824: 	    return &hreflocation('',$env{'request.filename'});
                   6825: 	}
1.693     albertel 6826: 
                   6827: 	my ($section, $group, @groups);
1.593     albertel 6828: 	my ($courselevelm,$courselevel);
1.539     albertel 6829: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6830: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6831: 
1.218     albertel 6832: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6833: 
1.60      www      6834: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6835: 	    my $symbp=$symbparm;
1.735     albertel 6836: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6837: 
                   6838: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6839: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6840: 
1.620     albertel 6841: 	    if (($env{'user.name'} eq $uname) &&
                   6842: 		($env{'user.domain'} eq $udom)) {
                   6843: 		$section=$env{'request.course.sec'};
1.733     raeburn  6844:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6845:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6846: 	    } else {
1.539     albertel 6847: 		if (! defined($usection)) {
1.551     albertel 6848: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6849: 		} else {
                   6850: 		    $section = $usection;
                   6851: 		}
1.733     raeburn  6852:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6853: 	    }
                   6854: 
                   6855: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6856: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6857: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6858: 
1.593     albertel 6859: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6860: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6861: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6862: 
1.60      www      6863: # ----------------------------------------------------------- first, check user
1.624     albertel 6864: 
                   6865: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6866: 				       ([$courselevelr,'resource'],
                   6867: 					[$courselevelm,'map'     ],
                   6868: 					[$courselevel, 'course'  ]));
1.931     albertel 6869: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6870: 
1.594     albertel 6871: # ------------------------------------------------ second, check some of course
1.684     raeburn  6872:             my $coursereply;
1.691     raeburn  6873:             if (@groups > 0) {
                   6874:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6875:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6876:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6877:             }
1.96      www      6878: 
1.684     raeburn  6879: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6880: 				  $env{'course.'.$courseid.'.domain'},
                   6881: 				  'course',
                   6882: 				  ([$seclevelr,   'resource'],
                   6883: 				   [$seclevelm,   'map'     ],
                   6884: 				   [$seclevel,    'course'  ],
                   6885: 				   [$courselevelr,'resource']));
                   6886: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6887: 
1.60      www      6888: # ------------------------------------------------------ third, check map parms
1.218     albertel 6889: 	    my %parmhash=();
                   6890: 	    my $thisparm='';
                   6891: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6892: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6893: 		    &GDBM_READER(),0640)) {
1.218     albertel 6894: 		$thisparm=$parmhash{$symbparm};
                   6895: 		untie(%parmhash);
                   6896: 	    }
1.927     albertel 6897: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6898: 	}
1.594     albertel 6899: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6900: 
1.218     albertel 6901: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6902: 	my $filename;
                   6903: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6904: 	if ($symbparm) {
1.409     www      6905: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6906: 	} else {
1.620     albertel 6907: 	    $filename=$env{'request.filename'};
1.282     albertel 6908: 	}
                   6909: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6910: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6911: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6912: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6913: 
1.927     albertel 6914: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6915: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6916: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6917: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6918: 				     $env{'course.'.$courseid.'.domain'},
                   6919: 				     'course',
1.927     albertel 6920: 				     ([$courselevelm,'map'   ],
                   6921: 				      [$courselevel, 'course']));
                   6922: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6923: 	}
1.145     www      6924: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6925: 	unless ($space eq '0') {
1.336     albertel 6926: 	    my @parts=split(/_/,$space);
                   6927: 	    my $id=pop(@parts);
                   6928: 	    my $part=join('_',@parts);
                   6929: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6930: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6931: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6932: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6933: 	}
1.395     albertel 6934: 	if ($recurse) { return undef; }
                   6935: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6936: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6937: # ---------------------------------------------------- Any other user namespace
                   6938:     } elsif ($realm eq 'environment') {
                   6939: # ----------------------------------------------------------------- environment
1.620     albertel 6940: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6941: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6942: 	} else {
1.770     albertel 6943: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6944: 		return '';
                   6945: 	    }
1.219     albertel 6946: 	    my %returnhash=&userenvironment($udom,$uname,
                   6947: 					    $spacequalifierrest);
                   6948: 	    return $returnhash{$spacequalifierrest};
                   6949: 	}
1.28      www      6950:     } elsif ($realm eq 'system') {
1.48      www      6951: # ----------------------------------------------------------------- system.time
                   6952: 	if ($space eq 'time') {
                   6953: 	    return time;
                   6954:         }
1.696     albertel 6955:     } elsif ($realm eq 'server') {
                   6956: # ----------------------------------------------------------------- system.time
                   6957: 	if ($space eq 'name') {
                   6958: 	    return $ENV{'SERVER_NAME'};
                   6959:         }
1.28      www      6960:     }
1.48      www      6961:     return '';
1.61      www      6962: }
                   6963: 
1.927     albertel 6964: sub get_reply {
                   6965:     my ($reply_value) = @_;
1.940     raeburn  6966:     if (ref($reply_value) eq 'ARRAY') {
                   6967:         if (wantarray) {
                   6968: 	    return @$reply_value;
                   6969:         }
                   6970:         return $reply_value->[0];
                   6971:     } else {
                   6972:         return $reply_value;
1.927     albertel 6973:     }
                   6974: }
                   6975: 
1.691     raeburn  6976: sub check_group_parms {
                   6977:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6978:     my @groupitems = ();
                   6979:     my $resultitem;
1.927     albertel 6980:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6981:     foreach my $group (@{$groups}) {
                   6982:         foreach my $level (@levels) {
1.927     albertel 6983:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6984:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6985:         }
                   6986:     }
                   6987:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6988:                             $env{'course.'.$courseid.'.domain'},
                   6989:                                      'course',@groupitems);
                   6990:     return $coursereply;
                   6991: }
                   6992: 
                   6993: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6994:     my ($courseid,@groups) = @_;
                   6995:     @groups = sort(@groups);
1.691     raeburn  6996:     return @groups;
                   6997: }
                   6998: 
1.395     albertel 6999: sub packages_tab_default {
                   7000:     my ($uri,$varname)=@_;
                   7001:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7002: 
                   7003:     my (@extension,@specifics,$do_default);
                   7004:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7005: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7006: 	if ($pack_type eq 'default') {
                   7007: 	    $do_default=1;
                   7008: 	} elsif ($pack_type eq 'extension') {
                   7009: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7010: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7011: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7012: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7013: 	}
                   7014:     }
                   7015:     # first look for a package that matches the requested part id
                   7016:     foreach my $package (@specifics) {
                   7017: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7018: 	next if ($pack_part ne $part);
                   7019: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7020: 	    return $packagetab{"$pack_type&$name&default"};
                   7021: 	}
                   7022:     }
                   7023:     # look for any possible matching non extension_ package
                   7024:     foreach my $package (@specifics) {
                   7025: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7026: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7027: 	    return $packagetab{"$pack_type&$name&default"};
                   7028: 	}
1.585     albertel 7029: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7030: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7031: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7032: 	}
                   7033:     }
1.738     albertel 7034:     # look for any posible extension_ match
                   7035:     foreach my $package (@extension) {
                   7036: 	my ($package,$pack_type)=@{$package};
                   7037: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7038: 	    return $packagetab{"$pack_type&$name&default"};
                   7039: 	}
                   7040: 	if (defined($packagetab{$package."&$name&default"})) {
                   7041: 	    return $packagetab{$package."&$name&default"};
                   7042: 	}
                   7043:     }
                   7044:     # look for a global default setting
                   7045:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7046: 	return $packagetab{"default&$name&default"};
                   7047:     }
1.395     albertel 7048:     return undef;
                   7049: }
                   7050: 
1.334     albertel 7051: sub add_prefix_and_part {
                   7052:     my ($prefix,$part)=@_;
                   7053:     my $keyroot;
                   7054:     if (defined($prefix) && $prefix !~ /^__/) {
                   7055: 	# prefix that has a part already
                   7056: 	$keyroot=$prefix;
                   7057:     } elsif (defined($prefix)) {
                   7058: 	# prefix that is missing a part
                   7059: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7060:     } else {
                   7061: 	# no prefix at all
                   7062: 	if (defined($part)) { $keyroot='_'.$part; }
                   7063:     }
                   7064:     return $keyroot;
                   7065: }
                   7066: 
1.71      www      7067: # ---------------------------------------------------------------- Get metadata
                   7068: 
1.599     albertel 7069: my %metaentry;
1.71      www      7070: sub metadata {
1.176     www      7071:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7072:     $uri=&declutter($uri);
1.288     albertel 7073:     # if it is a non metadata possible uri return quickly
1.529     albertel 7074:     if (($uri eq '') || 
                   7075: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7076: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7077:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7078: 	return undef;
                   7079:     }
                   7080:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7081: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7082: 	return undef;
1.288     albertel 7083:     }
1.73      www      7084:     my $filename=$uri;
                   7085:     $uri=~s/\.meta$//;
1.172     www      7086: #
                   7087: # Is the metadata already cached?
1.177     www      7088: # Look at timestamp of caching
1.172     www      7089: # Everything is cached by the main uri, libraries are never directly cached
                   7090: #
1.428     albertel 7091:     if (!defined($liburi)) {
1.599     albertel 7092: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7093: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7094:     }
                   7095:     {
1.172     www      7096: #
                   7097: # Is this a recursive call for a library?
                   7098: #
1.599     albertel 7099: #	if (! exists($metacache{$uri})) {
                   7100: #	    $metacache{$uri}={};
                   7101: #	}
1.924     albertel 7102: 	my $cachetime = 60*60;
1.171     www      7103:         if ($liburi) {
                   7104: 	    $liburi=&declutter($liburi);
                   7105:             $filename=$liburi;
1.401     bowersj2 7106:         } else {
1.599     albertel 7107: 	    &devalidate_cache_new('meta',$uri);
                   7108: 	    undef(%metaentry);
1.401     bowersj2 7109: 	}
1.140     www      7110:         my %metathesekeys=();
1.73      www      7111:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7112: 	my $metastring;
1.924     albertel 7113: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7114: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7115: 	    $metastring = 
1.929     albertel 7116: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7117: 					  ('grade_target' => 'meta'));
                   7118: 	    $cachetime = 1; # only want this cached in the child not long term
                   7119: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7120: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7121: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7122: 	    $metastring=&getfile($file);
1.489     albertel 7123: 	}
1.208     albertel 7124:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7125:         my $token;
1.140     www      7126:         undef %metathesekeys;
1.71      www      7127:         while ($token=$parser->get_token) {
1.339     albertel 7128: 	    if ($token->[0] eq 'S') {
                   7129: 		if (defined($token->[2]->{'package'})) {
1.172     www      7130: #
                   7131: # This is a package - get package info
                   7132: #
1.339     albertel 7133: 		    my $package=$token->[2]->{'package'};
                   7134: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7135: 		    if (defined($token->[2]->{'id'})) { 
                   7136: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7137: 		    }
1.599     albertel 7138: 		    if ($metaentry{':packages'}) {
                   7139: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7140: 		    } else {
1.599     albertel 7141: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7142: 		    }
1.736     albertel 7143: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7144: 			my $part=$keyroot;
                   7145: 			$part=~s/^\_//;
1.736     albertel 7146: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7147: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7148: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7149: 			    # ignore package.tab specified default values
                   7150:                             # here &package_tab_default() will fetch those
                   7151: 			    if ($subp eq 'default') { next; }
1.736     albertel 7152: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7153: 			    my $unikey;
                   7154: 			    if ($pack =~ /_0$/) {
                   7155: 				$unikey='parameter_0_'.$name;
                   7156: 				$part=0;
                   7157: 			    } else {
                   7158: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7159: 			    }
1.339     albertel 7160: 			    if ($subp eq 'display') {
                   7161: 				$value.=' [Part: '.$part.']';
                   7162: 			    }
1.599     albertel 7163: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7164: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7165: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7166: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7167: 			    }
1.599     albertel 7168: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7169: 				$metaentry{':'.$unikey}=
                   7170: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7171: 			    }
1.339     albertel 7172: 			}
                   7173: 		    }
                   7174: 		} else {
1.172     www      7175: #
                   7176: # This is not a package - some other kind of start tag
1.339     albertel 7177: #
                   7178: 		    my $entry=$token->[1];
                   7179: 		    my $unikey;
                   7180: 		    if ($entry eq 'import') {
                   7181: 			$unikey='';
                   7182: 		    } else {
                   7183: 			$unikey=$entry;
                   7184: 		    }
                   7185: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7186: 
                   7187: 		    if (defined($token->[2]->{'id'})) { 
                   7188: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7189: 		    }
1.175     www      7190: 
1.339     albertel 7191: 		    if ($entry eq 'import') {
1.175     www      7192: #
                   7193: # Importing a library here
1.339     albertel 7194: #
                   7195: 			if ($depthcount<20) {
                   7196: 			    my $location=$parser->get_text('/import');
                   7197: 			    my $dir=$filename;
                   7198: 			    $dir=~s|[^/]*$||;
                   7199: 			    $location=&filelocation($dir,$location);
1.736     albertel 7200: 			    my $metadata = 
                   7201: 				&metadata($uri,'keys', $location,$unikey,
                   7202: 					  $depthcount+1);
                   7203: 			    foreach my $meta (split(',',$metadata)) {
                   7204: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7205: 				$metathesekeys{$meta}=1;
1.339     albertel 7206: 			    }
                   7207: 			}
                   7208: 		    } else { 
                   7209: 			
                   7210: 			if (defined($token->[2]->{'name'})) { 
                   7211: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7212: 			}
                   7213: 			$metathesekeys{$unikey}=1;
1.736     albertel 7214: 			foreach my $param (@{$token->[3]}) {
                   7215: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7216: 				$token->[2]->{$param};
1.339     albertel 7217: 			}
                   7218: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7219: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7220: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7221: 		 # only ws inside the tag, and not in default, so use default
                   7222: 		 # as value
1.599     albertel 7223: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7224: 			} elsif ( $internaltext =~ /\S/ ) {
                   7225: 		  # something interesting inside the tag
                   7226: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7227: 			} else {
1.908     albertel 7228: 		  # no interesting values, don't set a default
1.339     albertel 7229: 			}
1.172     www      7230: # end of not-a-package not-a-library import
1.339     albertel 7231: 		    }
1.172     www      7232: # end of not-a-package start tag
1.339     albertel 7233: 		}
1.172     www      7234: # the next is the end of "start tag"
1.339     albertel 7235: 	    }
                   7236: 	}
1.483     albertel 7237: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7238: 	$extension = lc($extension);
                   7239: 	if ($extension eq 'htm') { $extension='html'; }
                   7240: 
1.737     albertel 7241: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7242: 	    #no specific packages #how's our extension
                   7243: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7244: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7245: 					 \%metathesekeys);
                   7246: 	}
1.883     albertel 7247: 
                   7248: 	if (!exists($metaentry{':packages'})
                   7249: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7250: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7251: 		#no specific packages well let's get default then
                   7252: 		if ($key!~/^default&/) { next; }
1.488     albertel 7253: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7254: 					     \%metathesekeys);
                   7255: 	    }
                   7256: 	}
1.338     www      7257: # are there custom rights to evaluate
1.599     albertel 7258: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7259: 
1.338     www      7260:     #
                   7261:     # Importing a rights file here
1.339     albertel 7262:     #
                   7263: 	    unless ($depthcount) {
1.599     albertel 7264: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7265: 		my $dir=$filename;
                   7266: 		$dir=~s|[^/]*$||;
                   7267: 		$location=&filelocation($dir,$location);
1.736     albertel 7268: 		my $rights_metadata =
                   7269: 		    &metadata($uri,'keys',$location,'_rights',
                   7270: 			      $depthcount+1);
                   7271: 		foreach my $rights (split(',',$rights_metadata)) {
                   7272: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7273: 		    $metathesekeys{$rights}=1;
1.339     albertel 7274: 		}
                   7275: 	    }
                   7276: 	}
1.737     albertel 7277: 	# uniqifiy package listing
                   7278: 	my %seen;
                   7279: 	my @uniq_packages =
                   7280: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7281: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7282: 
                   7283: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7284: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7285: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7286: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7287: # this is the end of "was not already recently cached
1.71      www      7288:     }
1.599     albertel 7289:     return $metaentry{':'.$what};
1.261     albertel 7290: }
                   7291: 
1.488     albertel 7292: sub metadata_create_package_def {
1.483     albertel 7293:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7294:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7295:     if ($subp eq 'default') { next; }
                   7296:     
1.599     albertel 7297:     if (defined($metaentry{':packages'})) {
                   7298: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7299:     } else {
1.599     albertel 7300: 	$metaentry{':packages'}=$package;
1.483     albertel 7301:     }
                   7302:     my $value=$packagetab{$key};
                   7303:     my $unikey;
                   7304:     $unikey='parameter_0_'.$name;
1.599     albertel 7305:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7306:     $$metathesekeys{$unikey}=1;
1.599     albertel 7307:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7308: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7309:     }
1.599     albertel 7310:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7311: 	$metaentry{':'.$unikey}=
                   7312: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7313:     }
                   7314: }
                   7315: 
1.261     albertel 7316: sub metadata_generate_part0 {
                   7317:     my ($metadata,$metacache,$uri) = @_;
                   7318:     my %allnames;
1.737     albertel 7319:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7320: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7321: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7322: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7323: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7324: 	    $allnames{$name}=$part;
                   7325: 	  }
                   7326: 	}
                   7327:     }
                   7328:     foreach my $name (keys(%allnames)) {
                   7329:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7330:       my $key=":parameter_0_$name";
1.261     albertel 7331:       $$metacache{"$key.part"}='0';
                   7332:       $$metacache{"$key.name"}=$name;
1.428     albertel 7333:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7334: 					   $allnames{$name}.'_'.$name.
                   7335: 					   '.type'};
1.428     albertel 7336:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7337: 			     '.display'};
1.644     www      7338:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7339:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7340:       $$metacache{"$key.display"}=$olddis;
                   7341:     }
1.71      www      7342: }
                   7343: 
1.764     albertel 7344: # ------------------------------------------------------ Devalidate title cache
                   7345: 
                   7346: sub devalidate_title_cache {
                   7347:     my ($url)=@_;
                   7348:     if (!$env{'request.course.id'}) { return; }
                   7349:     my $symb=&symbread($url);
                   7350:     if (!$symb) { return; }
                   7351:     my $key=$env{'request.course.id'}."\0".$symb;
                   7352:     &devalidate_cache_new('title',$key);
                   7353: }
                   7354: 
1.301     www      7355: # ------------------------------------------------- Get the title of a resource
                   7356: 
                   7357: sub gettitle {
                   7358:     my $urlsymb=shift;
                   7359:     my $symb=&symbread($urlsymb);
1.534     albertel 7360:     if ($symb) {
1.620     albertel 7361: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7362: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7363: 	if (defined($cached)) { 
                   7364: 	    return $result;
                   7365: 	}
1.534     albertel 7366: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7367: 	my $title='';
1.907     albertel 7368: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7369: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7370: 	} else {
                   7371: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7372: 		    &GDBM_READER(),0640)) {
                   7373: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7374: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7375: 		untie(%bighash);
                   7376: 	    }
1.534     albertel 7377: 	}
                   7378: 	$title=~s/\&colon\;/\:/gs;
                   7379: 	if ($title) {
1.599     albertel 7380: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7381: 	}
                   7382: 	$urlsymb=$url;
                   7383:     }
                   7384:     my $title=&metadata($urlsymb,'title');
                   7385:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7386:     return $title;
1.301     www      7387: }
1.613     albertel 7388: 
1.614     albertel 7389: sub get_slot {
                   7390:     my ($which,$cnum,$cdom)=@_;
                   7391:     if (!$cnum || !$cdom) {
1.790     albertel 7392: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7393: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7394: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7395:     }
1.703     albertel 7396:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7397:     my %slotinfo;
                   7398:     if (exists($remembered{$key})) {
                   7399: 	$slotinfo{$which} = $remembered{$key};
                   7400:     } else {
                   7401: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7402: 	&Apache::lonhomework::showhash(%slotinfo);
                   7403: 	my ($tmp)=keys(%slotinfo);
                   7404: 	if ($tmp=~/^error:/) { return (); }
                   7405: 	$remembered{$key} = $slotinfo{$which};
                   7406:     }
1.616     albertel 7407:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7408: 	return %{$slotinfo{$which}};
                   7409:     }
                   7410:     return $slotinfo{$which};
1.614     albertel 7411: }
1.31      www      7412: # ------------------------------------------------- Update symbolic store links
                   7413: 
                   7414: sub symblist {
                   7415:     my ($mapname,%newhash)=@_;
1.438     www      7416:     $mapname=&deversion(&declutter($mapname));
1.31      www      7417:     my %hash;
1.620     albertel 7418:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7419:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7420:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7421: 	    foreach my $url (keys %newhash) {
                   7422: 		next if ($url eq 'last_known'
                   7423: 			 && $env{'form.no_update_last_known'});
                   7424: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7425: 						    $newhash{$url}->[1],
                   7426: 						    $newhash{$url}->[0]);
1.191     harris41 7427:             }
1.31      www      7428:             if (untie(%hash)) {
                   7429: 		return 'ok';
                   7430:             }
                   7431:         }
                   7432:     }
                   7433:     return 'error';
1.212     www      7434: }
                   7435: 
                   7436: # --------------------------------------------------------------- Verify a symb
                   7437: 
                   7438: sub symbverify {
1.510     www      7439:     my ($symb,$thisurl)=@_;
                   7440:     my $thisfn=$thisurl;
1.439     www      7441:     $thisfn=&declutter($thisfn);
1.215     www      7442: # direct jump to resource in page or to a sequence - will construct own symbs
                   7443:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7444: # check URL part
1.409     www      7445:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7446: 
1.431     www      7447:     unless ($url eq $thisfn) { return 0; }
1.213     www      7448: 
1.216     www      7449:     $symb=&symbclean($symb);
1.510     www      7450:     $thisurl=&deversion($thisurl);
1.439     www      7451:     $thisfn=&deversion($thisfn);
1.213     www      7452: 
                   7453:     my %bighash;
                   7454:     my $okay=0;
1.431     www      7455: 
1.620     albertel 7456:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7457:                             &GDBM_READER(),0640)) {
1.510     www      7458:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7459:         unless ($ids) { 
1.510     www      7460:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7461:         }
                   7462:         if ($ids) {
                   7463: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7464: 	    foreach my $id (split(/\,/,$ids)) {
                   7465: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7466:                if (
                   7467:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7468:    eq $symb) { 
1.620     albertel 7469: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7470: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7471: 		       $okay=1; 
                   7472: 		   }
                   7473: 	       }
1.216     www      7474: 	   }
                   7475:         }
1.213     www      7476: 	untie(%bighash);
                   7477:     }
                   7478:     return $okay;
1.31      www      7479: }
                   7480: 
1.210     www      7481: # --------------------------------------------------------------- Clean-up symb
                   7482: 
                   7483: sub symbclean {
                   7484:     my $symb=shift;
1.568     albertel 7485:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7486: # remove version from map
                   7487:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7488: 
1.210     www      7489: # remove version from URL
                   7490:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7491: 
1.507     www      7492: # remove wrapper
                   7493: 
1.510     www      7494:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7495:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7496:     return $symb;
1.409     www      7497: }
                   7498: 
                   7499: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7500: 
                   7501: sub encode_symb {
                   7502:     my ($map,$resid,$url)=@_;
                   7503:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7504: }
1.409     www      7505: 
                   7506: sub decode_symb {
1.568     albertel 7507:     my $symb=shift;
                   7508:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7509:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7510:     return (&fixversion($map),$resid,&fixversion($url));
                   7511: }
                   7512: 
                   7513: sub fixversion {
                   7514:     my $fn=shift;
1.609     banghart 7515:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7516:     my %bighash;
                   7517:     my $uri=&clutter($fn);
1.620     albertel 7518:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7519: # is this cached?
1.599     albertel 7520:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7521:     if (defined($cached)) { return $result; }
                   7522: # unfortunately not cached, or expired
1.620     albertel 7523:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7524: 	    &GDBM_READER(),0640)) {
                   7525:  	if ($bighash{'version_'.$uri}) {
                   7526:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7527:  	    unless (($version eq 'mostrecent') || 
                   7528: 		    ($version==&getversion($uri))) {
1.440     www      7529:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7530:  	    }
                   7531:  	}
                   7532:  	untie %bighash;
1.413     www      7533:     }
1.599     albertel 7534:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7535: }
                   7536: 
                   7537: sub deversion {
                   7538:     my $url=shift;
                   7539:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7540:     return $url;
1.210     www      7541: }
                   7542: 
1.31      www      7543: # ------------------------------------------------------ Return symb list entry
                   7544: 
                   7545: sub symbread {
1.249     www      7546:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7547:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7548:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7549: # no filename provided? try from environment
1.44      www      7550:     unless ($thisfn) {
1.620     albertel 7551:         if ($env{'request.symb'}) {
                   7552: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7553: 	}
1.620     albertel 7554: 	$thisfn=$env{'request.filename'};
1.44      www      7555:     }
1.569     albertel 7556:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7557: # is that filename actually a symb? Verify, clean, and return
                   7558:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7559: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7560: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7561: 	}
1.242     www      7562:     }
1.44      www      7563:     $thisfn=declutter($thisfn);
1.31      www      7564:     my %hash;
1.37      www      7565:     my %bighash;
                   7566:     my $syval='';
1.620     albertel 7567:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7568:         my $targetfn = $thisfn;
1.609     banghart 7569:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7570:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7571:         }
1.687     albertel 7572: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7573: 	    $targetfn=$1;
                   7574: 	}
1.620     albertel 7575:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7576:                       &GDBM_READER(),0640)) {
1.481     raeburn  7577: 	    $syval=$hash{$targetfn};
1.37      www      7578:             untie(%hash);
                   7579:         }
                   7580: # ---------------------------------------------------------- There was an entry
                   7581:         if ($syval) {
1.601     albertel 7582: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7583: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7584: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7585: 		    #return $env{$cache_str}='';
1.601     albertel 7586: 		#}    
                   7587: 		#$syval.=$1;
                   7588: 	    #}
1.37      www      7589:         } else {
                   7590: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7591:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7592:                             &GDBM_READER(),0640)) {
1.37      www      7593: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7594:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7595:               unless ($ids) { 
                   7596:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7597:               }
                   7598:               unless ($ids) {
                   7599: # alias?
                   7600: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7601:               }
1.37      www      7602:               if ($ids) {
                   7603: # ------------------------------------------------------------------- Has ID(s)
                   7604:                  my @possibilities=split(/\,/,$ids);
1.39      www      7605:                  if ($#possibilities==0) {
                   7606: # ----------------------------------------------- There is only one possibility
1.37      www      7607: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7608: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7609: 						    $resid,$thisfn);
1.249     www      7610:                  } elsif (!$donotrecurse) {
1.39      www      7611: # ------------------------------------------ There is more than one possibility
                   7612:                      my $realpossible=0;
1.800     albertel 7613:                      foreach my $id (@possibilities) {
                   7614: 			 my $file=$bighash{'src_'.$id};
1.39      www      7615:                          if (&allowed('bre',$file)) {
1.800     albertel 7616:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7617:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7618: 				$realpossible++;
1.626     albertel 7619:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7620: 						    $resid,$thisfn);
1.39      www      7621:                             }
                   7622: 			 }
1.191     harris41 7623:                      }
1.39      www      7624: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7625:                  } else {
                   7626:                      $syval='';
1.37      www      7627:                  }
                   7628: 	      }
                   7629:               untie(%bighash)
1.481     raeburn  7630:            }
1.31      www      7631:         }
1.62      www      7632:         if ($syval) {
1.620     albertel 7633: 	    return $env{$cache_str}=$syval;
1.62      www      7634:         }
1.31      www      7635:     }
1.949     raeburn  7636:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7637:     return $env{$cache_str}='';
1.31      www      7638: }
                   7639: 
                   7640: # ---------------------------------------------------------- Return random seed
                   7641: 
1.32      www      7642: sub numval {
                   7643:     my $txt=shift;
                   7644:     $txt=~tr/A-J/0-9/;
                   7645:     $txt=~tr/a-j/0-9/;
                   7646:     $txt=~tr/K-T/0-9/;
                   7647:     $txt=~tr/k-t/0-9/;
                   7648:     $txt=~tr/U-Z/0-5/;
                   7649:     $txt=~tr/u-z/0-5/;
                   7650:     $txt=~s/\D//g;
1.564     albertel 7651:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7652:     return int($txt);
1.368     albertel 7653: }
                   7654: 
1.484     albertel 7655: sub numval2 {
                   7656:     my $txt=shift;
                   7657:     $txt=~tr/A-J/0-9/;
                   7658:     $txt=~tr/a-j/0-9/;
                   7659:     $txt=~tr/K-T/0-9/;
                   7660:     $txt=~tr/k-t/0-9/;
                   7661:     $txt=~tr/U-Z/0-5/;
                   7662:     $txt=~tr/u-z/0-5/;
                   7663:     $txt=~s/\D//g;
                   7664:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7665:     my $total;
                   7666:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7667:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7668:     return int($total);
                   7669: }
                   7670: 
1.575     albertel 7671: sub numval3 {
                   7672:     use integer;
                   7673:     my $txt=shift;
                   7674:     $txt=~tr/A-J/0-9/;
                   7675:     $txt=~tr/a-j/0-9/;
                   7676:     $txt=~tr/K-T/0-9/;
                   7677:     $txt=~tr/k-t/0-9/;
                   7678:     $txt=~tr/U-Z/0-5/;
                   7679:     $txt=~tr/u-z/0-5/;
                   7680:     $txt=~s/\D//g;
                   7681:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7682:     my $total;
                   7683:     foreach my $val (@txts) { $total+=$val; }
                   7684:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7685:     return $total;
                   7686: }
                   7687: 
1.675     albertel 7688: sub digest {
                   7689:     my ($data)=@_;
                   7690:     my $digest=&Digest::MD5::md5($data);
                   7691:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7692:     my ($e,$f);
                   7693:     {
                   7694:         use integer;
                   7695:         $e=($a+$b);
                   7696:         $f=($c+$d);
                   7697:         if ($_64bit) {
                   7698:             $e=(($e<<32)>>32);
                   7699:             $f=(($f<<32)>>32);
                   7700:         }
                   7701:     }
                   7702:     if (wantarray) {
                   7703: 	return ($e,$f);
                   7704:     } else {
                   7705: 	my $g;
                   7706: 	{
                   7707: 	    use integer;
                   7708: 	    $g=($e+$f);
                   7709: 	    if ($_64bit) {
                   7710: 		$g=(($g<<32)>>32);
                   7711: 	    }
                   7712: 	}
                   7713: 	return $g;
                   7714:     }
                   7715: }
                   7716: 
1.368     albertel 7717: sub latest_rnd_algorithm_id {
1.675     albertel 7718:     return '64bit5';
1.366     albertel 7719: }
1.32      www      7720: 
1.503     albertel 7721: sub get_rand_alg {
                   7722:     my ($courseid)=@_;
1.790     albertel 7723:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7724:     if ($courseid) {
1.620     albertel 7725: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7726:     }
                   7727:     return &latest_rnd_algorithm_id();
                   7728: }
                   7729: 
1.562     albertel 7730: sub validCODE {
                   7731:     my ($CODE)=@_;
                   7732:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7733:     return 0;
                   7734: }
                   7735: 
1.491     albertel 7736: sub getCODE {
1.620     albertel 7737:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7738:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7739: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7740: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7741: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7742:     }
                   7743:     return undef;
                   7744: }
                   7745: 
1.31      www      7746: sub rndseed {
1.155     albertel 7747:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7748:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7749:     if (!defined($symb)) {
1.366     albertel 7750: 	unless ($symb=$wsymb) { return time; }
                   7751:     }
                   7752:     if (!$courseid) { $courseid=$wcourseid; }
                   7753:     if (!$domain) { $domain=$wdomain; }
                   7754:     if (!$username) { $username=$wusername }
1.503     albertel 7755:     my $which=&get_rand_alg();
1.803     albertel 7756: 
1.491     albertel 7757:     if (defined(&getCODE())) {
1.675     albertel 7758: 	if ($which eq '64bit5') {
                   7759: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7760: 	} elsif ($which eq '64bit4') {
1.575     albertel 7761: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7762: 	} else {
                   7763: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7764: 	}
1.675     albertel 7765:     } elsif ($which eq '64bit5') {
                   7766: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7767:     } elsif ($which eq '64bit4') {
                   7768: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7769:     } elsif ($which eq '64bit3') {
                   7770: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7771:     } elsif ($which eq '64bit2') {
                   7772: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7773:     } elsif ($which eq '64bit') {
                   7774: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7775:     }
                   7776:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7777: }
                   7778: 
                   7779: sub rndseed_32bit {
                   7780:     my ($symb,$courseid,$domain,$username)=@_;
                   7781:     {
                   7782: 	use integer;
                   7783: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7784: 	my $symbseed=numval($symb) << 22;
                   7785: 	my $namechck=unpack("%32C*",$username) << 17;
                   7786: 	my $nameseed=numval($username) << 12;
                   7787: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7788: 	my $courseseed=unpack("%32C*",$courseid);
                   7789: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7790: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7791: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7792: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7793: 	return $num;
                   7794:     }
                   7795: }
                   7796: 
                   7797: sub rndseed_64bit {
                   7798:     my ($symb,$courseid,$domain,$username)=@_;
                   7799:     {
                   7800: 	use integer;
                   7801: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7802: 	my $symbseed=numval($symb) << 10;
                   7803: 	my $namechck=unpack("%32S*",$username);
                   7804: 	
                   7805: 	my $nameseed=numval($username) << 21;
                   7806: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7807: 	my $courseseed=unpack("%32S*",$courseid);
                   7808: 	
                   7809: 	my $num1=$symbchck+$symbseed+$namechck;
                   7810: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7811: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7812: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7813: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7814: 	return "$num1,$num2";
1.155     albertel 7815:     }
1.366     albertel 7816: }
                   7817: 
1.443     albertel 7818: sub rndseed_64bit2 {
                   7819:     my ($symb,$courseid,$domain,$username)=@_;
                   7820:     {
                   7821: 	use integer;
                   7822: 	# strings need to be an even # of cahracters long, it it is odd the
                   7823:         # last characters gets thrown away
                   7824: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7825: 	my $symbseed=numval($symb) << 10;
                   7826: 	my $namechck=unpack("%32S*",$username.' ');
                   7827: 	
                   7828: 	my $nameseed=numval($username) << 21;
1.501     albertel 7829: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7830: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7831: 	
                   7832: 	my $num1=$symbchck+$symbseed+$namechck;
                   7833: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7834: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7835: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7836: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7837: 	return "$num1,$num2";
                   7838:     }
                   7839: }
                   7840: 
                   7841: sub rndseed_64bit3 {
                   7842:     my ($symb,$courseid,$domain,$username)=@_;
                   7843:     {
                   7844: 	use integer;
                   7845: 	# strings need to be an even # of cahracters long, it it is odd the
                   7846:         # last characters gets thrown away
                   7847: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7848: 	my $symbseed=numval2($symb) << 10;
                   7849: 	my $namechck=unpack("%32S*",$username.' ');
                   7850: 	
                   7851: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7852: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7853: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7854: 	
                   7855: 	my $num1=$symbchck+$symbseed+$namechck;
                   7856: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7857: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7858: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7859: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7860: 	
1.503     albertel 7861: 	return "$num1:$num2";
1.443     albertel 7862:     }
                   7863: }
                   7864: 
1.575     albertel 7865: sub rndseed_64bit4 {
                   7866:     my ($symb,$courseid,$domain,$username)=@_;
                   7867:     {
                   7868: 	use integer;
                   7869: 	# strings need to be an even # of cahracters long, it it is odd the
                   7870:         # last characters gets thrown away
                   7871: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7872: 	my $symbseed=numval3($symb) << 10;
                   7873: 	my $namechck=unpack("%32S*",$username.' ');
                   7874: 	
                   7875: 	my $nameseed=numval3($username) << 21;
                   7876: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7877: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7878: 	
                   7879: 	my $num1=$symbchck+$symbseed+$namechck;
                   7880: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7881: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7882: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7883: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7884: 	
                   7885: 	return "$num1:$num2";
                   7886:     }
                   7887: }
                   7888: 
1.675     albertel 7889: sub rndseed_64bit5 {
                   7890:     my ($symb,$courseid,$domain,$username)=@_;
                   7891:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7892:     return "$num1:$num2";
                   7893: }
                   7894: 
1.366     albertel 7895: sub rndseed_CODE_64bit {
                   7896:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7897:     {
1.366     albertel 7898: 	use integer;
1.443     albertel 7899: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7900: 	my $symbseed=numval2($symb);
1.491     albertel 7901: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7902: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7903: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7904: 	my $num1=$symbseed+$CODEchck;
                   7905: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7906: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7907: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7908: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7909: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7910: 	return "$num1:$num2";
1.366     albertel 7911:     }
                   7912: }
                   7913: 
1.575     albertel 7914: sub rndseed_CODE_64bit4 {
                   7915:     my ($symb,$courseid,$domain,$username)=@_;
                   7916:     {
                   7917: 	use integer;
                   7918: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7919: 	my $symbseed=numval3($symb);
                   7920: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7921: 	my $CODEseed=numval3(&getCODE());
                   7922: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7923: 	my $num1=$symbseed+$CODEchck;
                   7924: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7925: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7926: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7927: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7928: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7929: 	return "$num1:$num2";
                   7930:     }
                   7931: }
                   7932: 
1.675     albertel 7933: sub rndseed_CODE_64bit5 {
                   7934:     my ($symb,$courseid,$domain,$username)=@_;
                   7935:     my $code = &getCODE();
                   7936:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7937:     return "$num1:$num2";
                   7938: }
                   7939: 
1.366     albertel 7940: sub setup_random_from_rndseed {
                   7941:     my ($rndseed)=@_;
1.503     albertel 7942:     if ($rndseed =~/([,:])/) {
                   7943: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7944: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7945:     } else {
                   7946: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7947:     }
1.36      albertel 7948: }
                   7949: 
1.474     albertel 7950: sub latest_receipt_algorithm_id {
1.835     albertel 7951:     return 'receipt3';
1.474     albertel 7952: }
                   7953: 
1.480     www      7954: sub recunique {
                   7955:     my $fucourseid=shift;
                   7956:     my $unique;
1.835     albertel 7957:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7958: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7959: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7960:     } else {
                   7961: 	$unique=$perlvar{'lonReceipt'};
                   7962:     }
                   7963:     return unpack("%32C*",$unique);
                   7964: }
                   7965: 
                   7966: sub recprefix {
                   7967:     my $fucourseid=shift;
                   7968:     my $prefix;
1.835     albertel 7969:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7970: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7971: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7972:     } else {
                   7973: 	$prefix=$perlvar{'lonHostID'};
                   7974:     }
                   7975:     return unpack("%32C*",$prefix);
                   7976: }
                   7977: 
1.76      www      7978: sub ireceipt {
1.474     albertel 7979:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7980: 
                   7981:     my $return =&recprefix($fucourseid).'-';
                   7982: 
                   7983:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7984: 	$env{'request.state'} eq 'construct') {
                   7985: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7986: 	return $return;
                   7987:     }
                   7988: 
1.76      www      7989:     my $cuname=unpack("%32C*",$funame);
                   7990:     my $cudom=unpack("%32C*",$fudom);
                   7991:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7992:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7993:     my $cunique=&recunique($fucourseid);
1.474     albertel 7994:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7995:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7996: 
1.790     albertel 7997: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7998: 			       
                   7999: 	$return.= ($cunique%$cuname+
                   8000: 		   $cunique%$cudom+
                   8001: 		   $cusymb%$cuname+
                   8002: 		   $cusymb%$cudom+
                   8003: 		   $cucourseid%$cuname+
                   8004: 		   $cucourseid%$cudom+
                   8005: 		   $cpart%$cuname+
                   8006: 		   $cpart%$cudom);
                   8007:     } else {
                   8008: 	$return.= ($cunique%$cuname+
                   8009: 		   $cunique%$cudom+
                   8010: 		   $cusymb%$cuname+
                   8011: 		   $cusymb%$cudom+
                   8012: 		   $cucourseid%$cuname+
                   8013: 		   $cucourseid%$cudom);
                   8014:     }
                   8015:     return $return;
1.76      www      8016: }
                   8017: 
                   8018: sub receipt {
1.474     albertel 8019:     my ($part)=@_;
1.790     albertel 8020:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8021:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8022: }
1.260     ng       8023: 
1.790     albertel 8024: sub whichuser {
                   8025:     my ($passedsymb)=@_;
                   8026:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8027:     if (defined($env{'form.grade_symb'})) {
                   8028: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8029: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8030: 	if (!$allowed &&
                   8031: 	    exists($env{'request.course.sec'}) &&
                   8032: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8033: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8034: 			      '/'.$env{'request.course.sec'});
                   8035: 	}
                   8036: 	if ($allowed) {
                   8037: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8038: 	    $courseid=$tmp_courseid;
                   8039: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8040: 	    ($name)=&get_env_multiple('form.grade_username');
                   8041: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8042: 	}
                   8043:     }
                   8044:     if (!$passedsymb) {
                   8045: 	$symb=&symbread();
                   8046:     } else {
                   8047: 	$symb=$passedsymb;
                   8048:     }
                   8049:     $courseid=$env{'request.course.id'};
                   8050:     $domain=$env{'user.domain'};
                   8051:     $name=$env{'user.name'};
                   8052:     if ($name eq 'public' && $domain eq 'public') {
                   8053: 	if (!defined($env{'form.username'})) {
                   8054: 	    $env{'form.username'}.=time.rand(10000000);
                   8055: 	}
                   8056: 	$name.=$env{'form.username'};
                   8057:     }
                   8058:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8059: 
                   8060: }
                   8061: 
1.36      albertel 8062: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8063: # returns either the contents of the file or 
                   8064: # -1 if the file doesn't exist
1.481     raeburn  8065: #
                   8066: # if the target is a file that was uploaded via DOCS, 
                   8067: # a check will be made to see if a current copy exists on the local server,
                   8068: # if it does this will be served, otherwise a copy will be retrieved from
                   8069: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8070: # the local server.   
1.472     albertel 8071: 
1.36      albertel 8072: sub getfile {
1.538     albertel 8073:     my ($file) = @_;
1.609     banghart 8074:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8075:     &repcopy($file);
                   8076:     return &readfile($file);
                   8077: }
                   8078: 
                   8079: sub repcopy_userfile {
                   8080:     my ($file)=@_;
1.609     banghart 8081:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8082:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8083:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8084: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8085:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8086:     if (-e "$file") {
1.828     www      8087: # we already have a local copy, check it out
1.538     albertel 8088: 	my @fileinfo = stat($file);
1.828     www      8089: 	my $rtncode;
                   8090: 	my $info;
1.538     albertel 8091: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8092: 	if ($lwpresp ne 'ok') {
1.828     www      8093: # there is no such file anymore, even though we had a local copy
1.482     albertel 8094: 	    if ($rtncode eq '404') {
1.538     albertel 8095: 		unlink($file);
1.482     albertel 8096: 	    }
                   8097: 	    return -1;
                   8098: 	}
                   8099: 	if ($info < $fileinfo[9]) {
1.828     www      8100: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8101: 	    return 'ok';
1.828     www      8102: 	} else {
                   8103: # the file is outdated, get rid of it
                   8104: 	    unlink($file);
1.482     albertel 8105: 	}
1.828     www      8106:     }
                   8107: # one way or the other, at this point, we don't have the file
                   8108: # construct the correct path for the file
                   8109:     my @parts = ($cdom,$cnum); 
                   8110:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8111: 	push @parts, split(/\//,$1);
                   8112:     }
                   8113:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8114:     foreach my $part (@parts) {
                   8115: 	$path .= '/'.$part;
                   8116: 	if (!-e $path) {
                   8117: 	    mkdir($path,0770);
1.482     albertel 8118: 	}
                   8119:     }
1.828     www      8120: # now the path exists for sure
                   8121: # get a user agent
                   8122:     my $ua=new LWP::UserAgent;
                   8123:     my $transferfile=$file.'.in.transfer';
                   8124: # FIXME: this should flock
                   8125:     if (-e $transferfile) { return 'ok'; }
                   8126:     my $request;
                   8127:     $uri=~s/^\///;
1.838     albertel 8128:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8129:     my $response=$ua->request($request,$transferfile);
                   8130: # did it work?
                   8131:     if ($response->is_error()) {
                   8132: 	unlink($transferfile);
                   8133: 	&logthis("Userfile repcopy failed for $uri");
                   8134: 	return -1;
                   8135:     }
                   8136: # worked, rename the transfer file
                   8137:     rename($transferfile,$file);
1.607     raeburn  8138:     return 'ok';
1.481     raeburn  8139: }
                   8140: 
1.517     albertel 8141: sub tokenwrapper {
                   8142:     my $uri=shift;
1.552     albertel 8143:     $uri=~s|^http\://([^/]+)||;
                   8144:     $uri=~s|^/||;
1.620     albertel 8145:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8146:     my $token=$1;
1.552     albertel 8147:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8148:     if ($udom && $uname && $file) {
                   8149: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8150:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8151:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8152:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8153:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8154:     } else {
                   8155:         return '/adm/notfound.html';
                   8156:     }
                   8157: }
                   8158: 
1.828     www      8159: # call with reqtype HEAD: get last modification time
                   8160: # call with reqtype GET: get the file contents
                   8161: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8162: #
1.481     raeburn  8163: sub getuploaded {
                   8164:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8165:     $uri=~s/^\///;
1.838     albertel 8166:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8167:     my $ua=new LWP::UserAgent;
                   8168:     my $request=new HTTP::Request($reqtype,$uri);
                   8169:     my $response=$ua->request($request);
                   8170:     $$rtncode = $response->code;
1.482     albertel 8171:     if (! $response->is_success()) {
                   8172: 	return 'failed';
                   8173:     }      
                   8174:     if ($reqtype eq 'HEAD') {
1.486     www      8175: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8176:     } elsif ($reqtype eq 'GET') {
                   8177: 	$$info = $response->content;
1.472     albertel 8178:     }
1.482     albertel 8179:     return 'ok';
1.36      albertel 8180: }
                   8181: 
1.481     raeburn  8182: sub readfile {
                   8183:     my $file = shift;
                   8184:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8185:     my $fh;
                   8186:     open($fh,"<$file");
                   8187:     my $a='';
1.800     albertel 8188:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8189:     return $a;
                   8190: }
                   8191: 
1.36      albertel 8192: sub filelocation {
1.590     banghart 8193:     my ($dir,$file) = @_;
                   8194:     my $location;
                   8195:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8196: 
                   8197:     if ($file =~ m-^/adm/-) {
                   8198: 	$file=~s-^/adm/wrapper/-/-;
                   8199: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8200:     }
1.882     albertel 8201: 
1.590     banghart 8202:     if ($file=~m:^/~:) { # is a contruction space reference
                   8203:         $location = $file;
                   8204:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8205:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8206: 	# is a correct contruction space reference
                   8207:         $location = $file;
1.956     raeburn  8208:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8209:         $location = $file;
1.609     banghart 8210:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8211:         my ($udom,$uname,$filename)=
1.811     albertel 8212:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8213:         my $home=&homeserver($uname,$udom);
                   8214:         my $is_me=0;
                   8215:         my @ids=&current_machine_ids();
                   8216:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8217:         if ($is_me) {
1.955     raeburn  8218:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8219:         } else {
                   8220:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8221:   	      $udom.'/'.$uname.'/'.$filename;
                   8222:         }
1.882     albertel 8223:     } elsif ($file =~ m-^/adm/-) {
                   8224: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8225:     } else {
                   8226:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8227:         $file=~s:^/res/:/:;
                   8228:         if ( !( $file =~ m:^/:) ) {
                   8229:             $location = $dir. '/'.$file;
                   8230:         } else {
                   8231:             $location = '/home/httpd/html/res'.$file;
                   8232:         }
1.59      albertel 8233:     }
1.590     banghart 8234:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8235:     while ($location=~m{/\.\./}) {
                   8236: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8237: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8238: 	} else {
                   8239: 	    $location=~ s{/\.\./}{/}g;
                   8240: 	}
                   8241:     } #remove dir/..
1.590     banghart 8242:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8243:     return $location;
1.46      www      8244: }
1.36      albertel 8245: 
1.46      www      8246: sub hreflocation {
                   8247:     my ($dir,$file)=@_;
1.460     albertel 8248:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8249: 	$file=filelocation($dir,$file);
1.700     albertel 8250:     } elsif ($file=~m-^/adm/-) {
                   8251: 	$file=~s-^/adm/wrapper/-/-;
                   8252: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8253:     }
                   8254:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8255: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8256:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8257: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8258:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8259: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8260: 	    -/uploaded/$1/$2/-x;
1.46      www      8261:     }
1.913     albertel 8262:     if ($file=~ m{^/userfiles/}) {
                   8263: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8264:     }
1.462     albertel 8265:     return $file;
1.465     albertel 8266: }
                   8267: 
                   8268: sub current_machine_domains {
1.853     albertel 8269:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8270: }
                   8271: 
                   8272: sub machine_domains {
                   8273:     my ($hostname) = @_;
1.465     albertel 8274:     my @domains;
1.838     albertel 8275:     my %hostname = &all_hostnames();
1.465     albertel 8276:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8277: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8278: 	if ($hostname eq $name) {
1.844     albertel 8279: 	    push(@domains,&host_domain($id));
1.465     albertel 8280: 	}
                   8281:     }
                   8282:     return @domains;
                   8283: }
                   8284: 
                   8285: sub current_machine_ids {
1.853     albertel 8286:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8287: }
                   8288: 
                   8289: sub machine_ids {
                   8290:     my ($hostname) = @_;
                   8291:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8292:     my @ids;
1.888     albertel 8293:     my %name_to_host = &all_names();
1.889     albertel 8294:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8295: 	return @{ $name_to_host{$hostname} };
                   8296:     }
                   8297:     return;
1.31      www      8298: }
                   8299: 
1.824     raeburn  8300: sub additional_machine_domains {
                   8301:     my @domains;
                   8302:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8303:     while( my $line = <$fh>) {
                   8304:         $line =~ s/\s//g;
                   8305:         push(@domains,$line);
                   8306:     }
                   8307:     return @domains;
                   8308: }
                   8309: 
                   8310: sub default_login_domain {
                   8311:     my $domain = $perlvar{'lonDefDomain'};
                   8312:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8313:     foreach my $posdom (&current_machine_domains(),
                   8314:                         &additional_machine_domains()) {
                   8315:         if (lc($posdom) eq lc($testdomain)) {
                   8316:             $domain=$posdom;
                   8317:             last;
                   8318:         }
                   8319:     }
                   8320:     return $domain;
                   8321: }
                   8322: 
1.31      www      8323: # ------------------------------------------------------------- Declutters URLs
                   8324: 
                   8325: sub declutter {
                   8326:     my $thisfn=shift;
1.569     albertel 8327:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8328:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8329:     $thisfn=~s/^\///;
1.697     albertel 8330:     $thisfn=~s|^adm/wrapper/||;
                   8331:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8332:     $thisfn=~s/^res\///;
1.235     www      8333:     $thisfn=~s/\?.+$//;
1.268     www      8334:     return $thisfn;
                   8335: }
                   8336: 
                   8337: # ------------------------------------------------------------- Clutter up URLs
                   8338: 
                   8339: sub clutter {
                   8340:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8341:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8342: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8343:        $thisfn='/res'.$thisfn; 
                   8344:     }
1.694     albertel 8345:     if ($thisfn !~m|/adm|) {
1.695     albertel 8346: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8347: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8348: 	} else {
                   8349: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8350: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8351: 	    if ($embstyle eq 'ssi'
                   8352: 		|| ($embstyle eq 'hdn')
                   8353: 		|| ($embstyle eq 'rat')
                   8354: 		|| ($embstyle eq 'prv')
                   8355: 		|| ($embstyle eq 'ign')) {
                   8356: 		#do nothing with these
                   8357: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8358: 		|| ($embstyle eq 'emb')
                   8359: 		|| ($embstyle eq 'wrp')) {
                   8360: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8361: 	    } elsif ($embstyle eq 'unk'
                   8362: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8363: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8364: 	    } else {
1.718     www      8365: #		&logthis("Got a blank emb style");
1.695     albertel 8366: 	    }
1.694     albertel 8367: 	}
                   8368:     }
1.31      www      8369:     return $thisfn;
1.12      www      8370: }
                   8371: 
1.787     albertel 8372: sub clutter_with_no_wrapper {
                   8373:     my $uri = &clutter(shift);
                   8374:     if ($uri =~ m-^/adm/-) {
                   8375: 	$uri =~ s-^/adm/wrapper/-/-;
                   8376: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8377:     }
                   8378:     return $uri;
                   8379: }
                   8380: 
1.557     albertel 8381: sub freeze_escape {
                   8382:     my ($value)=@_;
                   8383:     if (ref($value)) {
                   8384: 	$value=&nfreeze($value);
                   8385: 	return '__FROZEN__'.&escape($value);
                   8386:     }
                   8387:     return &escape($value);
                   8388: }
                   8389: 
1.11      www      8390: 
1.557     albertel 8391: sub thaw_unescape {
                   8392:     my ($value)=@_;
                   8393:     if ($value =~ /^__FROZEN__/) {
                   8394: 	substr($value,0,10,undef);
                   8395: 	$value=&unescape($value);
                   8396: 	return &thaw($value);
                   8397:     }
                   8398:     return &unescape($value);
                   8399: }
                   8400: 
1.436     albertel 8401: sub correct_line_ends {
                   8402:     my ($result)=@_;
                   8403:     $$result =~s/\r\n/\n/mg;
                   8404:     $$result =~s/\r/\n/mg;
1.415     albertel 8405: }
1.1       albertel 8406: # ================================================================ Main Program
                   8407: 
1.184     www      8408: sub goodbye {
1.204     albertel 8409:    &logthis("Starting Shut down");
1.443     albertel 8410: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8411:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8412: #converted
1.599     albertel 8413: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8414:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8415: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8416: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8417: #1.1 only
1.870     albertel 8418: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8419: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8420: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8421: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8422:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8423:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8424:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8425:    &flushcourselogs();
                   8426:    &logthis("Shutting down");
                   8427: }
                   8428: 
1.852     albertel 8429: sub get_dns {
1.869     albertel 8430:     my ($url,$func,$ignore_cache) = @_;
                   8431:     if (!$ignore_cache) {
                   8432: 	my ($content,$cached)=
                   8433: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8434: 	if ($cached) {
                   8435: 	    &$func($content);
                   8436: 	    return;
                   8437: 	}
                   8438:     }
                   8439: 
                   8440:     my %alldns;
1.852     albertel 8441:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8442:     foreach my $dns (<$config>) {
                   8443: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8444: 	$alldns{$1} = 1;
                   8445:     }
                   8446:     while (%alldns) {
                   8447: 	my ($dns) = keys(%alldns);
                   8448: 	delete($alldns{$dns});
1.852     albertel 8449: 	my $ua=new LWP::UserAgent;
                   8450: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8451: 	my $response=$ua->request($request);
                   8452: 	next if ($response->is_error());
                   8453: 	my @content = split("\n",$response->content);
1.869     albertel 8454: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8455: 	&$func(\@content);
1.869     albertel 8456: 	return;
1.852     albertel 8457:     }
                   8458:     close($config);
1.871     albertel 8459:     my $which = (split('/',$url))[3];
                   8460:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8461:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8462:     my @content = <$config>;
                   8463:     &$func(\@content);
                   8464:     return;
1.852     albertel 8465: }
1.327     albertel 8466: # ------------------------------------------------------------ Read domain file
                   8467: {
1.852     albertel 8468:     my $loaded;
1.846     albertel 8469:     my %domain;
                   8470: 
1.852     albertel 8471:     sub parse_domain_tab {
                   8472: 	my ($lines) = @_;
                   8473: 	foreach my $line (@$lines) {
                   8474: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8475: 
1.846     albertel 8476: 	    chomp($line);
1.852     albertel 8477: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8478: 	    my %this_domain;
                   8479: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8480: 			       'lang_def', 'city', 'longi', 'lati',
                   8481: 			       'primary') {
                   8482: 		$this_domain{$field} = shift(@elements);
                   8483: 	    }
                   8484: 	    $domain{$name} = \%this_domain;
1.852     albertel 8485: 	}
                   8486:     }
1.864     albertel 8487: 
                   8488:     sub reset_domain_info {
                   8489: 	undef($loaded);
                   8490: 	undef(%domain);
                   8491:     }
                   8492: 
1.852     albertel 8493:     sub load_domain_tab {
1.869     albertel 8494: 	my ($ignore_cache) = @_;
                   8495: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8496: 	my $fh;
                   8497: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8498: 	    my @lines = <$fh>;
                   8499: 	    &parse_domain_tab(\@lines);
1.448     albertel 8500: 	}
1.852     albertel 8501: 	close($fh);
                   8502: 	$loaded = 1;
1.327     albertel 8503:     }
1.846     albertel 8504: 
                   8505:     sub domain {
1.852     albertel 8506: 	&load_domain_tab() if (!$loaded);
                   8507: 
1.846     albertel 8508: 	my ($name,$what) = @_;
                   8509: 	return if ( !exists($domain{$name}) );
                   8510: 
                   8511: 	if (!$what) {
                   8512: 	    return $domain{$name}{'description'};
                   8513: 	}
                   8514: 	return $domain{$name}{$what};
                   8515:     }
1.327     albertel 8516: }
                   8517: 
                   8518: 
1.1       albertel 8519: # ------------------------------------------------------------- Read hosts file
                   8520: {
1.838     albertel 8521:     my %hostname;
1.844     albertel 8522:     my %hostdom;
1.845     albertel 8523:     my %libserv;
1.852     albertel 8524:     my $loaded;
1.888     albertel 8525:     my %name_to_host;
1.852     albertel 8526: 
                   8527:     sub parse_hosts_tab {
                   8528: 	my ($file) = @_;
                   8529: 	foreach my $configline (@$file) {
                   8530: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8531: 	    next if ($configline =~ /^\^/);
                   8532: 	    chomp($configline);
                   8533: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8534: 	    $name=~s/\s//g;
                   8535: 	    if ($id && $domain && $role && $name) {
                   8536: 		$hostname{$id}=$name;
1.888     albertel 8537: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8538: 		$hostdom{$id}=$domain;
                   8539: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8540: 	    }
                   8541: 	}
                   8542:     }
1.864     albertel 8543:     
                   8544:     sub reset_hosts_info {
1.897     albertel 8545: 	&purge_remembered();
1.864     albertel 8546: 	&reset_domain_info();
                   8547: 	&reset_hosts_ip_info();
1.892     albertel 8548: 	undef(%name_to_host);
1.864     albertel 8549: 	undef(%hostname);
                   8550: 	undef(%hostdom);
                   8551: 	undef(%libserv);
                   8552: 	undef($loaded);
                   8553:     }
1.1       albertel 8554: 
1.852     albertel 8555:     sub load_hosts_tab {
1.869     albertel 8556: 	my ($ignore_cache) = @_;
                   8557: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8558: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8559: 	my @config = <$config>;
                   8560: 	&parse_hosts_tab(\@config);
                   8561: 	close($config);
                   8562: 	$loaded=1;
1.1       albertel 8563:     }
1.852     albertel 8564: 
1.838     albertel 8565:     sub hostname {
1.852     albertel 8566: 	&load_hosts_tab() if (!$loaded);
                   8567: 
1.838     albertel 8568: 	my ($lonid) = @_;
                   8569: 	return $hostname{$lonid};
                   8570:     }
1.845     albertel 8571: 
1.838     albertel 8572:     sub all_hostnames {
1.852     albertel 8573: 	&load_hosts_tab() if (!$loaded);
                   8574: 
1.838     albertel 8575: 	return %hostname;
                   8576:     }
1.845     albertel 8577: 
1.888     albertel 8578:     sub all_names {
                   8579: 	&load_hosts_tab() if (!$loaded);
                   8580: 
                   8581: 	return %name_to_host;
                   8582:     }
                   8583: 
1.845     albertel 8584:     sub is_library {
1.852     albertel 8585: 	&load_hosts_tab() if (!$loaded);
                   8586: 
1.845     albertel 8587: 	return exists($libserv{$_[0]});
                   8588:     }
                   8589: 
                   8590:     sub all_library {
1.852     albertel 8591: 	&load_hosts_tab() if (!$loaded);
                   8592: 
1.845     albertel 8593: 	return %libserv;
                   8594:     }
                   8595: 
1.841     albertel 8596:     sub get_servers {
1.852     albertel 8597: 	&load_hosts_tab() if (!$loaded);
                   8598: 
1.841     albertel 8599: 	my ($domain,$type) = @_;
                   8600: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8601: 	                                          : %hostname;
                   8602: 	my %result;
1.842     albertel 8603: 	if (ref($domain) eq 'ARRAY') {
                   8604: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8605: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8606: 		    $result{$host} = $hostname;
                   8607: 		}
                   8608: 	    }
                   8609: 	} else {
                   8610: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8611: 		if ($hostdom{$host} eq $domain) {
                   8612: 		    $result{$host} = $hostname;
                   8613: 		}
1.841     albertel 8614: 	    }
                   8615: 	}
                   8616: 	return %result;
                   8617:     }
1.845     albertel 8618: 
1.844     albertel 8619:     sub host_domain {
1.852     albertel 8620: 	&load_hosts_tab() if (!$loaded);
                   8621: 
1.844     albertel 8622: 	my ($lonid) = @_;
                   8623: 	return $hostdom{$lonid};
                   8624:     }
                   8625: 
1.841     albertel 8626:     sub all_domains {
1.852     albertel 8627: 	&load_hosts_tab() if (!$loaded);
                   8628: 
1.841     albertel 8629: 	my %seen;
                   8630: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8631: 	return @uniq;
                   8632:     }
1.1       albertel 8633: }
                   8634: 
1.847     albertel 8635: { 
                   8636:     my %iphost;
1.856     albertel 8637:     my %name_to_ip;
                   8638:     my %lonid_to_ip;
1.869     albertel 8639: 
1.847     albertel 8640:     sub get_hosts_from_ip {
                   8641: 	my ($ip) = @_;
                   8642: 	my %iphosts = &get_iphost();
                   8643: 	if (ref($iphosts{$ip})) {
                   8644: 	    return @{$iphosts{$ip}};
                   8645: 	}
                   8646: 	return;
1.839     albertel 8647:     }
1.864     albertel 8648:     
                   8649:     sub reset_hosts_ip_info {
                   8650: 	undef(%iphost);
                   8651: 	undef(%name_to_ip);
                   8652: 	undef(%lonid_to_ip);
                   8653:     }
1.856     albertel 8654: 
                   8655:     sub get_host_ip {
                   8656: 	my ($lonid) = @_;
                   8657: 	if (exists($lonid_to_ip{$lonid})) {
                   8658: 	    return $lonid_to_ip{$lonid};
                   8659: 	}
                   8660: 	my $name=&hostname($lonid);
                   8661:    	my $ip = gethostbyname($name);
                   8662: 	return if (!$ip || length($ip) ne 4);
                   8663: 	$ip=inet_ntoa($ip);
                   8664: 	$name_to_ip{$name}   = $ip;
                   8665: 	$lonid_to_ip{$lonid} = $ip;
                   8666: 	return $ip;
                   8667:     }
1.847     albertel 8668:     
                   8669:     sub get_iphost {
1.869     albertel 8670: 	my ($ignore_cache) = @_;
1.894     albertel 8671: 
1.869     albertel 8672: 	if (!$ignore_cache) {
                   8673: 	    if (%iphost) {
                   8674: 		return %iphost;
                   8675: 	    }
                   8676: 	    my ($ip_info,$cached)=
                   8677: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8678: 	    if ($cached) {
                   8679: 		%iphost      = %{$ip_info->[0]};
                   8680: 		%name_to_ip  = %{$ip_info->[1]};
                   8681: 		%lonid_to_ip = %{$ip_info->[2]};
                   8682: 		return %iphost;
                   8683: 	    }
                   8684: 	}
1.894     albertel 8685: 
                   8686: 	# get yesterday's info for fallback
                   8687: 	my %old_name_to_ip;
                   8688: 	my ($ip_info,$cached)=
                   8689: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8690: 	if ($cached) {
                   8691: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8692: 	}
                   8693: 
1.888     albertel 8694: 	my %name_to_host = &all_names();
                   8695: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8696: 	    my $ip;
                   8697: 	    if (!exists($name_to_ip{$name})) {
                   8698: 		$ip = gethostbyname($name);
                   8699: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8700: 		    if (defined($old_name_to_ip{$name})) {
                   8701: 			$ip = $old_name_to_ip{$name};
                   8702: 			&logthis("Can't find $name defaulting to old $ip");
                   8703: 		    } else {
                   8704: 			&logthis("Name $name no IP found");
                   8705: 			next;
                   8706: 		    }
                   8707: 		} else {
                   8708: 		    $ip=inet_ntoa($ip);
1.847     albertel 8709: 		}
                   8710: 		$name_to_ip{$name} = $ip;
                   8711: 	    } else {
                   8712: 		$ip = $name_to_ip{$name};
1.653     albertel 8713: 	    }
1.888     albertel 8714: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8715: 		$lonid_to_ip{$id} = $ip;
                   8716: 	    }
                   8717: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8718: 	}
1.869     albertel 8719: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8720: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8721: 				      48*60*60);
1.869     albertel 8722: 
1.847     albertel 8723: 	return %iphost;
1.598     albertel 8724:     }
                   8725: }
                   8726: 
1.862     albertel 8727: BEGIN {
                   8728: 
                   8729: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8730:     unless ($readit) {
                   8731: {
                   8732:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8733:     %perlvar = (%perlvar,%{$configvars});
                   8734: }
                   8735: 
                   8736: 
1.1       albertel 8737: # ------------------------------------------------------ Read spare server file
                   8738: {
1.448     albertel 8739:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8740: 
                   8741:     while (my $configline=<$config>) {
                   8742:        chomp($configline);
1.284     matthew  8743:        if ($configline) {
1.784     albertel 8744: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8745: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8746: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8747:        }
                   8748:     }
1.448     albertel 8749:     close($config);
1.1       albertel 8750: }
1.11      www      8751: # ------------------------------------------------------------ Read permissions
                   8752: {
1.448     albertel 8753:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8754: 
                   8755:     while (my $configline=<$config>) {
1.448     albertel 8756: 	chomp($configline);
                   8757: 	if ($configline) {
                   8758: 	    my ($role,$perm)=split(/ /,$configline);
                   8759: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8760: 	}
1.11      www      8761:     }
1.448     albertel 8762:     close($config);
1.11      www      8763: }
                   8764: 
                   8765: # -------------------------------------------- Read plain texts for permissions
                   8766: {
1.448     albertel 8767:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8768: 
                   8769:     while (my $configline=<$config>) {
1.448     albertel 8770: 	chomp($configline);
                   8771: 	if ($configline) {
1.742     raeburn  8772: 	    my ($short,@plain)=split(/:/,$configline);
                   8773:             %{$prp{$short}} = ();
                   8774: 	    if (@plain > 0) {
                   8775:                 $prp{$short}{'std'} = $plain[0];
                   8776:                 for (my $i=1; $i<@plain; $i++) {
                   8777:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8778:                 }
                   8779:             }
1.448     albertel 8780: 	}
1.135     www      8781:     }
1.448     albertel 8782:     close($config);
1.135     www      8783: }
                   8784: 
                   8785: # ---------------------------------------------------------- Read package table
                   8786: {
1.448     albertel 8787:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8788: 
                   8789:     while (my $configline=<$config>) {
1.483     albertel 8790: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8791: 	chomp($configline);
                   8792: 	my ($short,$plain)=split(/:/,$configline);
                   8793: 	my ($pack,$name)=split(/\&/,$short);
                   8794: 	if ($plain ne '') {
                   8795: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8796: 	    $packagetab{$short}=$plain; 
                   8797: 	}
1.11      www      8798:     }
1.448     albertel 8799:     close($config);
1.329     matthew  8800: }
                   8801: 
                   8802: # ------------- set up temporary directory
                   8803: {
                   8804:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8805: 
1.11      www      8806: }
                   8807: 
1.794     albertel 8808: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8809: 				'compress_threshold'=> 20_000,
                   8810:  			        });
1.185     www      8811: 
1.281     www      8812: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8813: $dumpcount=0;
1.958     www      8814: $locknum=0;
1.22      www      8815: 
1.163     harris41 8816: &logtouch();
1.672     albertel 8817: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8818: $readit=1;
1.564     albertel 8819:     {
                   8820: 	use integer;
                   8821: 	my $test=(2**32)+1;
1.568     albertel 8822: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8823: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8824:     }
1.195     www      8825: }
1.1       albertel 8826: }
1.179     www      8827: 
1.1       albertel 8828: 1;
1.191     harris41 8829: __END__
                   8830: 
1.243     albertel 8831: =pod
                   8832: 
1.191     harris41 8833: =head1 NAME
                   8834: 
1.243     albertel 8835: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8836: 
                   8837: =head1 SYNOPSIS
                   8838: 
1.243     albertel 8839: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8840: 
                   8841:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8842: 
1.243     albertel 8843: Common parameters:
                   8844: 
                   8845: =over 4
                   8846: 
                   8847: =item *
                   8848: 
                   8849: $uname : an internal username (if $cname expecting a course Id specifically)
                   8850: 
                   8851: =item *
                   8852: 
                   8853: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8854: 
                   8855: =item *
                   8856: 
                   8857: $symb : a resource instance identifier
                   8858: 
                   8859: =item *
                   8860: 
                   8861: $namespace : the name of a .db file that contains the data needed or
                   8862: being set.
                   8863: 
                   8864: =back
                   8865: 
1.394     bowersj2 8866: =head1 OVERVIEW
1.191     harris41 8867: 
1.394     bowersj2 8868: lonnet provides subroutines which interact with the
                   8869: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8870: about classes, users, and resources.
1.243     albertel 8871: 
                   8872: For many of these objects you can also use this to store data about
                   8873: them or modify them in various ways.
1.191     harris41 8874: 
1.394     bowersj2 8875: =head2 Symbs
1.191     harris41 8876: 
1.394     bowersj2 8877: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8878: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8879: map, the resource number of the resource in the map, and the URL of
                   8880: the resource itself. The latter is somewhat redundant, but might help
                   8881: if maps change.
                   8882: 
                   8883: An example is
                   8884: 
                   8885:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8886: 
                   8887: The respective map entry is
                   8888: 
                   8889:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8890:   title="Problem 2">
                   8891:  </resource>
                   8892: 
                   8893: Symbs are used by the random number generator, as well as to store and
                   8894: restore data specific to a certain instance of for example a problem.
                   8895: 
                   8896: =head2 Storing And Retrieving Data
                   8897: 
                   8898: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8899: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8900: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8901: is is the non-critical message twin of cstore. These functions are for
                   8902: handlers to store a perl hash to a user's permanent data space in an
                   8903: easy manner, and to retrieve it again on another call. It is expected
                   8904: that a handler would use this once at the beginning to retrieve data,
                   8905: and then again once at the end to send only the new data back.
                   8906: 
                   8907: The data is stored in the user's data directory on the user's
                   8908: homeserver under the ID of the course.
                   8909: 
                   8910: The hash that is returned by restore will have all of the previous
                   8911: value for all of the elements of the hash.
                   8912: 
                   8913: Example:
                   8914: 
                   8915:  #creating a hash
                   8916:  my %hash;
                   8917:  $hash{'foo'}='bar';
                   8918: 
                   8919:  #storing it
                   8920:  &Apache::lonnet::cstore(\%hash);
                   8921: 
                   8922:  #changing a value
                   8923:  $hash{'foo'}='notbar';
                   8924: 
                   8925:  #adding a new value
                   8926:  $hash{'bar'}='foo';
                   8927:  &Apache::lonnet::cstore(\%hash);
                   8928: 
                   8929:  #retrieving the hash
                   8930:  my %history=&Apache::lonnet::restore();
                   8931: 
                   8932:  #print the hash
                   8933:  foreach my $key (sort(keys(%history))) {
                   8934:    print("\%history{$key} = $history{$key}");
                   8935:  }
                   8936: 
                   8937: Will print out:
1.191     harris41 8938: 
1.394     bowersj2 8939:  %history{1:foo} = bar
                   8940:  %history{1:keys} = foo:timestamp
                   8941:  %history{1:timestamp} = 990455579
                   8942:  %history{2:bar} = foo
                   8943:  %history{2:foo} = notbar
                   8944:  %history{2:keys} = foo:bar:timestamp
                   8945:  %history{2:timestamp} = 990455580
                   8946:  %history{bar} = foo
                   8947:  %history{foo} = notbar
                   8948:  %history{timestamp} = 990455580
                   8949:  %history{version} = 2
                   8950: 
                   8951: Note that the special hash entries C<keys>, C<version> and
                   8952: C<timestamp> were added to the hash. C<version> will be equal to the
                   8953: total number of versions of the data that have been stored. The
                   8954: C<timestamp> attribute will be the UNIX time the hash was
                   8955: stored. C<keys> is available in every historical section to list which
                   8956: keys were added or changed at a specific historical revision of a
                   8957: hash.
                   8958: 
                   8959: B<Warning>: do not store the hash that restore returns directly. This
                   8960: will cause a mess since it will restore the historical keys as if the
                   8961: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8962: 
1.394     bowersj2 8963: Calling convention:
1.191     harris41 8964: 
1.394     bowersj2 8965:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8966:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8967: 
1.394     bowersj2 8968: For more detailed information, see lonnet specific documentation.
1.191     harris41 8969: 
1.394     bowersj2 8970: =head1 RETURN MESSAGES
1.191     harris41 8971: 
1.394     bowersj2 8972: =over 4
1.191     harris41 8973: 
1.394     bowersj2 8974: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8975: 
1.394     bowersj2 8976: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8977: when the connection is brought back up
1.191     harris41 8978: 
1.394     bowersj2 8979: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8980: for later delivery
1.191     harris41 8981: 
1.394     bowersj2 8982: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8983: 
1.394     bowersj2 8984: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8985: that was requested
1.191     harris41 8986: 
1.243     albertel 8987: =back
1.191     harris41 8988: 
1.243     albertel 8989: =head1 PUBLIC SUBROUTINES
1.191     harris41 8990: 
1.243     albertel 8991: =head2 Session Environment Functions
1.191     harris41 8992: 
1.243     albertel 8993: =over 4
1.191     harris41 8994: 
1.394     bowersj2 8995: =item * 
                   8996: X<appenv()>
1.949     raeburn  8997: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 8998: the user envirnoment file, and will be restored for each access this
1.620     albertel 8999: user makes during this session, also modifies the %env for the current
1.949     raeburn  9000: process. Optional rolesarrayref - if defined contains a reference to an array
                   9001: of roles which are exempt from the restriction on modifying user.role entries 
                   9002: in the user's environment.db and in %env.    
1.191     harris41 9003: 
                   9004: =item *
1.394     bowersj2 9005: X<delenv()>
                   9006: B<delenv($regexp)>: removes all items from the session
                   9007: environment file that matches the regular expression in $regexp. The
1.620     albertel 9008: values are also delted from the current processes %env.
1.191     harris41 9009: 
1.795     albertel 9010: =item * get_env_multiple($name) 
                   9011: 
                   9012: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9013: values may be defined and end up as an array ref.
                   9014: 
                   9015: returns an array of values
                   9016: 
1.243     albertel 9017: =back
                   9018: 
                   9019: =head2 User Information
1.191     harris41 9020: 
1.243     albertel 9021: =over 4
1.191     harris41 9022: 
                   9023: =item *
1.394     bowersj2 9024: X<queryauthenticate()>
                   9025: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9026: authentication scheme
                   9027: 
                   9028: =item *
1.394     bowersj2 9029: X<authenticate()>
                   9030: B<authenticate($uname,$upass,$udom)>: try to
                   9031: authenticate user from domain's lib servers (first use the current
                   9032: one). C<$upass> should be the users password.
1.191     harris41 9033: 
                   9034: =item *
1.394     bowersj2 9035: X<homeserver()>
                   9036: B<homeserver($uname,$udom)>: find the server which has
                   9037: the user's directory and files (there must be only one), this caches
                   9038: the answer, and also caches if there is a borken connection.
1.191     harris41 9039: 
                   9040: =item *
1.394     bowersj2 9041: X<idget()>
                   9042: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9043: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9044: username, and only 1 username per ID in a specific domain) (returns
                   9045: hash: id=>name,id=>name)
1.191     harris41 9046: 
                   9047: =item *
1.394     bowersj2 9048: X<idrget()>
                   9049: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9050: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9051: 
                   9052: =item *
1.394     bowersj2 9053: X<idput()>
                   9054: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9055: 
                   9056: =item *
1.394     bowersj2 9057: X<rolesinit()>
                   9058: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9059: 
                   9060: =item *
1.551     albertel 9061: X<getsection()>
                   9062: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9063: course $cname, return section name/number or '' for "not in course"
                   9064: and '-1' for "no section"
                   9065: 
                   9066: =item *
1.394     bowersj2 9067: X<userenvironment()>
                   9068: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9069: passed in @what from the requested user's environment, returns a hash
                   9070: 
1.858     raeburn  9071: =item * 
                   9072: X<userlog_query()>
1.859     albertel 9073: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9074: activity.log file. %filters defines filters applied when parsing the
                   9075: log file. These can be start or end timestamps, or the type of action
                   9076: - log to look for Login or Logout events, check for Checkin or
                   9077: Checkout, role for role selection. The response is in the form
                   9078: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9079: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9080: 
1.243     albertel 9081: =back
                   9082: 
                   9083: =head2 User Roles
                   9084: 
                   9085: =over 4
                   9086: 
                   9087: =item *
                   9088: 
1.810     raeburn  9089: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9090:  F: full access
                   9091:  U,I,K: authentication modes (cxx only)
                   9092:  '': forbidden
                   9093:  1: user needs to choose course
                   9094:  2: browse allowed
1.766     albertel 9095:  A: passphrase authentication needed
1.243     albertel 9096: 
                   9097: =item *
                   9098: 
                   9099: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9100: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9101: and course level
                   9102: 
                   9103: =item *
                   9104: 
                   9105: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9106: explanation of a user role term
                   9107: 
1.832     raeburn  9108: =item *
                   9109: 
1.935     raeburn  9110: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9111: All arguments are optional. Returns a hash of a roles, either for
                   9112: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9113: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9114: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9115: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9116: For each key, value is set to colon-separated start and end times for
                   9117: the role.  If no username and domain are specified, will default to
1.934     raeburn  9118: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9119: of role statuses (active, future or previous), roles 
                   9120: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9121: to restrict the list of roles reported. If no array ref is 
                   9122: provided for types, will default to return only active roles.
1.834     albertel 9123: 
1.243     albertel 9124: =back
                   9125: 
                   9126: =head2 User Modification
                   9127: 
                   9128: =over 4
                   9129: 
                   9130: =item *
                   9131: 
1.957     raeburn  9132: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9133: user for the level given by URL.  Optional start and end dates (leave empty
                   9134: string or zero for "no date")
1.191     harris41 9135: 
                   9136: =item *
                   9137: 
1.243     albertel 9138: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9139: change a users, password, possible return values are: ok,
                   9140: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9141: refused
1.191     harris41 9142: 
                   9143: =item *
                   9144: 
1.243     albertel 9145: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9146: 
                   9147: =item *
                   9148: 
1.243     albertel 9149: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9150: modify user
1.191     harris41 9151: 
                   9152: =item *
                   9153: 
1.286     matthew  9154: modifystudent
                   9155: 
1.957     raeburn  9156: modify a student's enrollment and identification information.
1.286     matthew  9157: The course id is resolved based on the current users environment.  
                   9158: This means the envoking user must be a course coordinator or otherwise
                   9159: associated with a course.
                   9160: 
1.297     matthew  9161: This call is essentially a wrapper for lonnet::modifyuser and
                   9162: lonnet::modify_student_enrollment
1.286     matthew  9163: 
                   9164: Inputs: 
                   9165: 
                   9166: =over 4
                   9167: 
1.957     raeburn  9168: =item B<$udom> Student's loncapa domain
1.286     matthew  9169: 
1.957     raeburn  9170: =item B<$uname> Student's loncapa login name
1.286     matthew  9171: 
1.957     raeburn  9172: =item B<$uid> Student's id/student number
1.286     matthew  9173: 
1.957     raeburn  9174: =item B<$umode> Student's authentication mode
1.286     matthew  9175: 
1.957     raeburn  9176: =item B<$upass> Student's password
1.286     matthew  9177: 
1.957     raeburn  9178: =item B<$first> Student's first name
1.286     matthew  9179: 
1.957     raeburn  9180: =item B<$middle> Student's middle name
1.286     matthew  9181: 
1.957     raeburn  9182: =item B<$last> Student's last name
1.286     matthew  9183: 
1.957     raeburn  9184: =item B<$gene> Student's generation
1.286     matthew  9185: 
1.957     raeburn  9186: =item B<$usec> Student's section in course
1.286     matthew  9187: 
                   9188: =item B<$end> Unix time of the roles expiration
                   9189: 
                   9190: =item B<$start> Unix time of the roles start date
                   9191: 
                   9192: =item B<$forceid> If defined, allow $uid to be changed
                   9193: 
                   9194: =item B<$desiredhome> server to use as home server for student
                   9195: 
1.957     raeburn  9196: =item B<$email> Student's permanent e-mail address
                   9197: 
                   9198: =item B<$type> Type of enrollment (auto or manual)
                   9199: 
                   9200: =item B<$locktype>
                   9201: 
                   9202: =item B<$cid>
                   9203: 
                   9204: =item B<$selfenroll>
                   9205: 
                   9206: =item B<$context>
                   9207: 
1.286     matthew  9208: =back
1.297     matthew  9209: 
                   9210: =item *
                   9211: 
                   9212: modify_student_enrollment
                   9213: 
                   9214: Change a students enrollment status in a class.  The environment variable
                   9215: 'role.request.course' must be defined for this function to proceed.
                   9216: 
                   9217: Inputs:
                   9218: 
                   9219: =over 4
                   9220: 
                   9221: =item $udom, students domain
                   9222: 
                   9223: =item $uname, students name
                   9224: 
                   9225: =item $uid, students user id
                   9226: 
                   9227: =item $first, students first name
                   9228: 
                   9229: =item $middle
                   9230: 
                   9231: =item $last
                   9232: 
                   9233: =item $gene
                   9234: 
                   9235: =item $usec
                   9236: 
                   9237: =item $end
                   9238: 
                   9239: =item $start
                   9240: 
1.957     raeburn  9241: =item $type
                   9242: 
                   9243: =item $locktype
                   9244: 
                   9245: =item $cid
                   9246: 
                   9247: =item $selfenroll
                   9248: 
                   9249: =item $context
                   9250: 
1.297     matthew  9251: =back
                   9252: 
1.191     harris41 9253: 
                   9254: =item *
                   9255: 
1.243     albertel 9256: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9257: custom role; give a custom role to a user for the level given by URL.  Specify
                   9258: name and domain of role author, and role name
1.191     harris41 9259: 
                   9260: =item *
                   9261: 
1.243     albertel 9262: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9263: 
                   9264: =item *
                   9265: 
1.243     albertel 9266: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9267: 
                   9268: =back
                   9269: 
                   9270: =head2 Course Infomation
                   9271: 
                   9272: =over 4
1.191     harris41 9273: 
                   9274: =item *
                   9275: 
1.631     albertel 9276: coursedescription($courseid) : returns a hash of information about the
                   9277: specified course id, including all environment settings for the
                   9278: course, the description of the course will be in the hash under the
                   9279: key 'description'
1.191     harris41 9280: 
                   9281: =item *
                   9282: 
1.624     albertel 9283: resdata($name,$domain,$type,@which) : request for current parameter
                   9284: setting for a specific $type, where $type is either 'course' or 'user',
                   9285: @what should be a list of parameters to ask about. This routine caches
                   9286: answers for 5 minutes.
1.243     albertel 9287: 
1.877     foxr     9288: =item *
                   9289: 
                   9290: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9291: data base, returning a hash that is keyed by the resource name and has
                   9292: values that are the resource value.  I believe that the timestamps and
                   9293: versions are also returned.
                   9294: 
                   9295: 
1.243     albertel 9296: =back
                   9297: 
                   9298: =head2 Course Modification
                   9299: 
                   9300: =over 4
1.191     harris41 9301: 
                   9302: =item *
                   9303: 
1.243     albertel 9304: writecoursepref($courseid,%prefs) : write preferences (environment
                   9305: database) for a course
1.191     harris41 9306: 
                   9307: =item *
                   9308: 
1.243     albertel 9309: createcourse($udom,$description,$url) : make/modify course
                   9310: 
                   9311: =back
                   9312: 
                   9313: =head2 Resource Subroutines
                   9314: 
                   9315: =over 4
1.191     harris41 9316: 
                   9317: =item *
                   9318: 
1.243     albertel 9319: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9320: 
                   9321: =item *
                   9322: 
1.243     albertel 9323: repcopy($filename) : subscribes to the requested file, and attempts to
                   9324: replicate from the owning library server, Might return
1.607     raeburn  9325: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9326: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9327: resource. Expects the local filesystem pathname
                   9328: (/home/httpd/html/res/....)
                   9329: 
                   9330: =back
                   9331: 
                   9332: =head2 Resource Information
                   9333: 
                   9334: =over 4
1.191     harris41 9335: 
                   9336: =item *
                   9337: 
1.243     albertel 9338: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9339: a vairety of different possible values, $varname should be a request
                   9340: string, and the other parameters can be used to specify who and what
                   9341: one is asking about.
                   9342: 
                   9343: Possible values for $varname are environment.lastname (or other item
                   9344: from the envirnment hash), user.name (or someother aspect about the
                   9345: user), resource.0.maxtries (or some other part and parameter of a
                   9346: resource)
1.204     albertel 9347: 
                   9348: =item *
                   9349: 
1.243     albertel 9350: directcondval($number) : get current value of a condition; reads from a state
                   9351: string
1.204     albertel 9352: 
                   9353: =item *
                   9354: 
1.243     albertel 9355: condval($condidx) : value of condition index based on state
1.204     albertel 9356: 
                   9357: =item *
                   9358: 
1.243     albertel 9359: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9360: resource's metadata, $what should be either a specific key, or either
                   9361: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9362: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9363: 
                   9364: this function automatically caches all requests
1.191     harris41 9365: 
                   9366: =item *
                   9367: 
1.243     albertel 9368: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9369: network of library servers; returns file handle of where SQL and regex results
                   9370: will be stored for query
1.191     harris41 9371: 
                   9372: =item *
                   9373: 
1.243     albertel 9374: symbread($filename) : return symbolic list entry (filename argument optional);
                   9375: returns the data handle
1.191     harris41 9376: 
                   9377: =item *
                   9378: 
1.243     albertel 9379: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9380: a possible symb for the URL in $thisfn, and if is an encryypted
                   9381: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9382: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9383: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9384: 
1.191     harris41 9385: 
                   9386: =item *
                   9387: 
1.243     albertel 9388: symbclean($symb) : removes versions numbers from a symb, returns the
                   9389: cleaned symb
1.191     harris41 9390: 
                   9391: =item *
                   9392: 
1.243     albertel 9393: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9394: course map, user must be in a course for it to work.
1.191     harris41 9395: 
                   9396: =item *
                   9397: 
1.243     albertel 9398: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9399: 
                   9400: =item *
                   9401: 
1.243     albertel 9402: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9403: a random seed, all arguments are optional, if they aren't sent it uses the
                   9404: environment to derive them. Note: if symb isn't sent and it can't get one
                   9405: from &symbread it will use the current time as its return value
1.191     harris41 9406: 
                   9407: =item *
                   9408: 
1.243     albertel 9409: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9410: unfakeable, receipt
1.191     harris41 9411: 
                   9412: =item *
                   9413: 
1.620     albertel 9414: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9415: 
                   9416: =item *
                   9417: 
1.243     albertel 9418: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9419: 
                   9420: =item *
                   9421: 
1.243     albertel 9422: 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 9423: 
                   9424: =item *
                   9425: 
1.243     albertel 9426: 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 9427: 
                   9428: =item *
                   9429: 
1.243     albertel 9430: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9431: 
                   9432: =item *
                   9433: 
1.243     albertel 9434: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9435: forcing spreadsheet to reevaluate the resource scores next time.
                   9436: 
                   9437: =back
                   9438: 
                   9439: =head2 Storing/Retreiving Data
                   9440: 
                   9441: =over 4
1.191     harris41 9442: 
                   9443: =item *
                   9444: 
1.243     albertel 9445: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9446: for this url; hashref needs to be given and should be a \%hashname; the
                   9447: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9448: be derived from the env
1.191     harris41 9449: 
                   9450: =item *
                   9451: 
1.243     albertel 9452: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9453: uses critical subroutine
1.191     harris41 9454: 
                   9455: =item *
                   9456: 
1.243     albertel 9457: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9458: all args are optional
1.191     harris41 9459: 
                   9460: =item *
                   9461: 
1.717     albertel 9462: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9463: dumps the complete (or key matching regexp) namespace into a hash
                   9464: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9465: normally &store()ed into
                   9466: 
                   9467: $range should be either an integer '100' (give me the first 100
                   9468:                                            matching records)
                   9469:               or be  two integers sperated by a - with no spaces
                   9470:                  '30-50' (give me the 30th through the 50th matching
                   9471:                           records)
                   9472: 
                   9473: 
                   9474: =item *
                   9475: 
                   9476: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9477: replaces a &store() version of data with a replacement set of data
                   9478: for a particular resource in a namespace passed in the $storehash hash 
                   9479: reference
                   9480: 
                   9481: =item *
                   9482: 
1.243     albertel 9483: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9484: works very similar to store/cstore, but all data is stored in a
                   9485: temporary location and can be reset using tmpreset, $storehash should
                   9486: be a hash reference, returns nothing on success
1.191     harris41 9487: 
                   9488: =item *
                   9489: 
1.243     albertel 9490: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9491: similar to restore, but all data is stored in a temporary location and
                   9492: can be reset using tmpreset. Returns a hash of values on success,
                   9493: error string otherwise.
1.191     harris41 9494: 
                   9495: =item *
                   9496: 
1.243     albertel 9497: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9498: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9499: 
                   9500: =item *
                   9501: 
1.243     albertel 9502: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9503: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9504: 
                   9505: =item *
                   9506: 
1.243     albertel 9507: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9508: namesp ($udom and $uname are optional)
1.191     harris41 9509: 
                   9510: =item *
                   9511: 
1.702     albertel 9512: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9513: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9514: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9515: 
1.702     albertel 9516: $range should be either an integer '100' (give me the first 100
                   9517:                                            matching records)
                   9518:               or be  two integers sperated by a - with no spaces
                   9519:                  '30-50' (give me the 30th through the 50th matching
                   9520:                           records)
1.449     matthew  9521: =item *
                   9522: 
                   9523: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9524: $store can be a scalar, an array reference, or if the amount to be 
                   9525: incremented is > 1, a hash reference.
                   9526: 
                   9527: ($udom and $uname are optional)
1.191     harris41 9528: 
                   9529: =item *
                   9530: 
1.243     albertel 9531: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9532: ($udom and $uname are optional)
1.191     harris41 9533: 
                   9534: =item *
                   9535: 
1.243     albertel 9536: cput($namespace,$storehash,$udom,$uname) : critical put
                   9537: ($udom and $uname are optional)
1.191     harris41 9538: 
                   9539: =item *
                   9540: 
1.748     albertel 9541: newput($namespace,$storehash,$udom,$uname) :
                   9542: 
                   9543: Attempts to store the items in the $storehash, but only if they don't
                   9544: currently exist, if this succeeds you can be certain that you have 
                   9545: successfully created a new key value pair in the $namespace db.
                   9546: 
                   9547: 
                   9548: Args:
                   9549:  $namespace: name of database to store values to
                   9550:  $storehash: hashref to store to the db
                   9551:  $udom: (optional) domain of user containing the db
                   9552:  $uname: (optional) name of user caontaining the db
                   9553: 
                   9554: Returns:
                   9555:  'ok' -> succeeded in storing all keys of $storehash
                   9556:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9557:                         least <key> already existed in the db (other
                   9558:                         requested keys may also already exist)
                   9559:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9560:  'con_lost' -> unable to contact request server
                   9561:  'refused' -> action was not allowed by remote machine
                   9562: 
                   9563: 
                   9564: =item *
                   9565: 
1.243     albertel 9566: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9567: reference filled in from namesp (encrypts the return communication)
                   9568: ($udom and $uname are optional)
1.191     harris41 9569: 
                   9570: =item *
                   9571: 
1.243     albertel 9572: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9573: critical subroutine
                   9574: 
1.806     raeburn  9575: =item *
                   9576: 
1.860     raeburn  9577: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9578: array reference filled in from namespace found in domain level on either
                   9579: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9580: 
                   9581: =item *
                   9582: 
1.860     raeburn  9583: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9584: domain level either on specified domain server ($uhome) or primary domain 
                   9585: server ($udom and $uhome are optional)
1.806     raeburn  9586: 
1.943     raeburn  9587: =item * 
                   9588: 
                   9589: get_domain_defaults($target_domain) : returns hash with defaults for
                   9590: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9591: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9592: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9593: Values are retrieved from cache (if current), or from domain's configuration.db
                   9594: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9595: or lonTabs/domain.tab. 
                   9596: 
                   9597: %domdefaults = &get_auth_defaults($target_domain);
                   9598: 
1.243     albertel 9599: =back
                   9600: 
                   9601: =head2 Network Status Functions
                   9602: 
                   9603: =over 4
1.191     harris41 9604: 
                   9605: =item *
                   9606: 
                   9607: dirlist($uri) : return directory list based on URI
                   9608: 
                   9609: =item *
                   9610: 
1.243     albertel 9611: spareserver() : find server with least workload from spare.tab
                   9612: 
                   9613: =back
                   9614: 
                   9615: =head2 Apache Request
                   9616: 
                   9617: =over 4
1.191     harris41 9618: 
                   9619: =item *
                   9620: 
1.243     albertel 9621: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9622: localhost, posts hash
                   9623: 
                   9624: =back
                   9625: 
                   9626: =head2 Data to String to Data
                   9627: 
                   9628: =over 4
1.191     harris41 9629: 
                   9630: =item *
                   9631: 
1.243     albertel 9632: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9633: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9634: 
                   9635: =item *
                   9636: 
1.243     albertel 9637: hashref2str($hashref) : convert a hashref into a string complete with
                   9638: escaping and '=' and '&' separators, supports elements that are
                   9639: arrayrefs and hashrefs
1.191     harris41 9640: 
                   9641: =item *
                   9642: 
1.243     albertel 9643: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9644: with escaping and '&' separators, supports elements that are arrayrefs
                   9645: and hashrefs
1.191     harris41 9646: 
                   9647: =item *
                   9648: 
1.243     albertel 9649: str2hash($string) : convert string to hash using unescaping and
                   9650: splitting on '=' and '&', supports elements that are arrayrefs and
                   9651: hashrefs
1.191     harris41 9652: 
                   9653: =item *
                   9654: 
1.243     albertel 9655: str2array($string) : convert string to hash using unescaping and
                   9656: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9657: 
                   9658: =back
                   9659: 
                   9660: =head2 Logging Routines
                   9661: 
                   9662: =over 4
                   9663: 
                   9664: These routines allow one to make log messages in the lonnet.log and
                   9665: lonnet.perm logfiles.
1.191     harris41 9666: 
                   9667: =item *
                   9668: 
1.243     albertel 9669: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9670: 
                   9671: =item *
                   9672: 
1.243     albertel 9673: logthis() : append message to the normal lonnet.log file, it gets
                   9674: preiodically rolled over and deleted.
1.191     harris41 9675: 
                   9676: =item *
                   9677: 
1.243     albertel 9678: logperm() : append a permanent message to lonnet.perm.log, this log
                   9679: file never gets deleted by any automated portion of the system, only
                   9680: messages of critical importance should go in here.
                   9681: 
                   9682: =back
                   9683: 
                   9684: =head2 General File Helper Routines
                   9685: 
                   9686: =over 4
1.191     harris41 9687: 
                   9688: =item *
                   9689: 
1.481     raeburn  9690: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9691: (a) files in /uploaded
                   9692:   (i) If a local copy of the file exists - 
                   9693:       compares modification date of local copy with last-modified date for 
                   9694:       definitive version stored on home server for course. If local copy is 
                   9695:       stale, requests a new version from the home server and stores it. 
                   9696:       If the original has been removed from the home server, then local copy 
                   9697:       is unlinked.
                   9698:   (ii) If local copy does not exist -
                   9699:       requests the file from the home server and stores it. 
                   9700:   
                   9701:   If $caller is 'uploadrep':  
                   9702:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9703:     for request for files originally uploaded via DOCS. 
                   9704:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9705:   
                   9706:   Otherwise:
                   9707:      This indicates a call from the content generation phase of the request.
                   9708:      -  returns the entire contents of the file or -1.
                   9709:      
                   9710: (b) files in /res
                   9711:    - returns the entire contents of a file or -1; 
                   9712:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9713: 
1.712     albertel 9714: 
                   9715: =item *
                   9716: 
                   9717: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9718:                   reference
                   9719: 
                   9720: returns either a stat() list of data about the file or an empty list
                   9721: if the file doesn't exist or couldn't find out about it (connection
                   9722: problems or user unknown)
                   9723: 
1.191     harris41 9724: =item *
                   9725: 
1.243     albertel 9726: filelocation($dir,$file) : returns file system location of a file
                   9727: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9728: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9729: and a file of ../bob will become /a/bob)
1.191     harris41 9730: 
                   9731: =item *
                   9732: 
                   9733: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9734: filelocation except for hrefs
                   9735: 
                   9736: =item *
                   9737: 
                   9738: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9739: 
1.243     albertel 9740: =back
                   9741: 
1.608     albertel 9742: =head2 Usererfile file routines (/uploaded*)
                   9743: 
                   9744: =over 4
                   9745: 
                   9746: =item *
                   9747: 
                   9748: userfileupload(): main rotine for putting a file in a user or course's
                   9749:                   filespace, arguments are,
                   9750: 
1.620     albertel 9751:  formname - required - this is the name of the element in $env where the
1.608     albertel 9752:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9753:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9754:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9755:  coursedoc - if true, store the file in the course of the active role
                   9756:              of the current user
                   9757:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9758:          if undefined, it will be placed in "unknown"
                   9759: 
                   9760:  (This routine calls clean_filename() to remove any dangerous
                   9761:  characters from the filename, and then calls finuserfileupload() to
                   9762:  complete the transaction)
                   9763: 
                   9764:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9765:  and /adm/notfound.html if unsuccessful
                   9766: 
                   9767: =item *
                   9768: 
                   9769: clean_filename(): routine for cleaing a filename up for storage in
                   9770:                  userfile space, argument is:
                   9771: 
                   9772:  filename - proposed filename
                   9773: 
                   9774: returns: the new clean filename
                   9775: 
                   9776: =item *
                   9777: 
                   9778: finishuserfileupload(): routine that creaes and sends the file to
                   9779: userspace, probably shouldn't be called directly
                   9780: 
                   9781:   docuname: username or courseid of destination for the file
                   9782:   docudom: domain of user/course of destination for the file
                   9783:   formname: same as for userfileupload()
                   9784:   fname: filename (inculding subdirectories) for the file
                   9785: 
                   9786:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9787:  and /adm/notfound.html if unsuccessful
                   9788: 
                   9789: =item *
                   9790: 
                   9791: renameuserfile(): renames an existing userfile to a new name
                   9792: 
                   9793:   Args:
                   9794:    docuname: username or courseid of destination for the file
                   9795:    docudom: domain of user/course of destination for the file
                   9796:    old: current file name (including any subdirs under userfiles)
                   9797:    new: desired file name (including any subdirs under userfiles)
                   9798: 
                   9799: =item *
                   9800: 
                   9801: mkdiruserfile(): creates a directory is a userfiles dir
                   9802: 
                   9803:   Args:
                   9804:    docuname: username or courseid of destination for the file
                   9805:    docudom: domain of user/course of destination for the file
                   9806:    dir: dir to create (including any subdirs under userfiles)
                   9807: 
                   9808: =item *
                   9809: 
                   9810: removeuserfile(): removes a file that exists in userfiles
                   9811: 
                   9812:   Args:
                   9813:    docuname: username or courseid of destination for the file
                   9814:    docudom: domain of user/course of destination for the file
                   9815:    fname: filname to delete (including any subdirs under userfiles)
                   9816: 
                   9817: =item *
                   9818: 
                   9819: removeuploadedurl(): convience function for removeuserfile()
                   9820: 
                   9821:   Args:
                   9822:    url:  a full /uploaded/... url to delete
                   9823: 
1.747     albertel 9824: =item * 
                   9825: 
                   9826: get_portfile_permissions():
                   9827:   Args:
                   9828:     domain: domain of user or course contain the portfolio files
                   9829:     user: name of user or num of course contain the portfolio files
                   9830:   Returns:
                   9831:     hashref of a dump of the proper file_permissions.db
                   9832:    
                   9833: 
                   9834: =item * 
                   9835: 
                   9836: get_access_controls():
                   9837: 
                   9838: Args:
                   9839:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9840:   group: (optional) the group you want the files associated with
                   9841:   file: (optional) the file you want access info on
                   9842: 
                   9843: Returns:
1.749     raeburn  9844:     a hash (keys are file names) of hashes containing
                   9845:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9846:         values are XML containing access control settings (see below) 
1.747     albertel 9847: 
                   9848: Internal notes:
                   9849: 
1.749     raeburn  9850:  access controls are stored in file_permissions.db as key=value pairs.
                   9851:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9852:         where scope -> public,guest,course,group,domains or users.
                   9853:               end -> UNIX time for end of access (0 -> no end date)
                   9854:               start -> UNIX time for start of access
                   9855: 
                   9856:     value -> XML description of access control
                   9857:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9858:             <start></start>
                   9859:             <end></end>
                   9860: 
                   9861:             <password></password>  for scope type = guest
                   9862: 
                   9863:             <domain></domain>     for scope type = course or group
                   9864:             <number></number>
                   9865:             <roles id="">
                   9866:              <role></role>
                   9867:              <access></access>
                   9868:              <section></section>
                   9869:              <group></group>
                   9870:             </roles>
                   9871: 
                   9872:             <dom></dom>         for scope type = domains
                   9873: 
                   9874:             <users>             for scope type = users
                   9875:              <user>
                   9876:               <uname></uname>
                   9877:               <udom></udom>
                   9878:              </user>
                   9879:             </users>
                   9880:            </scope> 
                   9881:               
                   9882:  Access data is also aggregated for each file in an additional key=value pair:
                   9883:  key -> path to file/file_name\0accesscontrol 
                   9884:  value -> reference to hash
                   9885:           hash contains key = value pairs
                   9886:           where key = uniqueID:scope_end_start
                   9887:                 value = UNIX time record was last updated
                   9888: 
                   9889:           Used to improve speed of look-ups of access controls for each file.  
                   9890:  
                   9891:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9892: 
                   9893: modify_access_controls():
                   9894: 
                   9895: Modifies access controls for a portfolio file
                   9896: Args
                   9897: 1. file name
                   9898: 2. reference to hash of required changes,
                   9899: 3. domain
                   9900: 4. username
                   9901:   where domain,username are the domain of the portfolio owner 
                   9902:   (either a user or a course) 
                   9903: 
                   9904: Returns:
                   9905: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9906: 2. result of deletions ('ok' or 'error', with error message).
                   9907: 3. reference to hash of any new or updated access controls.
                   9908: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9909:    key = integer (inbound ID)
                   9910:    value = uniqueID  
1.747     albertel 9911: 
1.608     albertel 9912: =back
                   9913: 
1.243     albertel 9914: =head2 HTTP Helper Routines
                   9915: 
                   9916: =over 4
                   9917: 
1.191     harris41 9918: =item *
                   9919: 
                   9920: escape() : unpack non-word characters into CGI-compatible hex codes
                   9921: 
                   9922: =item *
                   9923: 
                   9924: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9925: 
1.243     albertel 9926: =back
                   9927: 
                   9928: =head1 PRIVATE SUBROUTINES
                   9929: 
                   9930: =head2 Underlying communication routines (Shouldn't call)
                   9931: 
                   9932: =over 4
                   9933: 
                   9934: =item *
                   9935: 
                   9936: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9937: 
                   9938: =item *
                   9939: 
                   9940: reply() : uses subreply to send a message to remote machine, logs all failures
                   9941: 
                   9942: =item *
                   9943: 
                   9944: critical() : passes a critical message to another server; if cannot
                   9945: get through then place message in connection buffer directory and
                   9946: returns con_delayed, if incapable of saving message, returns
                   9947: con_failed
                   9948: 
                   9949: =item *
                   9950: 
                   9951: reconlonc() : tries to reconnect lonc client processes.
                   9952: 
                   9953: =back
                   9954: 
                   9955: =head2 Resource Access Logging
                   9956: 
                   9957: =over 4
                   9958: 
                   9959: =item *
                   9960: 
                   9961: flushcourselogs() : flush (save) buffer logs and access logs
                   9962: 
                   9963: =item *
                   9964: 
                   9965: courselog($what) : save message for course in hash
                   9966: 
                   9967: =item *
                   9968: 
                   9969: courseacclog($what) : save message for course using &courselog().  Perform
                   9970: special processing for specific resource types (problems, exams, quizzes, etc).
                   9971: 
1.191     harris41 9972: =item *
                   9973: 
                   9974: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9975: as a PerlChildExitHandler
1.243     albertel 9976: 
                   9977: =back
                   9978: 
                   9979: =head2 Other
                   9980: 
                   9981: =over 4
                   9982: 
                   9983: =item *
                   9984: 
                   9985: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9986: 
                   9987: =back
                   9988: 
                   9989: =cut
1.877     foxr     9990: 

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