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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.957   ! raeburn     4: # $Id: lonnet.pm,v 1.956 2008/04/21 15:58:12 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,
                     42:     %courseownerbuf, %coursetypebuf);
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.369     albertel  529: # ------------------------------------------ Find out current server userload
                    530: sub userload {
                    531:     my $numusers=0;
                    532:     {
                    533: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    534: 	my $filename;
                    535: 	my $curtime=time;
                    536: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  537: 	    next if ($filename eq '.' || $filename eq '..');
                    538: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  539: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  540: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  541: 	}
                    542: 	closedir(LONIDS);
                    543:     }
                    544:     my $userloadpercent=0;
                    545:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    546:     if ($maxuserload) {
1.371     albertel  547: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  548:     }
1.372     albertel  549:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  550:     return $userloadpercent;
1.283     www       551: }
                    552: 
                    553: # ------------------------------------------ Fight off request when overloaded
                    554: 
                    555: sub overloaderror {
                    556:     my ($r,$checkserver)=@_;
                    557:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    558:     my $loadavg;
                    559:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  560:        open(my $loadfile,'/proc/loadavg');
1.283     www       561:        $loadavg=<$loadfile>;
                    562:        $loadavg =~ s/\s.*//g;
1.285     matthew   563:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  564:        close($loadfile);
1.283     www       565:     } else {
                    566:        $loadavg=&reply('load',$checkserver);
                    567:     }
1.285     matthew   568:     my $overload=$loadavg-100;
1.283     www       569:     if ($overload>0) {
1.285     matthew   570: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       571:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       572:         return 413;
1.283     www       573:     }    
                    574:     return '';
1.5       www       575: }
1.1       albertel  576: 
                    577: # ------------------------------ Find server with least workload from spare.tab
1.11      www       578: 
1.1       albertel  579: sub spareserver {
1.670     albertel  580:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  581:     my $spare_server;
1.370     albertel  582:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  583:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    584:                                                      :  $userloadpercent;
                    585:     
                    586:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    587: 	($spare_server, $lowest_load) =
                    588: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    589:     }
                    590: 
                    591:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    592: 
                    593:     if (!$found_server) {
                    594: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    595: 	    ($spare_server, $lowest_load) =
                    596: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    597: 	}
                    598:     }
                    599: 
                    600:     if (!$want_server_name) {
1.838     albertel  601: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  602:     }
                    603:     return $spare_server;
                    604: }
                    605: 
                    606: sub compare_server_load {
                    607:     my ($try_server, $spare_server, $lowest_load) = @_;
                    608: 
                    609:     my $loadans     = &reply('load',    $try_server);
                    610:     my $userloadans = &reply('userload',$try_server);
                    611: 
                    612:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    613: 	next; #didn't get a number from the server
                    614:     }
                    615: 
                    616:     my $load;
                    617:     if ($loadans =~ /\d/) {
                    618: 	if ($userloadans =~ /\d/) {
                    619: 	    #both are numbers, pick the bigger one
                    620: 	    $load = ($loadans > $userloadans) ? $loadans 
                    621: 		                              : $userloadans;
1.411     albertel  622: 	} else {
1.784     albertel  623: 	    $load = $loadans;
1.411     albertel  624: 	}
1.784     albertel  625:     } else {
                    626: 	$load = $userloadans;
                    627:     }
                    628: 
                    629:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    630: 	$spare_server = $try_server;
                    631: 	$lowest_load  = $load;
1.370     albertel  632:     }
1.784     albertel  633:     return ($spare_server,$lowest_load);
1.202     matthew   634: }
1.914     albertel  635: 
                    636: # --------------------------- ask offload servers if user already has a session
                    637: sub find_existing_session {
                    638:     my ($udom,$uname) = @_;
                    639:     foreach my $try_server (@{ $spareid{'primary'} },
                    640: 			    @{ $spareid{'default'} }) {
                    641: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    642:     }
                    643:     return;
                    644: }
                    645: 
                    646: # -------------------------------- ask if server already has a session for user
                    647: sub has_user_session {
                    648:     my ($lonid,$udom,$uname) = @_;
                    649:     my $result = &reply(join(':','userhassession',
                    650: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    651:     return 1 if ($result eq 'ok');
                    652: 
                    653:     return 0;
                    654: }
                    655: 
1.202     matthew   656: # --------------------------------------------- Try to change a user's password
                    657: 
                    658: sub changepass {
1.799     raeburn   659:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   660:     $currentpass = &escape($currentpass);
                    661:     $newpass     = &escape($newpass);
1.799     raeburn   662:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   663: 		       $server);
                    664:     if (! $answer) {
                    665: 	&logthis("No reply on password change request to $server ".
                    666: 		 "by $uname in domain $udom.");
                    667:     } elsif ($answer =~ "^ok") {
                    668:         &logthis("$uname in $udom successfully changed their password ".
                    669: 		 "on $server.");
                    670:     } elsif ($answer =~ "^pwchange_failure") {
                    671: 	&logthis("$uname in $udom was unable to change their password ".
                    672: 		 "on $server.  The action was blocked by either lcpasswd ".
                    673: 		 "or pwchange");
                    674:     } elsif ($answer =~ "^non_authorized") {
                    675:         &logthis("$uname in $udom did not get their password correct when ".
                    676: 		 "attempting to change it on $server.");
                    677:     } elsif ($answer =~ "^auth_mode_error") {
                    678:         &logthis("$uname in $udom attempted to change their password despite ".
                    679: 		 "not being locally or internally authenticated on $server.");
                    680:     } elsif ($answer =~ "^unknown_user") {
                    681:         &logthis("$uname in $udom attempted to change their password ".
                    682: 		 "on $server but were unable to because $server is not ".
                    683: 		 "their home server.");
                    684:     } elsif ($answer =~ "^refused") {
                    685: 	&logthis("$server refused to change $uname in $udom password because ".
                    686: 		 "it was sent an unencrypted request to change the password.");
                    687:     }
                    688:     return $answer;
1.1       albertel  689: }
                    690: 
1.169     harris41  691: # ----------------------- Try to determine user's current authentication scheme
                    692: 
                    693: sub queryauthenticate {
                    694:     my ($uname,$udom)=@_;
1.456     albertel  695:     my $uhome=&homeserver($uname,$udom);
                    696:     if (!$uhome) {
                    697: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    698: 	return 'no_host';
                    699:     }
                    700:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    701:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    702: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  703:     }
1.456     albertel  704:     return $answer;
1.169     harris41  705: }
                    706: 
1.1       albertel  707: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       708: 
1.1       albertel  709: sub authenticate {
1.952     raeburn   710:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  711:     $upass=&escape($upass);
                    712:     $uname= &LONCAPA::clean_username($uname);
1.836     www       713:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   714:     my $newhome;
1.836     www       715:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    716: # Maybe the machine was offline and only re-appeared again recently?
                    717:         &reconlonc();
                    718: # One more
1.952     raeburn   719: 	$uhome=&homeserver($uname,$udom,1);
                    720:         if (($uhome eq 'no_host') && $checkdefauth) {
                    721:             if (defined(&domain($udom,'primary'))) {
                    722:                 $newhome=&domain($udom,'primary');
                    723:             }
                    724:             if ($newhome ne '') {
                    725:                 $uhome = $newhome;
                    726:             }
                    727:         }
1.836     www       728: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    729: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   730: 	    return 'no_host';
                    731:         }
1.1       albertel  732:     }
1.952     raeburn   733:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  734:     if ($answer eq 'authorized') {
1.952     raeburn   735:         if ($newhome) {
                    736:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    737:             return 'no_account_on_host'; 
                    738:         } else {
                    739:             &logthis("User $uname at $udom authorized by $uhome");
                    740:             return $uhome;
                    741:         }
1.471     albertel  742:     }
                    743:     if ($answer eq 'non_authorized') {
                    744: 	&logthis("User $uname at $udom rejected by $uhome");
                    745: 	return 'no_host'; 
1.9       www       746:     }
1.471     albertel  747:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  748:     return 'no_host';
                    749: }
                    750: 
                    751: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       752: 
1.599     albertel  753: my %homecache;
1.1       albertel  754: sub homeserver {
1.230     stredwic  755:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  756:     my $index="$uname:$udom";
1.426     albertel  757: 
1.599     albertel  758:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  759: 
                    760:     my %servers = &get_servers($udom,'library');
                    761:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  762:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  763: 		 exists($badServerCache{$tryserver}));
1.841     albertel  764: 
                    765: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    766: 	if ($answer eq 'found') {
                    767: 	    delete($badServerCache{$tryserver}); 
                    768: 	    return $homecache{$index}=$tryserver;
                    769: 	} elsif ($answer eq 'no_host') {
                    770: 	    $badServerCache{$tryserver}=1;
                    771: 	}
1.1       albertel  772:     }    
                    773:     return 'no_host';
1.70      www       774: }
                    775: 
                    776: # ------------------------------------- Find the usernames behind a list of IDs
                    777: 
                    778: sub idget {
                    779:     my ($udom,@ids)=@_;
                    780:     my %returnhash=();
                    781:     
1.841     albertel  782:     my %servers = &get_servers($udom,'library');
                    783:     foreach my $tryserver (keys(%servers)) {
                    784: 	my $idlist=join('&',@ids);
                    785: 	$idlist=~tr/A-Z/a-z/; 
                    786: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    787: 	my @answer=();
                    788: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    789: 	    @answer=split(/\&/,$reply);
                    790: 	}                    ;
                    791: 	my $i;
                    792: 	for ($i=0;$i<=$#ids;$i++) {
                    793: 	    if ($answer[$i]) {
                    794: 		$returnhash{$ids[$i]}=$answer[$i];
                    795: 	    } 
                    796: 	}
                    797:     } 
1.70      www       798:     return %returnhash;
                    799: }
                    800: 
                    801: # ------------------------------------- Find the IDs behind a list of usernames
                    802: 
                    803: sub idrget {
                    804:     my ($udom,@unames)=@_;
                    805:     my %returnhash=();
1.800     albertel  806:     foreach my $uname (@unames) {
                    807:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  808:     }
1.70      www       809:     return %returnhash;
                    810: }
                    811: 
                    812: # ------------------------------- Store away a list of names and associated IDs
                    813: 
                    814: sub idput {
                    815:     my ($udom,%ids)=@_;
                    816:     my %servers=();
1.800     albertel  817:     foreach my $uname (keys(%ids)) {
                    818: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    819:         my $uhom=&homeserver($uname,$udom);
1.70      www       820:         if ($uhom ne 'no_host') {
1.800     albertel  821:             my $id=&escape($ids{$uname});
1.70      www       822:             $id=~tr/A-Z/a-z/;
1.800     albertel  823:             my $esc_unam=&escape($uname);
1.70      www       824: 	    if ($servers{$uhom}) {
1.800     albertel  825: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       826:             } else {
1.800     albertel  827:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       828:             }
                    829:         }
1.191     harris41  830:     }
1.800     albertel  831:     foreach my $server (keys(%servers)) {
                    832:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  833:     }
1.344     www       834: }
                    835: 
1.806     raeburn   836: # ------------------------------------------- get items from domain db files   
                    837: 
                    838: sub get_dom {
1.860     raeburn   839:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   840:     my $items='';
                    841:     foreach my $item (@$storearr) {
                    842:         $items.=&escape($item).'&';
                    843:     }
                    844:     $items=~s/\&$//;
1.860     raeburn   845:     if (!$udom) {
                    846:         $udom=$env{'user.domain'};
                    847:         if (defined(&domain($udom,'primary'))) {
                    848:             $uhome=&domain($udom,'primary');
                    849:         } else {
1.874     albertel  850:             undef($uhome);
1.860     raeburn   851:         }
                    852:     } else {
                    853:         if (!$uhome) {
                    854:             if (defined(&domain($udom,'primary'))) {
                    855:                 $uhome=&domain($udom,'primary');
                    856:             }
                    857:         }
                    858:     }
                    859:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   860:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   861:         my %returnhash;
1.875     albertel  862:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   863:             return %returnhash;
                    864:         }
1.806     raeburn   865:         my @pairs=split(/\&/,$rep);
                    866:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    867:             return @pairs;
                    868:         }
                    869:         my $i=0;
                    870:         foreach my $item (@$storearr) {
                    871:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    872:             $i++;
                    873:         }
                    874:         return %returnhash;
                    875:     } else {
1.880     banghart  876:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   877:     }
                    878: }
                    879: 
                    880: # -------------------------------------------- put items in domain db files 
                    881: 
                    882: sub put_dom {
1.860     raeburn   883:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    884:     if (!$udom) {
                    885:         $udom=$env{'user.domain'};
                    886:         if (defined(&domain($udom,'primary'))) {
                    887:             $uhome=&domain($udom,'primary');
                    888:         } else {
1.874     albertel  889:             undef($uhome);
1.860     raeburn   890:         }
                    891:     } else {
                    892:         if (!$uhome) {
                    893:             if (defined(&domain($udom,'primary'))) {
                    894:                 $uhome=&domain($udom,'primary');
                    895:             }
                    896:         }
                    897:     } 
                    898:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   899:         my $items='';
                    900:         foreach my $item (keys(%$storehash)) {
                    901:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    902:         }
                    903:         $items=~s/\&$//;
                    904:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    905:     } else {
1.860     raeburn   906:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   907:     }
                    908: }
                    909: 
1.837     raeburn   910: sub retrieve_inst_usertypes {
                    911:     my ($udom) = @_;
                    912:     my (%returnhash,@order);
1.846     albertel  913:     if (defined(&domain($udom,'primary'))) {
                    914:         my $uhome=&domain($udom,'primary');
1.837     raeburn   915:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    916:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    917:         my @pairs=split(/\&/,$hashitems);
                    918:         foreach my $item (@pairs) {
                    919:             my ($key,$value)=split(/=/,$item,2);
                    920:             $key = &unescape($key);
                    921:             next if ($key =~ /^error: 2 /);
                    922:             $returnhash{$key}=&thaw_unescape($value);
                    923:         }
                    924:         my @esc_order = split(/\&/,$orderitems);
                    925:         foreach my $item (@esc_order) {
                    926:             push(@order,&unescape($item));
                    927:         }
                    928:     } else {
                    929:         &logthis("get_dom failed - no primary domain server for $udom");
                    930:     }
                    931:     return (\%returnhash,\@order);
                    932: }
                    933: 
1.868     raeburn   934: sub is_domainimage {
                    935:     my ($url) = @_;
                    936:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    937:         if (&domain($1) ne '') {
                    938:             return '1';
                    939:         }
                    940:     }
                    941:     return;
                    942: }
                    943: 
1.899     raeburn   944: sub inst_directory_query {
                    945:     my ($srch) = @_;
                    946:     my $udom = $srch->{'srchdomain'};
                    947:     my %results;
                    948:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   949:     my $outcome;
1.899     raeburn   950:     if ($homeserver ne '') {
1.904     albertel  951: 	my $queryid=&reply("querysend:instdirsearch:".
                    952: 			   &escape($srch->{'srchby'}).':'.
                    953: 			   &escape($srch->{'srchterm'}).':'.
                    954: 			   &escape($srch->{'srchtype'}),$homeserver);
                    955: 	my $host=&hostname($homeserver);
                    956: 	if ($queryid !~/^\Q$host\E\_/) {
                    957: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    958: 	    return;
                    959: 	}
                    960: 	my $response = &get_query_reply($queryid);
                    961: 	my $maxtries = 5;
                    962: 	my $tries = 1;
                    963: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    964: 	    $response = &get_query_reply($queryid);
                    965: 	    $tries ++;
                    966: 	}
                    967: 
                    968:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   969:             if ($response eq 'unavailable') {
                    970:                 $outcome = $response;
                    971:             } else {
                    972:                 $outcome = 'ok';
                    973:                 my @matches = split(/\n/,$response);
                    974:                 foreach my $match (@matches) {
                    975:                     my ($key,$value) = split(/=/,$match);
                    976:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    977:                 }
1.899     raeburn   978:             }
                    979:         }
                    980:     }
1.909     raeburn   981:     return ($outcome,%results);
1.899     raeburn   982: }
                    983: 
                    984: sub usersearch {
                    985:     my ($srch) = @_;
                    986:     my $dom = $srch->{'srchdomain'};
                    987:     my %results;
                    988:     my %libserv = &all_library();
                    989:     my $query = 'usersearch';
                    990:     foreach my $tryserver (keys(%libserv)) {
                    991:         if (&host_domain($tryserver) eq $dom) {
                    992:             my $host=&hostname($tryserver);
                    993:             my $queryid=
1.911     raeburn   994:                 &reply("querysend:".&escape($query).':'.
                    995:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   996:                        &escape($srch->{'srchtype'}).':'.
                    997:                        &escape($srch->{'srchterm'}),$tryserver);
                    998:             if ($queryid !~/^\Q$host\E\_/) {
                    999:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1000:                 next;
1.899     raeburn  1001:             }
                   1002:             my $reply = &get_query_reply($queryid);
                   1003:             my $maxtries = 1;
                   1004:             my $tries = 1;
                   1005:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1006:                 $reply = &get_query_reply($queryid);
                   1007:                 $tries ++;
                   1008:             }
                   1009:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1010:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1011:             } else {
1.911     raeburn  1012:                 my @matches;
                   1013:                 if ($reply =~ /\n/) {
                   1014:                     @matches = split(/\n/,$reply);
                   1015:                 } else {
                   1016:                     @matches = split(/\&/,$reply);
                   1017:                 }
1.899     raeburn  1018:                 foreach my $match (@matches) {
                   1019:                     my ($uname,$udom,%userhash);
1.911     raeburn  1020:                     foreach my $entry (split(/:/,$match)) {
                   1021:                         my ($key,$value) =
                   1022:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1023:                         $userhash{$key} = $value;
                   1024:                         if ($key eq 'username') {
                   1025:                             $uname = $value;
                   1026:                         } elsif ($key eq 'domain') {
                   1027:                             $udom = $value;
1.911     raeburn  1028:                         }
1.899     raeburn  1029:                     }
                   1030:                     $results{$uname.':'.$udom} = \%userhash;
                   1031:                 }
                   1032:             }
                   1033:         }
                   1034:     }
                   1035:     return %results;
                   1036: }
                   1037: 
1.912     raeburn  1038: sub get_instuser {
                   1039:     my ($udom,$uname,$id) = @_;
                   1040:     my $homeserver = &domain($udom,'primary');
                   1041:     my ($outcome,%results);
                   1042:     if ($homeserver ne '') {
                   1043:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1044:                            &escape($id).':'.&escape($udom),$homeserver);
                   1045:         my $host=&hostname($homeserver);
                   1046:         if ($queryid !~/^\Q$host\E\_/) {
                   1047:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1048:             return;
                   1049:         }
                   1050:         my $response = &get_query_reply($queryid);
                   1051:         my $maxtries = 5;
                   1052:         my $tries = 1;
                   1053:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1054:             $response = &get_query_reply($queryid);
                   1055:             $tries ++;
                   1056:         }
                   1057:         if (!&error($response) && $response ne 'refused') {
                   1058:             if ($response eq 'unavailable') {
                   1059:                 $outcome = $response;
                   1060:             } else {
                   1061:                 $outcome = 'ok';
                   1062:                 my @matches = split(/\n/,$response);
                   1063:                 foreach my $match (@matches) {
                   1064:                     my ($key,$value) = split(/=/,$match);
                   1065:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1066:                 }
                   1067:             }
                   1068:         }
                   1069:     }
                   1070:     my %userinfo;
                   1071:     if (ref($results{$uname}) eq 'HASH') {
                   1072:         %userinfo = %{$results{$uname}};
                   1073:     } 
                   1074:     return ($outcome,%userinfo);
                   1075: }
                   1076: 
                   1077: sub inst_rulecheck {
1.923     raeburn  1078:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1079:     my %returnhash;
                   1080:     if ($udom ne '') {
                   1081:         if (ref($rules) eq 'ARRAY') {
                   1082:             @{$rules} = map {&escape($_);} (@{$rules});
                   1083:             my $rulestr = join(':',@{$rules});
                   1084:             my $homeserver=&domain($udom,'primary');
                   1085:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1086:                 my $response;
                   1087:                 if ($item eq 'username') {                
                   1088:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1089:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1090:                                               $homeserver));
1.923     raeburn  1091:                 } elsif ($item eq 'id') {
                   1092:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1093:                                               ':'.&escape($id).':'.$rulestr,
                   1094:                                               $homeserver));
1.945     raeburn  1095:                 } elsif ($item eq 'selfcreate') {
                   1096:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1097:                                                &escape($udom).':'.&escape($uname).
                   1098:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1099:                 }
1.912     raeburn  1100:                 if ($response ne 'refused') {
                   1101:                     my @pairs=split(/\&/,$response);
                   1102:                     foreach my $item (@pairs) {
                   1103:                         my ($key,$value)=split(/=/,$item,2);
                   1104:                         $key = &unescape($key);
                   1105:                         next if ($key =~ /^error: 2 /);
                   1106:                         $returnhash{$key}=&thaw_unescape($value);
                   1107:                     }
                   1108:                 }
                   1109:             }
                   1110:         }
                   1111:     }
                   1112:     return %returnhash;
                   1113: }
                   1114: 
                   1115: sub inst_userrules {
1.923     raeburn  1116:     my ($udom,$check) = @_;
1.912     raeburn  1117:     my (%ruleshash,@ruleorder);
                   1118:     if ($udom ne '') {
                   1119:         my $homeserver=&domain($udom,'primary');
                   1120:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1121:             my $response;
                   1122:             if ($check eq 'id') {
                   1123:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1124:                                  $homeserver);
1.943     raeburn  1125:             } elsif ($check eq 'email') {
                   1126:                 $response=&reply('instemailrules:'.&escape($udom),
                   1127:                                  $homeserver);
1.923     raeburn  1128:             } else {
                   1129:                 $response=&reply('instuserrules:'.&escape($udom),
                   1130:                                  $homeserver);
                   1131:             }
1.912     raeburn  1132:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1133:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1134:                 ($response ne 'no_such_host')) {
                   1135:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1136:                 my @pairs=split(/\&/,$hashitems);
                   1137:                 foreach my $item (@pairs) {
                   1138:                     my ($key,$value)=split(/=/,$item,2);
                   1139:                     $key = &unescape($key);
                   1140:                     next if ($key =~ /^error: 2 /);
                   1141:                     $ruleshash{$key}=&thaw_unescape($value);
                   1142:                 }
                   1143:                 my @esc_order = split(/\&/,$orderitems);
                   1144:                 foreach my $item (@esc_order) {
                   1145:                     push(@ruleorder,&unescape($item));
                   1146:                 }
                   1147:             }
                   1148:         }
                   1149:     }
                   1150:     return (\%ruleshash,\@ruleorder);
                   1151: }
                   1152: 
1.943     raeburn  1153: # ------------------------- Get Authentication and Language Defaults for Domain
                   1154: 
                   1155: sub get_domain_defaults {
                   1156:     my ($domain) = @_;
                   1157:     my $cachetime = 60*60*24;
                   1158:     my ($defauthtype,$defautharg,$deflang);
                   1159:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1160:     if (defined($cached)) {
                   1161:         if (ref($result) eq 'HASH') {
                   1162:             return %{$result};
                   1163:         }
                   1164:     }
                   1165:     my %domdefaults;
                   1166:     my %domconfig =
                   1167:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1168:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1169:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1170:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1171:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1172:     } else {
                   1173:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1174:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1175:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1176:     }
                   1177:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1178:                                   $cachetime);
                   1179:     return %domdefaults;
                   1180: }
                   1181: 
1.344     www      1182: # --------------------------------------------------- Assign a key to a student
                   1183: 
                   1184: sub assign_access_key {
1.364     www      1185: #
                   1186: # a valid key looks like uname:udom#comments
                   1187: # comments are being appended
                   1188: #
1.498     www      1189:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1190:     $kdom=
1.620     albertel 1191:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1192:     $knum=
1.620     albertel 1193:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1194:     $cdom=
1.620     albertel 1195:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1196:     $cnum=
1.620     albertel 1197:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1198:     $udom=$env{'user.name'} unless (defined($udom));
                   1199:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1200:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1201:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1202:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1203:                                                   # assigned to this person
                   1204:                                                   # - this should not happen,
1.345     www      1205:                                                   # unless something went wrong
                   1206:                                                   # the first time around
                   1207: # ready to assign
1.364     www      1208:         $logentry=$1.'; '.$logentry;
1.496     www      1209:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1210:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1211: # key now belongs to user
1.346     www      1212: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1213:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1214:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1215:                 return 'ok';
                   1216:             } else {
                   1217:                 return 
                   1218:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1219: 	    }
                   1220:         } else {
                   1221:             return 'error: Could not assign key, try again later.';
                   1222:         }
1.364     www      1223:     } elsif (!$existing{$ckey}) {
1.345     www      1224: # the key does not exist
                   1225: 	return 'error: The key does not exist';
                   1226:     } else {
                   1227: # the key is somebody else's
                   1228: 	return 'error: The key is already in use';
                   1229:     }
1.344     www      1230: }
                   1231: 
1.364     www      1232: # ------------------------------------------ put an additional comment on a key
                   1233: 
                   1234: sub comment_access_key {
                   1235: #
                   1236: # a valid key looks like uname:udom#comments
                   1237: # comments are being appended
                   1238: #
                   1239:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1240:     $cdom=
1.620     albertel 1241:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1242:     $cnum=
1.620     albertel 1243:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1244:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1245:     if ($existing{$ckey}) {
                   1246:         $existing{$ckey}.='; '.$logentry;
                   1247: # ready to assign
1.367     www      1248:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1249:                                                  $cdom,$cnum) eq 'ok') {
                   1250: 	    return 'ok';
                   1251:         } else {
                   1252: 	    return 'error: Count not store comment.';
                   1253:         }
                   1254:     } else {
                   1255: # the key does not exist
                   1256: 	return 'error: The key does not exist';
                   1257:     }
                   1258: }
                   1259: 
1.344     www      1260: # ------------------------------------------------------ Generate a set of keys
                   1261: 
                   1262: sub generate_access_keys {
1.364     www      1263:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1264:     $cdom=
1.620     albertel 1265:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1266:     $cnum=
1.620     albertel 1267:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1268:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1269:     unless (($cdom) && ($cnum)) { return 0; }
                   1270:     if ($number>10000) { return 0; }
                   1271:     sleep(2); # make sure don't get same seed twice
                   1272:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1273:     my $total=0;
                   1274:     for (my $i=1;$i<=$number;$i++) {
                   1275:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1276:                   sprintf("%lx",int(100000*rand)).'-'.
                   1277:                   sprintf("%lx",int(100000*rand));
                   1278:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1279:        $newkey=~s/0/h/g; # and also 0 and O
                   1280:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1281:        if ($existing{$newkey}) {
                   1282:            $i--;
                   1283:        } else {
1.364     www      1284: 	  if (&put('accesskeys',
                   1285:               { $newkey => '# generated '.localtime().
1.620     albertel 1286:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1287:                            '; '.$logentry },
                   1288: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1289:               $total++;
                   1290: 	  }
                   1291:        }
                   1292:     }
1.620     albertel 1293:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1294:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1295:     return $total;
                   1296: }
                   1297: 
                   1298: # ------------------------------------------------------- Validate an accesskey
                   1299: 
                   1300: sub validate_access_key {
                   1301:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1302:     $cdom=
1.620     albertel 1303:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1304:     $cnum=
1.620     albertel 1305:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1306:     $udom=$env{'user.domain'} unless (defined($udom));
                   1307:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1308:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1309:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1310: }
                   1311: 
                   1312: # ------------------------------------- Find the section of student in a course
1.652     albertel 1313: sub devalidate_getsection_cache {
                   1314:     my ($udom,$unam,$courseid)=@_;
                   1315:     my $hashid="$udom:$unam:$courseid";
                   1316:     &devalidate_cache_new('getsection',$hashid);
                   1317: }
1.298     matthew  1318: 
1.815     albertel 1319: sub courseid_to_courseurl {
                   1320:     my ($courseid) = @_;
                   1321:     #already url style courseid
                   1322:     return $courseid if ($courseid =~ m{^/});
                   1323: 
                   1324:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1325: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1326: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1327: 	return "/$cdom/$cnum";
                   1328:     }
                   1329: 
                   1330:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1331:     if (exists($courseinfo{'num'})) {
                   1332: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1333:     }
                   1334: 
                   1335:     return undef;
                   1336: }
                   1337: 
1.298     matthew  1338: sub getsection {
                   1339:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1340:     my $cachetime=1800;
1.551     albertel 1341: 
                   1342:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1343:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1344:     if (defined($cached)) { return $result; }
                   1345: 
1.298     matthew  1346:     my %Pending; 
                   1347:     my %Expired;
                   1348:     #
                   1349:     # Each role can either have not started yet (pending), be active, 
                   1350:     #    or have expired.
                   1351:     #
                   1352:     # If there is an active role, we are done.
                   1353:     #
                   1354:     # If there is more than one role which has not started yet, 
                   1355:     #     choose the one which will start sooner
                   1356:     # If there is one role which has not started yet, return it.
                   1357:     #
                   1358:     # If there is more than one expired role, choose the one which ended last.
                   1359:     # If there is a role which has expired, return it.
                   1360:     #
1.815     albertel 1361:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1362:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1363:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1364:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1365:         my $section=$1;
                   1366:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1367:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1368:         my $now=time;
1.548     albertel 1369:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1370:             $Expired{$end}=$section;
                   1371:             next;
                   1372:         }
1.548     albertel 1373:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1374:             $Pending{$start}=$section;
                   1375:             next;
                   1376:         }
1.599     albertel 1377:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1378:     }
                   1379:     #
                   1380:     # Presumedly there will be few matching roles from the above
                   1381:     # loop and the sorting time will be negligible.
                   1382:     if (scalar(keys(%Pending))) {
                   1383:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1384:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1385:     } 
                   1386:     if (scalar(keys(%Expired))) {
                   1387:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1388:         my $time = pop(@sorted);
1.599     albertel 1389:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1390:     }
1.599     albertel 1391:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1392: }
1.70      www      1393: 
1.599     albertel 1394: sub save_cache {
                   1395:     &purge_remembered();
1.722     albertel 1396:     #&Apache::loncommon::validate_page();
1.620     albertel 1397:     undef(%env);
1.780     albertel 1398:     undef($env_loaded);
1.599     albertel 1399: }
1.452     albertel 1400: 
1.599     albertel 1401: my $to_remember=-1;
                   1402: my %remembered;
                   1403: my %accessed;
                   1404: my $kicks=0;
                   1405: my $hits=0;
1.849     albertel 1406: sub make_key {
                   1407:     my ($name,$id) = @_;
1.872     albertel 1408:     if (length($id) > 65 
                   1409: 	&& length(&escape($id)) > 200) {
                   1410: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1411:     }
1.849     albertel 1412:     return &escape($name.':'.$id);
                   1413: }
                   1414: 
1.599     albertel 1415: sub devalidate_cache_new {
                   1416:     my ($name,$id,$debug) = @_;
                   1417:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1418:     $id=&make_key($name,$id);
1.599     albertel 1419:     $memcache->delete($id);
                   1420:     delete($remembered{$id});
                   1421:     delete($accessed{$id});
                   1422: }
                   1423: 
                   1424: sub is_cached_new {
                   1425:     my ($name,$id,$debug) = @_;
1.849     albertel 1426:     $id=&make_key($name,$id);
1.599     albertel 1427:     if (exists($remembered{$id})) {
                   1428: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1429: 	$accessed{$id}=[&gettimeofday()];
                   1430: 	$hits++;
                   1431: 	return ($remembered{$id},1);
                   1432:     }
                   1433:     my $value = $memcache->get($id);
                   1434:     if (!(defined($value))) {
                   1435: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1436: 	return (undef,undef);
1.416     albertel 1437:     }
1.599     albertel 1438:     if ($value eq '__undef__') {
                   1439: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1440: 	$value=undef;
                   1441:     }
                   1442:     &make_room($id,$value,$debug);
                   1443:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1444:     return ($value,1);
                   1445: }
                   1446: 
                   1447: sub do_cache_new {
                   1448:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1449:     $id=&make_key($name,$id);
1.599     albertel 1450:     my $setvalue=$value;
                   1451:     if (!defined($setvalue)) {
                   1452: 	$setvalue='__undef__';
                   1453:     }
1.623     albertel 1454:     if (!defined($time) ) {
                   1455: 	$time=600;
                   1456:     }
1.599     albertel 1457:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1458:     my $result = $memcache->set($id,$setvalue,$time);
                   1459:     if (! $result) {
1.872     albertel 1460: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1461: 	$memcache->disconnect_all();
1.872     albertel 1462:     }
1.600     albertel 1463:     # need to make a copy of $value
1.919     albertel 1464:     &make_room($id,$value,$debug);
1.599     albertel 1465:     return $value;
                   1466: }
                   1467: 
                   1468: sub make_room {
                   1469:     my ($id,$value,$debug)=@_;
1.919     albertel 1470: 
                   1471:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1472:                                     : $value;
1.599     albertel 1473:     if ($to_remember<0) { return; }
                   1474:     $accessed{$id}=[&gettimeofday()];
                   1475:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1476:     my $to_kick;
                   1477:     my $max_time=0;
                   1478:     foreach my $other (keys(%accessed)) {
                   1479: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1480: 	    $to_kick=$other;
                   1481: 	    $max_time=&tv_interval($accessed{$other});
                   1482: 	}
                   1483:     }
                   1484:     delete($remembered{$to_kick});
                   1485:     delete($accessed{$to_kick});
                   1486:     $kicks++;
                   1487:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1488:     return;
                   1489: }
                   1490: 
1.599     albertel 1491: sub purge_remembered {
1.604     albertel 1492:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1493:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1494:     undef(%remembered);
                   1495:     undef(%accessed);
1.428     albertel 1496: }
1.70      www      1497: # ------------------------------------- Read an entry from a user's environment
                   1498: 
                   1499: sub userenvironment {
                   1500:     my ($udom,$unam,@what)=@_;
                   1501:     my %returnhash=();
                   1502:     my @answer=split(/\&/,
                   1503:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1504:                       &homeserver($unam,$udom)));
                   1505:     my $i;
                   1506:     for ($i=0;$i<=$#what;$i++) {
                   1507: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1508:     }
                   1509:     return %returnhash;
1.1       albertel 1510: }
                   1511: 
1.617     albertel 1512: # ---------------------------------------------------------- Get a studentphoto
                   1513: sub studentphoto {
                   1514:     my ($udom,$unam,$ext) = @_;
                   1515:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1516:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1517:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1518:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1519:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1520:             } else {
                   1521:                 my ($result,$perm_reqd)=
1.707     albertel 1522: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1523:                 if ($result eq 'ok') {
                   1524:                     if (!($perm_reqd eq 'yes')) {
                   1525:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1526:                     }
                   1527:                 }
                   1528:             }
                   1529:         }
                   1530:     } else {
                   1531:         my ($result,$perm_reqd) = 
1.707     albertel 1532: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1533:         if ($result eq 'ok') {
                   1534:             if (!($perm_reqd eq 'yes')) {
                   1535:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1536:             }
                   1537:         }
                   1538:     }
                   1539:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1540: }
                   1541: 
                   1542: sub retrievestudentphoto {
                   1543:     my ($udom,$unam,$ext,$type) = @_;
                   1544:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1545:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1546:     if ($ret eq 'ok') {
                   1547:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1548:         if ($type eq 'thumbnail') {
                   1549:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1550:         }
                   1551:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1552:         return $tokenurl;
                   1553:     } else {
                   1554:         if ($type eq 'thumbnail') {
                   1555:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1556:         } else { 
                   1557:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1558:         }
1.617     albertel 1559:     }
                   1560: }
                   1561: 
1.263     www      1562: # -------------------------------------------------------------------- New chat
                   1563: 
                   1564: sub chatsend {
1.724     raeburn  1565:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1566:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1567:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1568:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1569:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1570: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1571: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1572: }
                   1573: 
                   1574: # ------------------------------------------ Find current version of a resource
                   1575: 
                   1576: sub getversion {
                   1577:     my $fname=&clutter(shift);
                   1578:     unless ($fname=~/^\/res\//) { return -1; }
                   1579:     return &currentversion(&filelocation('',$fname));
                   1580: }
                   1581: 
                   1582: sub currentversion {
                   1583:     my $fname=shift;
1.599     albertel 1584:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1585:     if (defined($cached)) { return $result; }
1.292     www      1586:     my $author=$fname;
                   1587:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1588:     my ($udom,$uname)=split(/\//,$author);
                   1589:     my $home=homeserver($uname,$udom);
                   1590:     if ($home eq 'no_host') { 
                   1591:         return -1; 
                   1592:     }
                   1593:     my $answer=reply("currentversion:$fname",$home);
                   1594:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1595: 	return -1;
                   1596:     }
1.599     albertel 1597:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1598: }
                   1599: 
1.1       albertel 1600: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1601: 
1.1       albertel 1602: sub subscribe {
                   1603:     my $fname=shift;
1.761     raeburn  1604:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1605:     $fname=~s/[\n\r]//g;
1.1       albertel 1606:     my $author=$fname;
                   1607:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1608:     my ($udom,$uname)=split(/\//,$author);
                   1609:     my $home=homeserver($uname,$udom);
1.335     albertel 1610:     if ($home eq 'no_host') {
                   1611:         return 'not_found';
1.1       albertel 1612:     }
                   1613:     my $answer=reply("sub:$fname",$home);
1.64      www      1614:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1615: 	$answer.=' by '.$home;
                   1616:     }
1.1       albertel 1617:     return $answer;
                   1618: }
                   1619:     
1.8       www      1620: # -------------------------------------------------------------- Replicate file
                   1621: 
                   1622: sub repcopy {
                   1623:     my $filename=shift;
1.23      www      1624:     $filename=~s/\/+/\//g;
1.607     raeburn  1625:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1626:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1627:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1628: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1629: 	return &repcopy_userfile($filename);
                   1630:     }
1.532     albertel 1631:     $filename=~s/[\n\r]//g;
1.8       www      1632:     my $transname="$filename.in.transfer";
1.828     www      1633: # FIXME: this should flock
1.607     raeburn  1634:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1635:     my $remoteurl=subscribe($filename);
1.64      www      1636:     if ($remoteurl =~ /^con_lost by/) {
                   1637: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1638:            return 'unavailable';
1.8       www      1639:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1640: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1641: 	   return 'not_found';
1.64      www      1642:     } elsif ($remoteurl =~ /^rejected by/) {
                   1643: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1644:            return 'forbidden';
1.20      www      1645:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1646:            return 'ok';
1.8       www      1647:     } else {
1.290     www      1648:         my $author=$filename;
                   1649:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1650:         my ($udom,$uname)=split(/\//,$author);
                   1651:         my $home=homeserver($uname,$udom);
                   1652:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1653:            my @parts=split(/\//,$filename);
                   1654:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1655:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1656:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1657: 	       return 'bad_request';
1.8       www      1658:            }
                   1659:            my $count;
                   1660:            for ($count=5;$count<$#parts;$count++) {
                   1661:                $path.="/$parts[$count]";
                   1662:                if ((-e $path)!=1) {
                   1663: 		   mkdir($path,0777);
                   1664:                }
                   1665:            }
                   1666:            my $ua=new LWP::UserAgent;
                   1667:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1668:            my $response=$ua->request($request,$transname);
                   1669:            if ($response->is_error()) {
                   1670: 	       unlink($transname);
                   1671:                my $message=$response->status_line;
1.672     albertel 1672:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1673:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1674:                return 'unavailable';
1.8       www      1675:            } else {
1.16      www      1676: 	       if ($remoteurl!~/\.meta$/) {
                   1677:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1678:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1679:                   if ($mresponse->is_error()) {
                   1680: 		      unlink($filename.'.meta');
                   1681:                       &logthis(
1.672     albertel 1682:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1683:                   }
                   1684: 	       }
1.8       www      1685:                rename($transname,$filename);
1.607     raeburn  1686:                return 'ok';
1.8       www      1687:            }
1.290     www      1688:        }
1.8       www      1689:     }
1.330     www      1690: }
                   1691: 
                   1692: # ------------------------------------------------ Get server side include body
                   1693: sub ssi_body {
1.381     albertel 1694:     my ($filelink,%form)=@_;
1.606     matthew  1695:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1696:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1697:     }
1.953     www      1698:     my $output='';
                   1699:     my $response;
                   1700:     if ($filelink=~/^http\:/) {
1.954     raeburn  1701:        ($output,$response)=&externalssi($filelink);
1.953     www      1702:     } else {
                   1703:        ($output,$response)=&ssi($filelink,%form);
                   1704:     }
1.778     albertel 1705:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1706:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1707:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1708:     if (wantarray) {
                   1709:         return ($output, $response);
                   1710:     } else {
                   1711:         return $output;
                   1712:     }
1.8       www      1713: }
                   1714: 
1.15      www      1715: # --------------------------------------------------------- Server Side Include
                   1716: 
1.782     albertel 1717: sub absolute_url {
                   1718:     my ($host_name) = @_;
                   1719:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1720:     if ($host_name eq '') {
                   1721: 	$host_name = $ENV{'SERVER_NAME'};
                   1722:     }
                   1723:     return $protocol.$host_name;
                   1724: }
                   1725: 
1.942     foxr     1726: #
                   1727: #   Server side include.
                   1728: # Parameters:
                   1729: #  fn     Possibly encrypted resource name/id.
                   1730: #  form   Hash that describes how the rendering should be done
                   1731: #         and other things.
1.944     foxr     1732: # Returns:
1.950     raeburn  1733: #   Scalar context: The content of the response.
                   1734: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1735: #     
1.15      www      1736: sub ssi {
                   1737: 
1.944     foxr     1738:     my ($fn,%form)=@_;
1.15      www      1739:     my $ua=new LWP::UserAgent;
1.23      www      1740:     my $request;
1.711     albertel 1741: 
                   1742:     $form{'no_update_last_known'}=1;
1.895     albertel 1743:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1744:     if (%form) {
1.782     albertel 1745:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1746:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1747:     } else {
1.782     albertel 1748:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1749:     }
                   1750: 
1.15      www      1751:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1752:     my $response=$ua->request($request);
                   1753: 
1.944     foxr     1754:     if (wantarray) {
                   1755: 	return ($response->content, $response);
                   1756:     } else {
                   1757: 	return $response->content;
1.942     foxr     1758:     }
1.324     www      1759: }
                   1760: 
                   1761: sub externalssi {
                   1762:     my ($url)=@_;
                   1763:     my $ua=new LWP::UserAgent;
                   1764:     my $request=new HTTP::Request('GET',$url);
                   1765:     my $response=$ua->request($request);
1.954     raeburn  1766:     if (wantarray) {
                   1767:         return ($response->content, $response);
                   1768:     } else {
                   1769:         return $response->content;
                   1770:     }
1.15      www      1771: }
1.254     www      1772: 
1.492     albertel 1773: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1774: 
                   1775: sub allowuploaded {
                   1776:     my ($srcurl,$url)=@_;
                   1777:     $url=&clutter(&declutter($url));
                   1778:     my $dir=$url;
                   1779:     $dir=~s/\/[^\/]+$//;
                   1780:     my %httpref=();
                   1781:     my $httpurl=&hreflocation('',$url);
                   1782:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1783:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1784: }
1.477     raeburn  1785: 
1.478     albertel 1786: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1787: # input: action, courseID, current domain, intended
1.637     raeburn  1788: #        path to file, source of file, instruction to parse file for objects,
                   1789: #        ref to hash for embedded objects,
                   1790: #        ref to hash for codebase of java objects.
                   1791: #
1.485     raeburn  1792: # output: url to file (if action was uploaddoc), 
                   1793: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1794: #
1.478     albertel 1795: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1796: # course.
1.477     raeburn  1797: #
1.478     albertel 1798: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1799: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1800: #          course's home server.
1.477     raeburn  1801: #
1.478     albertel 1802: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1803: #          be copied from $source (current location) to 
                   1804: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1805: #         and will then be copied to
                   1806: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1807: #         course's home server.
1.485     raeburn  1808: #
1.481     raeburn  1809: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1810: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1811: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1812: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1813: #         in course's home server.
1.637     raeburn  1814: #
1.477     raeburn  1815: 
                   1816: sub process_coursefile {
1.638     albertel 1817:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1818:     my $fetchresult;
1.638     albertel 1819:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1820:     if ($action eq 'propagate') {
1.638     albertel 1821:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1822: 			     $home);
1.481     raeburn  1823:     } else {
1.477     raeburn  1824:         my $fpath = '';
                   1825:         my $fname = $file;
1.478     albertel 1826:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1827:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1828:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1829:         if ($action eq 'copy') {
                   1830:             if ($source eq '') {
                   1831:                 $fetchresult = 'no source file';
                   1832:                 return $fetchresult;
                   1833:             } else {
                   1834:                 my $destination = $filepath.'/'.$fname;
                   1835:                 rename($source,$destination);
                   1836:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1837:                                  $home);
1.481     raeburn  1838:             }
                   1839:         } elsif ($action eq 'uploaddoc') {
                   1840:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1841:             print $fh $env{'form.'.$source};
1.481     raeburn  1842:             close($fh);
1.637     raeburn  1843:             if ($parser eq 'parse') {
                   1844:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1845:                 unless ($parse_result eq 'ok') {
                   1846:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1847:                 }
                   1848:             }
1.477     raeburn  1849:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1850:                                  $home);
1.481     raeburn  1851:             if ($fetchresult eq 'ok') {
                   1852:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1853:             } else {
                   1854:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1855:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1856:                 return '/adm/notfound.html';
                   1857:             }
1.477     raeburn  1858:         }
                   1859:     }
1.485     raeburn  1860:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1861:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1862:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1863:     }
                   1864:     return $fetchresult;
                   1865: }
                   1866: 
1.637     raeburn  1867: sub build_filepath {
                   1868:     my ($fpath) = @_;
                   1869:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1870:     unless ($fpath eq '') {
                   1871:         my @parts=split('/',$fpath);
                   1872:         foreach my $part (@parts) {
                   1873:             $filepath.= '/'.$part;
                   1874:             if ((-e $filepath)!=1) {
                   1875:                 mkdir($filepath,0777);
                   1876:             }
                   1877:         }
                   1878:     }
                   1879:     return $filepath;
                   1880: }
                   1881: 
                   1882: sub store_edited_file {
1.638     albertel 1883:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1884:     my $file = $primary_url;
                   1885:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1886:     my $fpath = '';
                   1887:     my $fname = $file;
                   1888:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1889:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1890:     my $filepath = &build_filepath($fpath);
                   1891:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1892:     print $fh $content;
                   1893:     close($fh);
1.638     albertel 1894:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1895:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1896: 			  $home);
1.637     raeburn  1897:     if ($$fetchresult eq 'ok') {
                   1898:         return '/uploaded/'.$fpath.'/'.$fname;
                   1899:     } else {
1.638     albertel 1900:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1901: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1902:         return '/adm/notfound.html';
                   1903:     }
                   1904: }
                   1905: 
1.531     albertel 1906: sub clean_filename {
1.831     albertel 1907:     my ($fname,$args)=@_;
1.315     www      1908: # Replace Windows backslashes by forward slashes
1.257     www      1909:     $fname=~s/\\/\//g;
1.831     albertel 1910:     if (!$args->{'keep_path'}) {
                   1911:         # Get rid of everything but the actual filename
                   1912: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1913:     }
1.315     www      1914: # Replace spaces by underscores
                   1915:     $fname=~s/\s+/\_/g;
                   1916: # Replace all other weird characters by nothing
1.831     albertel 1917:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1918: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1919: # numbers
                   1920:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1921:     return $fname;
                   1922: }
                   1923: 
1.608     albertel 1924: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1925: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1926: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1927: #        $coursedoc - if true up to the current course
                   1928: #                     if false
                   1929: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1930: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1931: #        $allfiles - reference to hash for embedded objects
                   1932: #        $codebase - reference to hash for codebase of java objects
                   1933: #        $desuname - username for permanent storage of uploaded file
                   1934: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1935: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1936: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1937: # 
1.686     albertel 1938: # output: url of file in userspace, or error: <message> 
                   1939: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1940: 
                   1941: 
1.531     albertel 1942: sub userfileupload {
1.860     raeburn  1943:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1944:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1945:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1946:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1947:     $fname=&clean_filename($fname);
1.315     www      1948: # See if there is anything left
1.257     www      1949:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1950:     chop($env{'form.'.$formname});
1.523     raeburn  1951:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1952:         my $now = time;
                   1953:         my $filepath = 'tmp/helprequests/'.$now;
                   1954:         my @parts=split(/\//,$filepath);
                   1955:         my $fullpath = $perlvar{'lonDaemons'};
                   1956:         for (my $i=0;$i<@parts;$i++) {
                   1957:             $fullpath .= '/'.$parts[$i];
                   1958:             if ((-e $fullpath)!=1) {
                   1959:                 mkdir($fullpath,0777);
                   1960:             }
                   1961:         }
                   1962:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1963:         print $fh $env{'form.'.$formname};
1.523     raeburn  1964:         close($fh);
1.741     raeburn  1965:         return $fullpath.'/'.$fname;
                   1966:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1967:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1968:                        '_'.$env{'user.domain'}.'/pending';
                   1969:         my @parts=split(/\//,$filepath);
                   1970:         my $fullpath = $perlvar{'lonDaemons'};
                   1971:         for (my $i=0;$i<@parts;$i++) {
                   1972:             $fullpath .= '/'.$parts[$i];
                   1973:             if ((-e $fullpath)!=1) {
                   1974:                 mkdir($fullpath,0777);
                   1975:             }
                   1976:         }
                   1977:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1978:         print $fh $env{'form.'.$formname};
                   1979:         close($fh);
                   1980:         return $fullpath.'/'.$fname;
1.523     raeburn  1981:     }
1.719     banghart 1982:     
1.258     www      1983: # Create the directory if not present
1.493     albertel 1984:     $fname="$subdir/$fname";
1.259     www      1985:     if ($coursedoc) {
1.638     albertel 1986: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1987: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1988:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1989:             return &finishuserfileupload($docuname,$docudom,
                   1990: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1991: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1992:         } else {
1.620     albertel 1993:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1994:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1995: 				       $fname,$formname,$parser,
                   1996: 				       $allfiles,$codebase);
1.481     raeburn  1997:         }
1.719     banghart 1998:     } elsif (defined($destuname)) {
                   1999:         my $docuname=$destuname;
                   2000:         my $docudom=$destudom;
1.860     raeburn  2001: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2002: 				     $parser,$allfiles,$codebase,
                   2003:                                      $thumbwidth,$thumbheight);
1.719     banghart 2004:         
1.259     www      2005:     } else {
1.638     albertel 2006:         my $docuname=$env{'user.name'};
                   2007:         my $docudom=$env{'user.domain'};
1.714     raeburn  2008:         if (exists($env{'form.group'})) {
                   2009:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2010:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2011:         }
1.860     raeburn  2012: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2013: 				     $parser,$allfiles,$codebase,
                   2014:                                      $thumbwidth,$thumbheight);
1.259     www      2015:     }
1.271     www      2016: }
                   2017: 
                   2018: sub finishuserfileupload {
1.860     raeburn  2019:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2020:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2021:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2022:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2023:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2024:     $file=$fname;
                   2025:     if ($fname=~m|/|) {
                   2026:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2027: 	$path.=$fnamepath.'/';
                   2028:     }
1.259     www      2029:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2030:     my $count;
                   2031:     for ($count=4;$count<=$#parts;$count++) {
                   2032:         $filepath.="/$parts[$count]";
                   2033:         if ((-e $filepath)!=1) {
                   2034: 	    mkdir($filepath,0777);
                   2035:         }
                   2036:     }
                   2037: # Save the file
                   2038:     {
1.701     albertel 2039: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2040: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2041: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2042: 	    return '/adm/notfound.html';
                   2043: 	}
                   2044: 	if (!print FH ($env{'form.'.$formname})) {
                   2045: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2046: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2047: 	    return '/adm/notfound.html';
                   2048: 	}
1.570     albertel 2049: 	close(FH);
1.258     www      2050:     }
1.637     raeburn  2051:     if ($parser eq 'parse') {
1.638     albertel 2052:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2053: 						   $codebase);
1.637     raeburn  2054:         unless ($parse_result eq 'ok') {
1.638     albertel 2055:             &logthis('Failed to parse '.$filepath.$file.
                   2056: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2057:         }
                   2058:     }
1.860     raeburn  2059:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2060:         my $input = $filepath.'/'.$file;
                   2061:         my $output = $filepath.'/'.'tn-'.$file;
                   2062:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2063:         system("convert -sample $thumbsize $input $output");
                   2064:         if (-e $filepath.'/'.'tn-'.$file) {
                   2065:             $fetchthumb  = 1; 
                   2066:         }
                   2067:     }
1.858     raeburn  2068:  
1.259     www      2069: # Notify homeserver to grep it
                   2070: #
1.638     albertel 2071:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2072:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2073:     if ($fetchresult eq 'ok') {
1.860     raeburn  2074:         if ($fetchthumb) {
                   2075:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2076:             if ($thumbresult ne 'ok') {
                   2077:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2078:                          $docuhome.': '.$thumbresult);
                   2079:             }
                   2080:         }
1.259     www      2081: #
1.258     www      2082: # Return the URL to it
1.494     albertel 2083:         return '/uploaded/'.$path.$file;
1.263     www      2084:     } else {
1.494     albertel 2085:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2086: 		 ': '.$fetchresult);
1.263     www      2087:         return '/adm/notfound.html';
1.858     raeburn  2088:     }
1.493     albertel 2089: }
                   2090: 
1.637     raeburn  2091: sub extract_embedded_items {
1.648     raeburn  2092:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2093:     my @state = ();
                   2094:     my %javafiles = (
                   2095:                       codebase => '',
                   2096:                       code => '',
                   2097:                       archive => ''
                   2098:                     );
                   2099:     my %mediafiles = (
                   2100:                       src => '',
                   2101:                       movie => '',
                   2102:                      );
1.648     raeburn  2103:     my $p;
                   2104:     if ($content) {
                   2105:         $p = HTML::LCParser->new($content);
                   2106:     } else {
                   2107:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2108:     }
1.641     albertel 2109:     while (my $t=$p->get_token()) {
1.640     albertel 2110: 	if ($t->[0] eq 'S') {
                   2111: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2112: 	    push(@state, $tagname);
1.648     raeburn  2113:             if (lc($tagname) eq 'allow') {
                   2114:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2115:             }
1.640     albertel 2116: 	    if (lc($tagname) eq 'img') {
                   2117: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2118: 	    }
1.886     albertel 2119: 	    if (lc($tagname) eq 'a') {
                   2120: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2121: 	    }
1.645     raeburn  2122:             if (lc($tagname) eq 'script') {
                   2123:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2124:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2125:                 } else {
                   2126:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2127:                 }
                   2128:             }
                   2129:             if (lc($tagname) eq 'link') {
                   2130:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2131:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2132:                 }
                   2133:             }
1.640     albertel 2134: 	    if (lc($tagname) eq 'object' ||
                   2135: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2136: 		foreach my $item (keys(%javafiles)) {
                   2137: 		    $javafiles{$item} = '';
                   2138: 		}
                   2139: 	    }
                   2140: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2141: 		my $name = lc($attr->{'name'});
                   2142: 		foreach my $item (keys(%javafiles)) {
                   2143: 		    if ($name eq $item) {
                   2144: 			$javafiles{$item} = $attr->{'value'};
                   2145: 			last;
                   2146: 		    }
                   2147: 		}
                   2148: 		foreach my $item (keys(%mediafiles)) {
                   2149: 		    if ($name eq $item) {
                   2150: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2151: 			last;
                   2152: 		    }
                   2153: 		}
                   2154: 	    }
                   2155: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2156: 		foreach my $item (keys(%javafiles)) {
                   2157: 		    if ($attr->{$item}) {
                   2158: 			$javafiles{$item} = $attr->{$item};
                   2159: 			last;
                   2160: 		    }
                   2161: 		}
                   2162: 		foreach my $item (keys(%mediafiles)) {
                   2163: 		    if ($attr->{$item}) {
                   2164: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2165: 			last;
                   2166: 		    }
                   2167: 		}
                   2168: 	    }
                   2169: 	} elsif ($t->[0] eq 'E') {
                   2170: 	    my ($tagname) = ($t->[1]);
                   2171: 	    if ($javafiles{'codebase'} ne '') {
                   2172: 		$javafiles{'codebase'} .= '/';
                   2173: 	    }  
                   2174: 	    if (lc($tagname) eq 'applet' ||
                   2175: 		lc($tagname) eq 'object' ||
                   2176: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2177: 		) {
                   2178: 		foreach my $item (keys(%javafiles)) {
                   2179: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2180: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2181: 			&add_filetype($allfiles,$file,$item);
                   2182: 		    }
                   2183: 		}
                   2184: 	    } 
                   2185: 	    pop @state;
                   2186: 	}
                   2187:     }
1.637     raeburn  2188:     return 'ok';
                   2189: }
                   2190: 
1.639     albertel 2191: sub add_filetype {
                   2192:     my ($allfiles,$file,$type)=@_;
                   2193:     if (exists($allfiles->{$file})) {
                   2194: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2195: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2196: 	}
                   2197:     } else {
                   2198: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2199:     }
                   2200: }
                   2201: 
1.493     albertel 2202: sub removeuploadedurl {
                   2203:     my ($url)=@_;
                   2204:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2205:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2206: }
                   2207: 
                   2208: sub removeuserfile {
                   2209:     my ($docuname,$docudom,$fname)=@_;
                   2210:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2211:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2212:     if ($result eq 'ok') {
                   2213:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2214:             my $metafile = $fname.'.meta';
                   2215:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2216: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2217:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2218:             my $sqlresult = 
1.823     albertel 2219:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2220:                                         'portfolio_metadata',$group,
                   2221:                                         'delete');
1.798     raeburn  2222:         }
                   2223:     }
                   2224:     return $result;
1.257     www      2225: }
1.15      www      2226: 
1.530     albertel 2227: sub mkdiruserfile {
                   2228:     my ($docuname,$docudom,$dir)=@_;
                   2229:     my $home=&homeserver($docuname,$docudom);
                   2230:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2231: }
                   2232: 
1.531     albertel 2233: sub renameuserfile {
                   2234:     my ($docuname,$docudom,$old,$new)=@_;
                   2235:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2236:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2237:                         &escape("$old").':'.&escape("$new"),$home);
                   2238:     if ($result eq 'ok') {
                   2239:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2240:             my $oldmeta = $old.'.meta';
                   2241:             my $newmeta = $new.'.meta';
                   2242:             my $metaresult = 
                   2243:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2244: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2245:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2246:             my $sqlresult = 
1.823     albertel 2247:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2248:                                         'portfolio_metadata',$group,
                   2249:                                         'delete');
1.798     raeburn  2250:         }
                   2251:     }
                   2252:     return $result;
1.531     albertel 2253: }
                   2254: 
1.14      www      2255: # ------------------------------------------------------------------------- Log
                   2256: 
                   2257: sub log {
                   2258:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2259:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2260: }
                   2261: 
                   2262: # ------------------------------------------------------------------ Course Log
1.352     www      2263: #
                   2264: # This routine flushes several buffers of non-mission-critical nature
                   2265: #
1.157     www      2266: 
                   2267: sub flushcourselogs {
1.352     www      2268:     &logthis('Flushing log buffers');
                   2269: #
                   2270: # course logs
                   2271: # This is a log of all transactions in a course, which can be used
                   2272: # for data mining purposes
                   2273: #
                   2274: # It also collects the courseid database, which lists last transaction
                   2275: # times and course titles for all courseids
                   2276: #
                   2277:     my %courseidbuffer=();
1.921     raeburn  2278:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2279:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2280: 		          &escape($courselogs{$crsid}),
                   2281: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2282: 	    delete $courselogs{$crsid};
                   2283:         } else {
                   2284:             &logthis('Failed to flush log buffer for '.$crsid);
                   2285:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2286:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2287:                         " exceeded maximum size, deleting.</font>");
                   2288:                delete $courselogs{$crsid};
                   2289:             }
1.352     www      2290:         }
1.920     raeburn  2291:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2292:             'description' => $coursedescrbuf{$crsid},
                   2293:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2294:             'type'        => $coursetypebuf{$crsid},
                   2295:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2296:         };
1.191     harris41 2297:     }
1.352     www      2298: #
                   2299: # Write course id database (reverse lookup) to homeserver of courses 
                   2300: # Is used in pickcourse
                   2301: #
1.840     albertel 2302:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2303:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2304:                                     $courseidbuffer{$crs_home},
                   2305:                                     $crs_home,'timeonly');
1.352     www      2306:     }
                   2307: #
                   2308: # File accesses
                   2309: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2310: #
1.449     matthew  2311:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2312:         if ($entry =~ /___count$/) {
                   2313:             my ($dom,$name);
1.807     albertel 2314:             ($dom,$name,undef)=
1.811     albertel 2315: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2316:             if (! defined($dom) || $dom eq '' || 
                   2317:                 ! defined($name) || $name eq '') {
1.620     albertel 2318:                 my $cid = $env{'request.course.id'};
                   2319:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2320:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2321:             }
1.450     matthew  2322:             my $value = $accesshash{$entry};
                   2323:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2324:             my %temphash=($url => $value);
1.449     matthew  2325:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2326:             if ($result eq 'ok') {
                   2327:                 delete $accesshash{$entry};
                   2328:             } elsif ($result eq 'unknown_cmd') {
                   2329:                 # Target server has old code running on it.
1.450     matthew  2330:                 my %temphash=($entry => $value);
1.449     matthew  2331:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2332:                     delete $accesshash{$entry};
                   2333:                 }
                   2334:             }
                   2335:         } else {
1.811     albertel 2336:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2337:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2338:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2339:                 delete $accesshash{$entry};
                   2340:             }
1.185     www      2341:         }
1.191     harris41 2342:     }
1.352     www      2343: #
                   2344: # Roles
                   2345: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2346: #
1.800     albertel 2347:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2348:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2349: 	    split(/\:/,$entry);
                   2350:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2351:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2352:                 $rudom,$runame) eq 'ok') {
                   2353: 	    delete $userrolehash{$entry};
                   2354:         }
                   2355:     }
1.662     raeburn  2356: #
                   2357: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2358: #
                   2359:     my %domrolebuffer = ();
                   2360:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2361:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2362:         if ($domrolebuffer{$rudom}) {
                   2363:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2364:                       '='.&escape($domainrolehash{$entry});
                   2365:         } else {
                   2366:             $domrolebuffer{$rudom}.=&escape($entry).
                   2367:                       '='.&escape($domainrolehash{$entry});
                   2368:         }
                   2369:         delete $domainrolehash{$entry};
                   2370:     }
                   2371:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2372: 	my %servers = &get_servers($dom,'library');
                   2373: 	foreach my $tryserver (keys(%servers)) {
                   2374: 	    unless (&reply('domroleput:'.$dom.':'.
                   2375: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2376: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2377: 	    }
1.662     raeburn  2378:         }
                   2379:     }
1.186     www      2380:     $dumpcount++;
1.157     www      2381: }
                   2382: 
                   2383: sub courselog {
                   2384:     my $what=shift;
1.158     www      2385:     $what=time.':'.$what;
1.620     albertel 2386:     unless ($env{'request.course.id'}) { return ''; }
                   2387:     $coursedombuf{$env{'request.course.id'}}=
                   2388:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2389:     $coursenumbuf{$env{'request.course.id'}}=
                   2390:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2391:     $coursehombuf{$env{'request.course.id'}}=
                   2392:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2393:     $coursedescrbuf{$env{'request.course.id'}}=
                   2394:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2395:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2396:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2397:     $courseownerbuf{$env{'request.course.id'}}=
                   2398:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2399:     $coursetypebuf{$env{'request.course.id'}}=
                   2400:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2401:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2402: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2403:     } else {
1.620     albertel 2404: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2405:     }
1.620     albertel 2406:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2407: 	&flushcourselogs();
                   2408:     }
1.158     www      2409: }
                   2410: 
                   2411: sub courseacclog {
                   2412:     my $fnsymb=shift;
1.620     albertel 2413:     unless ($env{'request.course.id'}) { return ''; }
                   2414:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2415:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2416:         $what.=':POST';
1.583     matthew  2417:         # FIXME: Probably ought to escape things....
1.800     albertel 2418: 	foreach my $key (keys(%env)) {
                   2419:             if ($key=~/^form\.(.*)/) {
                   2420: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2421:             }
1.191     harris41 2422:         }
1.583     matthew  2423:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2424:         # FIXME: We should not be depending on a form parameter that someone
                   2425:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2426:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2427:             $what.= ':POST';
                   2428:             # FIXME: Probably ought to escape things....
                   2429:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2430:                                  'crsdiscuss') {
1.620     albertel 2431:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2432:             }
                   2433:         }
1.158     www      2434:     }
                   2435:     &courselog($what);
1.149     www      2436: }
                   2437: 
1.185     www      2438: sub countacc {
                   2439:     my $url=&declutter(shift);
1.458     matthew  2440:     return if (! defined($url) || $url eq '');
1.620     albertel 2441:     unless ($env{'request.course.id'}) { return ''; }
                   2442:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2443:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2444:     $accesshash{$key}++;
1.185     www      2445: }
1.349     www      2446: 
1.361     www      2447: sub linklog {
                   2448:     my ($from,$to)=@_;
                   2449:     $from=&declutter($from);
                   2450:     $to=&declutter($to);
                   2451:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2452:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2453: }
                   2454:   
1.349     www      2455: sub userrolelog {
                   2456:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2457:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2458:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2459:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2460:         ($trole=~/^ta/)) {
1.350     www      2461:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2462:        $userrolehash
                   2463:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2464:                     =$tend.':'.$tstart;
1.662     raeburn  2465:     }
1.898     albertel 2466:     if (($env{'request.role'} =~ /dc\./) &&
                   2467: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2468: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2469: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2470:        $userrolehash
                   2471:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2472:                     =$tend.':'.$tstart;
                   2473:     }
1.662     raeburn  2474:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2475:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2476:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2477:         ($trole=~/^sc/)) {
                   2478:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2479:        $domainrolehash
                   2480:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2481:                     = $tend.':'.$tstart;
                   2482:     }
1.351     www      2483: }
                   2484: 
1.957   ! raeburn  2485: sub courserolelog {
        !          2486:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
        !          2487:     if (($trole eq 'cc') || ($trole eq 'in') ||
        !          2488:         ($trole eq 'ep') || ($trole eq 'ad') ||
        !          2489:         ($trole eq 'ta') || ($trole eq 'st') ||
        !          2490:         ($trole=~/^cr/) || ($trole eq 'gr')) {
        !          2491:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
        !          2492:             my $cdom = $1;
        !          2493:             my $cnum = $2;
        !          2494:             my $sec = $3;
        !          2495:             my $namespace = 'rolelog';
        !          2496:             my %storehash = (
        !          2497:                                role    => $trole,
        !          2498:                                start   => $tstart,
        !          2499:                                end     => $tend,
        !          2500:                                selfenroll => $selfenroll,
        !          2501:                                context    => $context,
        !          2502:                             );
        !          2503:             if ($trole eq 'gr') {
        !          2504:                 $namespace = 'groupslog';
        !          2505:                 $storehash{'group'} = $sec;
        !          2506:             } else {
        !          2507:                 $storehash{'section'} = $sec;
        !          2508:             }
        !          2509:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
        !          2510:         }
        !          2511:     }
        !          2512:     return;
        !          2513: }
        !          2514: 
1.351     www      2515: sub get_course_adv_roles {
1.948     raeburn  2516:     my ($cid,$codes) = @_;
1.620     albertel 2517:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2518:     my %coursehash=&coursedescription($cid);
1.470     www      2519:     my %nothide=();
1.800     albertel 2520:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2521:         if ($user !~ /:/) {
                   2522: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2523:         } else {
                   2524:             $nothide{$user}=1;
                   2525:         }
1.470     www      2526:     }
1.351     www      2527:     my %returnhash=();
                   2528:     my %dumphash=
                   2529:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2530:     my $now=time;
1.800     albertel 2531:     foreach my $entry (keys %dumphash) {
                   2532: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2533:         if (($tstart) && ($tstart<0)) { next; }
                   2534:         if (($tend) && ($tend<$now)) { next; }
                   2535:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2536:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2537: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2538: 	if ((&privileged($username,$domain)) && 
                   2539: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2540: 	if ($role eq 'cr') { next; }
1.948     raeburn  2541:         if ($codes) {
                   2542:             if ($section) { $role .= ':'.$section; }
                   2543:             if ($returnhash{$role}) {
                   2544:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2545:             } else {
                   2546:                 $returnhash{$role}=$username.':'.$domain;
                   2547:             }
1.351     www      2548:         } else {
1.948     raeburn  2549:             my $key=&plaintext($role);
                   2550:             if ($section) { $key.=' (Section '.$section.')'; }
                   2551:             if ($returnhash{$key}) {
                   2552: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2553:             } else {
                   2554:                 $returnhash{$key}=$username.':'.$domain;
                   2555:             }
1.351     www      2556:         }
1.948     raeburn  2557:     }
1.400     www      2558:     return %returnhash;
                   2559: }
                   2560: 
                   2561: sub get_my_roles {
1.937     raeburn  2562:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2563:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2564:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2565:     my (%dumphash,%nothide);
1.858     raeburn  2566:     if ($context eq 'userroles') { 
                   2567:         %dumphash = &dump('roles',$udom,$uname);
                   2568:     } else {
                   2569:         %dumphash=
1.400     www      2570:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2571:         if ($hidepriv) {
                   2572:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2573:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2574:                 if ($user !~ /:/) {
                   2575:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2576:                 } else {
                   2577:                     $nothide{$user} = 1;
                   2578:                 }
                   2579:             }
                   2580:         }
1.858     raeburn  2581:     }
1.400     www      2582:     my %returnhash=();
                   2583:     my $now=time;
1.800     albertel 2584:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2585:         my ($role,$tend,$tstart);
                   2586:         if ($context eq 'userroles') {
                   2587: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2588:         } else {
                   2589:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2590:         }
1.400     www      2591:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2592:         my $status = 'active';
1.939     raeburn  2593:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2594:             $status = 'previous';
                   2595:         } 
                   2596:         if (($tstart) && ($now<$tstart)) {
                   2597:             $status = 'future';
                   2598:         }
                   2599:         if (ref($types) eq 'ARRAY') {
                   2600:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2601:                 next;
                   2602:             } 
                   2603:         } else {
                   2604:             if ($status ne 'active') {
                   2605:                 next;
                   2606:             }
                   2607:         }
1.867     raeburn  2608:         my ($rolecode,$username,$domain,$section,$area);
                   2609:         if ($context eq 'userroles') {
                   2610:             ($area,$rolecode) = split(/_/,$entry);
                   2611:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2612:         } else {
                   2613:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2614:         }
1.832     raeburn  2615:         if (ref($roledoms) eq 'ARRAY') {
                   2616:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2617:                 next;
                   2618:             }
                   2619:         }
                   2620:         if (ref($roles) eq 'ARRAY') {
                   2621:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2622:                 if ($role =~ /^cr\//) {
                   2623:                     if (!grep(/^cr$/,@{$roles})) {
                   2624:                         next;
                   2625:                     }
                   2626:                 } else {
                   2627:                     next;
                   2628:                 }
1.832     raeburn  2629:             }
1.867     raeburn  2630:         }
1.937     raeburn  2631:         if ($hidepriv) {
                   2632:             if ((&privileged($username,$domain)) &&
                   2633:                 (!$nothide{$username.':'.$domain})) { 
                   2634:                 next;
                   2635:             }
                   2636:         }
1.933     raeburn  2637:         if ($withsec) {
                   2638:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2639:                 $tstart.':'.$tend;
                   2640:         } else {
                   2641:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2642:         }
1.832     raeburn  2643:     }
1.373     www      2644:     return %returnhash;
1.399     www      2645: }
                   2646: 
                   2647: # ----------------------------------------------------- Frontpage Announcements
                   2648: #
                   2649: #
                   2650: 
                   2651: sub postannounce {
                   2652:     my ($server,$text)=@_;
1.844     albertel 2653:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2654:     unless ($text=~/\w/) { $text=''; }
                   2655:     return &reply('setannounce:'.&escape($text),$server);
                   2656: }
                   2657: 
                   2658: sub getannounce {
1.448     albertel 2659: 
                   2660:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2661: 	my $announcement='';
1.800     albertel 2662: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2663: 	close($fh);
1.399     www      2664: 	if ($announcement=~/\w/) { 
                   2665: 	    return 
                   2666:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2667:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2668: 	} else {
                   2669: 	    return '';
                   2670: 	}
                   2671:     } else {
                   2672: 	return '';
                   2673:     }
1.351     www      2674: }
1.353     www      2675: 
                   2676: # ---------------------------------------------------------- Course ID routines
                   2677: # Deal with domain's nohist_courseid.db files
                   2678: #
                   2679: 
                   2680: sub courseidput {
1.921     raeburn  2681:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2682:     my $outcome;
                   2683:     if ($caller eq 'timeonly') {
                   2684:         my $cids = '';
                   2685:         foreach my $item (keys(%$storehash)) {
                   2686:             $cids.=&escape($item).'&';
                   2687:         }
                   2688:         $cids=~s/\&$//;
                   2689:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2690:                           $coursehome);       
                   2691:     } else {
                   2692:         my $items = '';
                   2693:         foreach my $item (keys(%$storehash)) {
                   2694:             $items.= &escape($item).'='.
                   2695:                      &freeze_escape($$storehash{$item}).'&';
                   2696:         }
                   2697:         $items=~s/\&$//;
                   2698:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2699:                           $coursehome);
1.918     raeburn  2700:     }
                   2701:     if ($outcome eq 'unknown_cmd') {
                   2702:         my $what;
                   2703:         foreach my $cid (keys(%$storehash)) {
                   2704:             $what .= &escape($cid).'=';
1.921     raeburn  2705:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2706:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2707:             }
                   2708:             $what =~ s/\:$/&/;
                   2709:         }
                   2710:         $what =~ s/\&$//;  
                   2711:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2712:     } else {
                   2713:         return $outcome;
                   2714:     }
1.353     www      2715: }
                   2716: 
                   2717: sub courseiddump {
1.921     raeburn  2718:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2719:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
                   2720:         $selfenrollonly)=@_;
1.918     raeburn  2721:     my $as_hash = 1;
                   2722:     my %returnhash;
                   2723:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2724:     my %libserv = &all_library();
                   2725:     foreach my $tryserver (keys(%libserv)) {
                   2726:         if ( (  $hostidflag == 1 
                   2727: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2728: 	     || (!defined($hostidflag)) ) {
                   2729: 
1.918     raeburn  2730: 	    if (($domfilter eq '') ||
                   2731: 		(&host_domain($tryserver) eq $domfilter)) {
                   2732:                 my $rep = 
                   2733:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2734:                          $sincefilter.':'.&escape($descfilter).':'.
                   2735:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2736:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2737:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   2738:                          &escape($selfenrollonly),$tryserver);
1.918     raeburn  2739:                 my @pairs=split(/\&/,$rep);
                   2740:                 foreach my $item (@pairs) {
                   2741:                     my ($key,$value)=split(/\=/,$item,2);
                   2742:                     $key = &unescape($key);
                   2743:                     next if ($key =~ /^error: 2 /);
                   2744:                     my $result = &thaw_unescape($value);
                   2745:                     if (ref($result) eq 'HASH') {
                   2746:                         $returnhash{$key}=$result;
                   2747:                     } else {
1.921     raeburn  2748:                         my @responses = split(/:/,$value);
                   2749:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2750:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2751:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2752:                         }
                   2753:                     } 
1.353     www      2754:                 }
                   2755:             }
                   2756:         }
                   2757:     }
                   2758:     return %returnhash;
                   2759: }
                   2760: 
1.658     raeburn  2761: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2762: 
                   2763: sub dcmailput {
1.685     raeburn  2764:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2765:     my $status = &Apache::lonnet::critical(
1.740     www      2766:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2767:        &escape($message),$server);
1.662     raeburn  2768:     return $status;
                   2769: }
                   2770: 
1.658     raeburn  2771: sub dcmaildump {
                   2772:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2773:     my %returnhash=();
1.846     albertel 2774: 
                   2775:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2776:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2777:                                                          &escape($enddate).':';
                   2778: 	my @esc_senders=map { &escape($_)} @$senders;
                   2779: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2780: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2781:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2782:             if (($key) && ($value)) {
                   2783:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2784:             }
                   2785:         }
                   2786:     }
                   2787:     return %returnhash;
                   2788: }
1.662     raeburn  2789: # ---------------------------------------------------------- Domain roles
                   2790: 
                   2791: sub get_domain_roles {
                   2792:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2793:     if (undef($startdate) || $startdate eq '') {
                   2794:         $startdate = '.';
                   2795:     }
                   2796:     if (undef($enddate) || $enddate eq '') {
                   2797:         $enddate = '.';
                   2798:     }
1.922     raeburn  2799:     my $rolelist;
                   2800:     if (ref($roles) eq 'ARRAY') {
                   2801:         $rolelist = join(':',@{$roles});
                   2802:     }
1.662     raeburn  2803:     my %personnel = ();
1.841     albertel 2804: 
                   2805:     my %servers = &get_servers($dom,'library');
                   2806:     foreach my $tryserver (keys(%servers)) {
                   2807: 	%{$personnel{$tryserver}}=();
                   2808: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2809: 					    &escape($startdate).':'.
                   2810: 					    &escape($enddate).':'.
                   2811: 					    &escape($rolelist), $tryserver))) {
                   2812: 	    my ($key,$value) = split(/\=/,$line,2);
                   2813: 	    if (($key) && ($value)) {
                   2814: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2815: 	    }
                   2816: 	}
1.662     raeburn  2817:     }
                   2818:     return %personnel;
                   2819: }
1.658     raeburn  2820: 
1.149     www      2821: # ----------------------------------------------------------- Check out an item
                   2822: 
1.504     albertel 2823: sub get_first_access {
                   2824:     my ($type,$argsymb)=@_;
1.790     albertel 2825:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2826:     if ($argsymb) { $symb=$argsymb; }
                   2827:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2828:     if ($type eq 'course') {
                   2829: 	$res='course';
                   2830:     } elsif ($type eq 'map') {
1.588     albertel 2831: 	$res=&symbread($map);
                   2832:     } else {
                   2833: 	$res=$symb;
                   2834:     }
                   2835:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2836:     return $times{"$courseid\0$res"};
1.504     albertel 2837: }
                   2838: 
                   2839: sub set_first_access {
                   2840:     my ($type)=@_;
1.790     albertel 2841:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2842:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2843:     if ($type eq 'course') {
                   2844: 	$res='course';
                   2845:     } elsif ($type eq 'map') {
1.588     albertel 2846: 	$res=&symbread($map);
                   2847:     } else {
                   2848: 	$res=$symb;
                   2849:     }
                   2850:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2851:     if (!$firstaccess) {
1.588     albertel 2852: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2853:     }
                   2854:     return 'already_set';
1.504     albertel 2855: }
                   2856: 
1.149     www      2857: sub checkout {
                   2858:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2859:     my $now=time;
                   2860:     my $lonhost=$perlvar{'lonHostID'};
                   2861:     my $infostr=&escape(
1.234     www      2862:                  'CHECKOUTTOKEN&'.
1.149     www      2863:                  $tuname.'&'.
                   2864:                  $tudom.'&'.
                   2865:                  $tcrsid.'&'.
                   2866:                  $symb.'&'.
                   2867: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2868:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2869:     if ($token=~/^error\:/) { 
1.672     albertel 2870:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2871:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2872:                  "</font>");
                   2873:         return ''; 
                   2874:     }
                   2875: 
1.149     www      2876:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2877:     $token=~tr/a-z/A-Z/;
                   2878: 
1.153     www      2879:     my %infohash=('resource.0.outtoken' => $token,
                   2880:                   'resource.0.checkouttime' => $now,
                   2881:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2882: 
                   2883:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2884:        return '';
1.151     www      2885:     } else {
1.672     albertel 2886:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2887:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2888:                  "</font>");
1.149     www      2889:     }    
                   2890: 
                   2891:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2892:                          &escape('Checkout '.$infostr.' - '.
                   2893:                                                  $token)) ne 'ok') {
                   2894: 	return '';
1.151     www      2895:     } else {
1.672     albertel 2896:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2897:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2898:                  "</font>");
1.149     www      2899:     }
1.151     www      2900:     return $token;
1.149     www      2901: }
                   2902: 
                   2903: # ------------------------------------------------------------ Check in an item
                   2904: 
                   2905: sub checkin {
                   2906:     my $token=shift;
1.150     www      2907:     my $now=time;
                   2908:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2909:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2910:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2911:     $dtoken=~s/\W/\_/g;
1.234     www      2912:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2913:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2914: 
1.154     www      2915:     unless (($tuname) && ($tudom)) {
                   2916:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2917:         return '';
                   2918:     }
                   2919:     
                   2920:     unless (&allowed('mgr',$tcrsid)) {
                   2921:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2922:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2923:         return '';
                   2924:     }
                   2925: 
1.153     www      2926:     my %infohash=('resource.0.intoken' => $token,
                   2927:                   'resource.0.checkintime' => $now,
                   2928:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2929: 
                   2930:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2931:        return '';
                   2932:     }    
                   2933: 
                   2934:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2935:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2936: 	return '';
                   2937:     }
                   2938: 
                   2939:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2940: }
                   2941: 
                   2942: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2943: 
                   2944: sub expirespread {
                   2945:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2946:     my $cid=$env{'request.course.id'}; 
1.110     www      2947:     if ($cid) {
                   2948:        my $now=time;
                   2949:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2950:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2951:                             $env{'course.'.$cid.'.num'}.
1.110     www      2952: 	        	    ':nohist_expirationdates:'.
                   2953:                             &escape($key).'='.$now,
1.620     albertel 2954:                             $env{'course.'.$cid.'.home'})
1.110     www      2955:     }
                   2956:     return 'ok';
1.14      www      2957: }
                   2958: 
1.109     www      2959: # ----------------------------------------------------- Devalidate Spreadsheets
                   2960: 
                   2961: sub devalidate {
1.325     www      2962:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2963:     my $cid=$env{'request.course.id'}; 
1.109     www      2964:     if ($cid) {
1.391     matthew  2965:         # delete the stored spreadsheets for
                   2966:         # - the student level sheet of this user in course's homespace
                   2967:         # - the assessment level sheet for this resource 
                   2968:         #   for this user in user's homespace
1.553     albertel 2969: 	# - current conditional state info
1.325     www      2970: 	my $key=$uname.':'.$udom.':';
1.109     www      2971:         my $status=
1.299     matthew  2972: 	    &del('nohist_calculatedsheets',
1.391     matthew  2973: 		 [$key.'studentcalc:'],
1.620     albertel 2974: 		 $env{'course.'.$cid.'.domain'},
                   2975: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2976: 		.' '.
                   2977: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2978: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2979:         unless ($status eq 'ok ok') {
                   2980:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2981:                     $uname.' at '.$udom.' for '.
1.109     www      2982: 		    $symb.': '.$status);
1.133     albertel 2983:         }
1.553     albertel 2984: 	&delenv('user.state.'.$cid);
1.109     www      2985:     }
                   2986: }
                   2987: 
1.265     albertel 2988: sub get_scalar {
                   2989:     my ($string,$end) = @_;
                   2990:     my $value;
                   2991:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2992: 	$value = $1;
                   2993:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2994: 	$value = $1;
                   2995:     }
                   2996:     return &unescape($value);
                   2997: }
                   2998: 
                   2999: sub array2str {
                   3000:   my (@array) = @_;
                   3001:   my $result=&arrayref2str(\@array);
                   3002:   $result=~s/^__ARRAY_REF__//;
                   3003:   $result=~s/__END_ARRAY_REF__$//;
                   3004:   return $result;
                   3005: }
                   3006: 
1.204     albertel 3007: sub arrayref2str {
                   3008:   my ($arrayref) = @_;
1.265     albertel 3009:   my $result='__ARRAY_REF__';
1.204     albertel 3010:   foreach my $elem (@$arrayref) {
1.265     albertel 3011:     if(ref($elem) eq 'ARRAY') {
                   3012:       $result.=&arrayref2str($elem).'&';
                   3013:     } elsif(ref($elem) eq 'HASH') {
                   3014:       $result.=&hashref2str($elem).'&';
                   3015:     } elsif(ref($elem)) {
                   3016:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3017:     } else {
                   3018:       $result.=&escape($elem).'&';
                   3019:     }
                   3020:   }
                   3021:   $result=~s/\&$//;
1.265     albertel 3022:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3023:   return $result;
                   3024: }
                   3025: 
1.168     albertel 3026: sub hash2str {
1.204     albertel 3027:   my (%hash) = @_;
                   3028:   my $result=&hashref2str(\%hash);
1.265     albertel 3029:   $result=~s/^__HASH_REF__//;
                   3030:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3031:   return $result;
                   3032: }
                   3033: 
                   3034: sub hashref2str {
                   3035:   my ($hashref)=@_;
1.265     albertel 3036:   my $result='__HASH_REF__';
1.800     albertel 3037:   foreach my $key (sort(keys(%$hashref))) {
                   3038:     if (ref($key) eq 'ARRAY') {
                   3039:       $result.=&arrayref2str($key).'=';
                   3040:     } elsif (ref($key) eq 'HASH') {
                   3041:       $result.=&hashref2str($key).'=';
                   3042:     } elsif (ref($key)) {
1.265     albertel 3043:       $result.='=';
1.800     albertel 3044:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3045:     } else {
1.800     albertel 3046: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3047:     }
                   3048: 
1.800     albertel 3049:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3050:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3051:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3052:       $result.=&hashref2str($hashref->{$key}).'&';
                   3053:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3054:        $result.='&';
1.800     albertel 3055:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3056:     } else {
1.800     albertel 3057:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3058:     }
                   3059:   }
1.168     albertel 3060:   $result=~s/\&$//;
1.265     albertel 3061:   $result .= '__END_HASH_REF__';
1.168     albertel 3062:   return $result;
                   3063: }
                   3064: 
                   3065: sub str2hash {
1.265     albertel 3066:     my ($string)=@_;
                   3067:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3068:     return %$hash;
                   3069: }
                   3070: 
                   3071: sub str2hashref {
1.168     albertel 3072:   my ($string) = @_;
1.265     albertel 3073: 
                   3074:   my %hash;
                   3075: 
                   3076:   if($string !~ /^__HASH_REF__/) {
                   3077:       if (! ($string eq '' || !defined($string))) {
                   3078: 	  $hash{'error'}='Not hash reference';
                   3079:       }
                   3080:       return (\%hash, $string);
                   3081:   }
                   3082: 
                   3083:   $string =~ s/^__HASH_REF__//;
                   3084: 
                   3085:   while($string !~ /^__END_HASH_REF__/) {
                   3086:       #key
                   3087:       my $key='';
                   3088:       if($string =~ /^__HASH_REF__/) {
                   3089:           ($key, $string)=&str2hashref($string);
                   3090:           if(defined($key->{'error'})) {
                   3091:               $hash{'error'}='Bad data';
                   3092:               return (\%hash, $string);
                   3093:           }
                   3094:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3095:           ($key, $string)=&str2arrayref($string);
                   3096:           if($key->[0] eq 'Array reference error') {
                   3097:               $hash{'error'}='Bad data';
                   3098:               return (\%hash, $string);
                   3099:           }
                   3100:       } else {
                   3101:           $string =~ s/^(.*?)=//;
1.267     albertel 3102: 	  $key=&unescape($1);
1.265     albertel 3103:       }
                   3104:       $string =~ s/^=//;
                   3105: 
                   3106:       #value
                   3107:       my $value='';
                   3108:       if($string =~ /^__HASH_REF__/) {
                   3109:           ($value, $string)=&str2hashref($string);
                   3110:           if(defined($value->{'error'})) {
                   3111:               $hash{'error'}='Bad data';
                   3112:               return (\%hash, $string);
                   3113:           }
                   3114:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3115:           ($value, $string)=&str2arrayref($string);
                   3116:           if($value->[0] eq 'Array reference error') {
                   3117:               $hash{'error'}='Bad data';
                   3118:               return (\%hash, $string);
                   3119:           }
                   3120:       } else {
                   3121: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3122:       }
                   3123:       $string =~ s/^&//;
                   3124: 
                   3125:       $hash{$key}=$value;
1.204     albertel 3126:   }
1.265     albertel 3127: 
                   3128:   $string =~ s/^__END_HASH_REF__//;
                   3129: 
                   3130:   return (\%hash, $string);
1.204     albertel 3131: }
                   3132: 
                   3133: sub str2array {
1.265     albertel 3134:     my ($string)=@_;
                   3135:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3136:     return @$array;
                   3137: }
                   3138: 
                   3139: sub str2arrayref {
1.204     albertel 3140:   my ($string) = @_;
1.265     albertel 3141:   my @array;
                   3142: 
                   3143:   if($string !~ /^__ARRAY_REF__/) {
                   3144:       if (! ($string eq '' || !defined($string))) {
                   3145: 	  $array[0]='Array reference error';
                   3146:       }
                   3147:       return (\@array, $string);
                   3148:   }
                   3149: 
                   3150:   $string =~ s/^__ARRAY_REF__//;
                   3151: 
                   3152:   while($string !~ /^__END_ARRAY_REF__/) {
                   3153:       my $value='';
                   3154:       if($string =~ /^__HASH_REF__/) {
                   3155:           ($value, $string)=&str2hashref($string);
                   3156:           if(defined($value->{'error'})) {
                   3157:               $array[0] ='Array reference error';
                   3158:               return (\@array, $string);
                   3159:           }
                   3160:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3161:           ($value, $string)=&str2arrayref($string);
                   3162:           if($value->[0] eq 'Array reference error') {
                   3163:               $array[0] ='Array reference error';
                   3164:               return (\@array, $string);
                   3165:           }
                   3166:       } else {
                   3167: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3168:       }
                   3169:       $string =~ s/^&//;
                   3170: 
                   3171:       push(@array, $value);
1.191     harris41 3172:   }
1.265     albertel 3173: 
                   3174:   $string =~ s/^__END_ARRAY_REF__//;
                   3175: 
                   3176:   return (\@array, $string);
1.168     albertel 3177: }
                   3178: 
1.167     albertel 3179: # -------------------------------------------------------------------Temp Store
                   3180: 
1.168     albertel 3181: sub tmpreset {
                   3182:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3183:   if (!$symb) {
                   3184:     $symb=&symbread();
1.620     albertel 3185:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3186:   }
                   3187:   $symb=escape($symb);
                   3188: 
1.620     albertel 3189:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3190:   $namespace=~s/\//\_/g;
                   3191:   $namespace=~s/\W//g;
                   3192: 
1.620     albertel 3193:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3194:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3195:   if ($domain eq 'public' && $stuname eq 'public') {
                   3196:       $stuname=$ENV{'REMOTE_ADDR'};
                   3197:   }
1.168     albertel 3198:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3199:   my %hash;
                   3200:   if (tie(%hash,'GDBM_File',
                   3201: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3202: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3203:     foreach my $key (keys %hash) {
1.180     albertel 3204:       if ($key=~ /:$symb/) {
1.168     albertel 3205: 	delete($hash{$key});
                   3206:       }
                   3207:     }
                   3208:   }
                   3209: }
                   3210: 
1.167     albertel 3211: sub tmpstore {
1.168     albertel 3212:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3213: 
                   3214:   if (!$symb) {
                   3215:     $symb=&symbread();
1.620     albertel 3216:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3217:   }
                   3218:   $symb=escape($symb);
                   3219: 
                   3220:   if (!$namespace) {
                   3221:     # I don't think we would ever want to store this for a course.
                   3222:     # it seems this will only be used if we don't have a course.
1.620     albertel 3223:     #$namespace=$env{'request.course.id'};
1.168     albertel 3224:     #if (!$namespace) {
1.620     albertel 3225:       $namespace=$env{'request.state'};
1.168     albertel 3226:     #}
                   3227:   }
                   3228:   $namespace=~s/\//\_/g;
                   3229:   $namespace=~s/\W//g;
1.620     albertel 3230:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3231:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3232:   if ($domain eq 'public' && $stuname eq 'public') {
                   3233:       $stuname=$ENV{'REMOTE_ADDR'};
                   3234:   }
1.168     albertel 3235:   my $now=time;
                   3236:   my %hash;
                   3237:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3238:   if (tie(%hash,'GDBM_File',
                   3239: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3240: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3241:     $hash{"version:$symb"}++;
                   3242:     my $version=$hash{"version:$symb"};
                   3243:     my $allkeys=''; 
                   3244:     foreach my $key (keys(%$storehash)) {
                   3245:       $allkeys.=$key.':';
1.591     albertel 3246:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3247:     }
                   3248:     $hash{"$version:$symb:timestamp"}=$now;
                   3249:     $allkeys.='timestamp';
                   3250:     $hash{"$version:keys:$symb"}=$allkeys;
                   3251:     if (untie(%hash)) {
                   3252:       return 'ok';
                   3253:     } else {
                   3254:       return "error:$!";
                   3255:     }
                   3256:   } else {
                   3257:     return "error:$!";
                   3258:   }
                   3259: }
1.167     albertel 3260: 
1.168     albertel 3261: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3262: 
1.168     albertel 3263: sub tmprestore {
                   3264:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3265: 
1.168     albertel 3266:   if (!$symb) {
                   3267:     $symb=&symbread();
1.620     albertel 3268:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3269:   }
                   3270:   $symb=escape($symb);
                   3271: 
1.620     albertel 3272:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3273: 
1.620     albertel 3274:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3275:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3276:   if ($domain eq 'public' && $stuname eq 'public') {
                   3277:       $stuname=$ENV{'REMOTE_ADDR'};
                   3278:   }
1.168     albertel 3279:   my %returnhash;
                   3280:   $namespace=~s/\//\_/g;
                   3281:   $namespace=~s/\W//g;
                   3282:   my %hash;
                   3283:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3284:   if (tie(%hash,'GDBM_File',
                   3285: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3286: 	  &GDBM_READER(),0640)) {
1.168     albertel 3287:     my $version=$hash{"version:$symb"};
                   3288:     $returnhash{'version'}=$version;
                   3289:     my $scope;
                   3290:     for ($scope=1;$scope<=$version;$scope++) {
                   3291:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3292:       my @keys=split(/:/,$vkeys);
                   3293:       my $key;
                   3294:       $returnhash{"$scope:keys"}=$vkeys;
                   3295:       foreach $key (@keys) {
1.591     albertel 3296: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3297: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3298:       }
                   3299:     }
1.168     albertel 3300:     if (!(untie(%hash))) {
                   3301:       return "error:$!";
                   3302:     }
                   3303:   } else {
                   3304:     return "error:$!";
                   3305:   }
                   3306:   return %returnhash;
1.167     albertel 3307: }
                   3308: 
1.9       www      3309: # ----------------------------------------------------------------------- Store
                   3310: 
                   3311: sub store {
1.124     www      3312:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3313:     my $home='';
                   3314: 
1.168     albertel 3315:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3316: 
1.213     www      3317:     $symb=&symbclean($symb);
1.122     albertel 3318:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3319: 
1.620     albertel 3320:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3321:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3322: 
                   3323:     &devalidate($symb,$stuname,$domain);
1.109     www      3324: 
                   3325:     $symb=escape($symb);
1.187     www      3326:     if (!$namespace) { 
1.620     albertel 3327:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3328:           return ''; 
                   3329:        } 
                   3330:     }
1.620     albertel 3331:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3332: 
                   3333:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3334:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3335: 
1.12      www      3336:     my $namevalue='';
1.800     albertel 3337:     foreach my $key (keys(%$storehash)) {
                   3338:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3339:     }
1.12      www      3340:     $namevalue=~s/\&$//;
1.187     www      3341:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3342:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3343: }
                   3344: 
1.47      www      3345: # -------------------------------------------------------------- Critical Store
                   3346: 
                   3347: sub cstore {
1.124     www      3348:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3349:     my $home='';
                   3350: 
1.168     albertel 3351:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3352: 
1.213     www      3353:     $symb=&symbclean($symb);
1.122     albertel 3354:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3355: 
1.620     albertel 3356:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3357:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3358: 
                   3359:     &devalidate($symb,$stuname,$domain);
1.109     www      3360: 
                   3361:     $symb=escape($symb);
1.187     www      3362:     if (!$namespace) { 
1.620     albertel 3363:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3364:           return ''; 
                   3365:        } 
                   3366:     }
1.620     albertel 3367:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3368: 
                   3369:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3370:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3371: 
1.47      www      3372:     my $namevalue='';
1.800     albertel 3373:     foreach my $key (keys(%$storehash)) {
                   3374:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3375:     }
1.47      www      3376:     $namevalue=~s/\&$//;
1.187     www      3377:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3378:     return critical
                   3379:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3380: }
                   3381: 
1.9       www      3382: # --------------------------------------------------------------------- Restore
                   3383: 
                   3384: sub restore {
1.124     www      3385:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3386:     my $home='';
                   3387: 
1.168     albertel 3388:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3389: 
1.122     albertel 3390:     if (!$symb) {
                   3391:       unless ($symb=escape(&symbread())) { return ''; }
                   3392:     } else {
1.213     www      3393:       $symb=&escape(&symbclean($symb));
1.122     albertel 3394:     }
1.188     www      3395:     if (!$namespace) { 
1.620     albertel 3396:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3397:           return ''; 
                   3398:        } 
                   3399:     }
1.620     albertel 3400:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3401:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3402:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3403:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3404: 
1.12      www      3405:     my %returnhash=();
1.800     albertel 3406:     foreach my $line (split(/\&/,$answer)) {
                   3407: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3408:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3409:     }
1.75      www      3410:     my $version;
                   3411:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3412:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3413:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3414:        }
1.75      www      3415:     }
1.13      www      3416:     return %returnhash;
1.34      www      3417: }
                   3418: 
                   3419: # ---------------------------------------------------------- Course Description
                   3420: 
                   3421: sub coursedescription {
1.731     albertel 3422:     my ($courseid,$args)=@_;
1.34      www      3423:     $courseid=~s/^\///;
1.49      www      3424:     $courseid=~s/\_/\//g;
1.34      www      3425:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3426:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3427:     my $normalid=$cdomain.'_'.$cnum;
                   3428:     # need to always cache even if we get errors otherwise we keep 
                   3429:     # trying and trying and trying to get the course description.
                   3430:     my %envhash=();
                   3431:     my %returnhash=();
1.731     albertel 3432:     
                   3433:     my $expiretime=600;
                   3434:     if ($env{'request.course.id'} eq $normalid) {
                   3435: 	$expiretime=120;
                   3436:     }
                   3437: 
                   3438:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3439:     if (!$args->{'freshen_cache'}
                   3440: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3441: 	foreach my $key (keys(%env)) {
                   3442: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3443: 	    my ($setting) = $1;
                   3444: 	    $returnhash{$setting} = $env{$key};
                   3445: 	}
                   3446: 	return %returnhash;
                   3447:     }
                   3448: 
                   3449:     # get the data agin
                   3450:     if (!$args->{'one_time'}) {
                   3451: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3452:     }
1.811     albertel 3453: 
1.34      www      3454:     if ($chome ne 'no_host') {
1.302     albertel 3455:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3456:        if (!exists($returnhash{'con_lost'})) {
                   3457:            $returnhash{'home'}= $chome;
                   3458: 	   $returnhash{'domain'} = $cdomain;
                   3459: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3460:            if (!defined($returnhash{'type'})) {
                   3461:                $returnhash{'type'} = 'Course';
                   3462:            }
1.130     albertel 3463:            while (my ($name,$value) = each %returnhash) {
1.53      www      3464:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3465:            }
1.270     www      3466:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3467:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3468: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3469:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3470:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3471:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3472:        }
                   3473:     }
1.731     albertel 3474:     if (!$args->{'one_time'}) {
1.949     raeburn  3475: 	&appenv(\%envhash);
1.731     albertel 3476:     }
1.302     albertel 3477:     return %returnhash;
1.461     www      3478: }
                   3479: 
                   3480: # -------------------------------------------------See if a user is privileged
                   3481: 
                   3482: sub privileged {
                   3483:     my ($username,$domain)=@_;
                   3484:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3485: 			&homeserver($username,$domain));
                   3486:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3487:     my $now=time;
                   3488:     if ($rolesdump ne '') {
1.800     albertel 3489:         foreach my $entry (split(/&/,$rolesdump)) {
                   3490: 	    if ($entry!~/^rolesdef_/) {
                   3491: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3492: 		$area=~s/\_\w\w$//;
                   3493: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3494: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3495: 		    my $active=1;
                   3496: 		    if ($tend) {
                   3497: 			if ($tend<$now) { $active=0; }
                   3498: 		    }
                   3499: 		    if ($tstart) {
                   3500: 			if ($tstart>$now) { $active=0; }
                   3501: 		    }
                   3502: 		    if ($active) { return 1; }
                   3503: 		}
                   3504: 	    }
                   3505: 	}
                   3506:     }
                   3507:     return 0;
1.9       www      3508: }
1.1       albertel 3509: 
1.103     harris41 3510: # -------------------------------------------------------- Get user privileges
1.11      www      3511: 
                   3512: sub rolesinit {
                   3513:     my ($domain,$username,$authhost)=@_;
                   3514:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3515:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3516:     my %allroles=();
1.678     raeburn  3517:     my %allgroups=();   
1.11      www      3518:     my $now=time;
1.743     albertel 3519:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3520:     my $group_privs;
1.11      www      3521: 
                   3522:     if ($rolesdump ne '') {
1.800     albertel 3523:         foreach my $entry (split(/&/,$rolesdump)) {
                   3524: 	  if ($entry!~/^rolesdef_/) {
                   3525:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3526: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3527:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3528: 	    if ($role=~/^cr/) { 
1.807     albertel 3529: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3530: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3531: 		    ($tend,$tstart)=split('_',$trest);
                   3532: 		} else {
                   3533: 		    $trole=$role;
                   3534: 		}
1.678     raeburn  3535:             } elsif ($role =~ m|^gr/|) {
                   3536:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3537:                 ($trole,$group_privs) = split(/\//,$trole);
                   3538:                 $group_privs = &unescape($group_privs);
1.587     albertel 3539: 	    } else {
                   3540: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3541: 	    }
1.743     albertel 3542: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3543: 					 $username);
                   3544: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3545:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3546:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3547:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3548: 		my $spec=$trole.'.'.$area;
                   3549: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3550: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3551:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3552:                 } elsif ($trole eq 'gr') {
                   3553:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3554: 		} else {
1.567     raeburn  3555:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3556: 		}
1.12      www      3557:             }
1.662     raeburn  3558:           }
1.191     harris41 3559:         }
1.743     albertel 3560:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3561:         $userroles{'user.adv'}    = $adv;
                   3562: 	$userroles{'user.author'} = $author;
1.620     albertel 3563:         $env{'user.adv'}=$adv;
1.11      www      3564:     }
1.743     albertel 3565:     return \%userroles;  
1.11      www      3566: }
                   3567: 
1.567     raeburn  3568: sub set_arearole {
                   3569:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3570: # log the associated role with the area
                   3571:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3572:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3573: }
                   3574: 
                   3575: sub custom_roleprivs {
                   3576:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3577:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3578:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3579:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3580:         my ($rdummy,$roledef)=
                   3581:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3582:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3583:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3584:             if (defined($syspriv)) {
                   3585:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3586:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3587:             }
                   3588:             if ($tdomain ne '') {
                   3589:                 if (defined($dompriv)) {
                   3590:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3591:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3592:                 }
                   3593:                 if (($trest ne '') && (defined($coursepriv))) {
                   3594:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3595:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3596:                 }
                   3597:             }
                   3598:         }
                   3599:     }
                   3600: }
                   3601: 
1.678     raeburn  3602: sub group_roleprivs {
                   3603:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3604:     my $access = 1;
                   3605:     my $now = time;
                   3606:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3607:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3608:     if ($access) {
1.811     albertel 3609:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3610:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3611:     }
                   3612: }
1.567     raeburn  3613: 
                   3614: sub standard_roleprivs {
                   3615:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3616:     if (defined($pr{$trole.':s'})) {
                   3617:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3618:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3619:     }
                   3620:     if ($tdomain ne '') {
                   3621:         if (defined($pr{$trole.':d'})) {
                   3622:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3623:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3624:         }
                   3625:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3626:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3627:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3628:         }
                   3629:     }
                   3630: }
                   3631: 
                   3632: sub set_userprivs {
1.678     raeburn  3633:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3634:     my $author=0;
                   3635:     my $adv=0;
1.678     raeburn  3636:     my %grouproles = ();
                   3637:     if (keys(%{$allgroups}) > 0) {
                   3638:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3639:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3640:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3641:                 $trole = $1;
                   3642:                 $area = $2;
1.681     raeburn  3643:                 $sec = $3;
                   3644:                 $extendedarea = $area.$sec;
                   3645:                 if (exists($$allgroups{$area})) {
                   3646:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3647:                         my $spec = $trole.'.'.$extendedarea;
                   3648:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3649:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3650:                     }
                   3651:                 }
                   3652:             }
                   3653:         }
                   3654:     }
1.800     albertel 3655:     foreach my $group (keys(%grouproles)) {
                   3656:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3657:     }
1.800     albertel 3658:     foreach my $role (keys(%{$allroles})) {
                   3659:         my %thesepriv;
1.941     raeburn  3660:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3661:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3662:             if ($item ne '') {
                   3663:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3664:                 if ($restrictions eq '') {
                   3665:                     $thesepriv{$privilege}='F';
                   3666:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3667:                     $thesepriv{$privilege}.=$restrictions;
                   3668:                 }
                   3669:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3670:             }
                   3671:         }
                   3672:         my $thesestr='';
1.800     albertel 3673:         foreach my $priv (keys(%thesepriv)) {
                   3674: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3675: 	}
                   3676:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3677:     }
                   3678:     return ($author,$adv);
                   3679: }
                   3680: 
1.12      www      3681: # --------------------------------------------------------------- get interface
                   3682: 
                   3683: sub get {
1.131     albertel 3684:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3685:    my $items='';
1.800     albertel 3686:    foreach my $item (@$storearr) {
                   3687:        $items.=&escape($item).'&';
1.191     harris41 3688:    }
1.12      www      3689:    $items=~s/\&$//;
1.620     albertel 3690:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3691:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3692:    my $uhome=&homeserver($uname,$udomain);
                   3693: 
1.133     albertel 3694:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3695:    my @pairs=split(/\&/,$rep);
1.273     albertel 3696:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3697:      return @pairs;
                   3698:    }
1.15      www      3699:    my %returnhash=();
1.42      www      3700:    my $i=0;
1.800     albertel 3701:    foreach my $item (@$storearr) {
                   3702:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3703:       $i++;
1.191     harris41 3704:    }
1.15      www      3705:    return %returnhash;
1.27      www      3706: }
                   3707: 
                   3708: # --------------------------------------------------------------- del interface
                   3709: 
                   3710: sub del {
1.133     albertel 3711:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3712:    my $items='';
1.800     albertel 3713:    foreach my $item (@$storearr) {
                   3714:        $items.=&escape($item).'&';
1.191     harris41 3715:    }
1.27      www      3716:    $items=~s/\&$//;
1.620     albertel 3717:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3718:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3719:    my $uhome=&homeserver($uname,$udomain);
                   3720: 
                   3721:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3722: }
                   3723: 
                   3724: # -------------------------------------------------------------- dump interface
                   3725: 
                   3726: sub dump {
1.755     albertel 3727:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3728:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3729:     if (!$uname) { $uname=$env{'user.name'}; }
                   3730:     my $uhome=&homeserver($uname,$udomain);
                   3731:     if ($regexp) {
                   3732: 	$regexp=&escape($regexp);
                   3733:     } else {
                   3734: 	$regexp='.';
                   3735:     }
                   3736:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3737:     my @pairs=split(/\&/,$rep);
                   3738:     my %returnhash=();
                   3739:     foreach my $item (@pairs) {
                   3740: 	my ($key,$value)=split(/=/,$item,2);
                   3741: 	$key = &unescape($key);
                   3742: 	next if ($key =~ /^error: 2 /);
                   3743: 	$returnhash{$key}=&thaw_unescape($value);
                   3744:     }
                   3745:     return %returnhash;
1.407     www      3746: }
                   3747: 
1.717     albertel 3748: # --------------------------------------------------------- dumpstore interface
                   3749: 
                   3750: sub dumpstore {
                   3751:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3752:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3753:    if (!$uname) { $uname=$env{'user.name'}; }
                   3754:    my $uhome=&homeserver($uname,$udomain);
                   3755:    if ($regexp) {
                   3756:        $regexp=&escape($regexp);
                   3757:    } else {
                   3758:        $regexp='.';
                   3759:    }
                   3760:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3761:    my @pairs=split(/\&/,$rep);
                   3762:    my %returnhash=();
                   3763:    foreach my $item (@pairs) {
                   3764:        my ($key,$value)=split(/=/,$item,2);
                   3765:        next if ($key =~ /^error: 2 /);
                   3766:        $returnhash{$key}=&thaw_unescape($value);
                   3767:    }
                   3768:    return %returnhash;
1.717     albertel 3769: }
                   3770: 
1.407     www      3771: # -------------------------------------------------------------- keys interface
                   3772: 
                   3773: sub getkeys {
                   3774:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3775:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3776:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3777:    my $uhome=&homeserver($uname,$udomain);
                   3778:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3779:    my @keyarray=();
1.800     albertel 3780:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3781:       next if ($key =~ /^error: 2 /);
1.800     albertel 3782:       push(@keyarray,&unescape($key));
1.407     www      3783:    }
                   3784:    return @keyarray;
1.318     matthew  3785: }
                   3786: 
1.319     matthew  3787: # --------------------------------------------------------------- currentdump
                   3788: sub currentdump {
1.328     matthew  3789:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3790:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3791:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3792:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3793:    my $uhome = &homeserver($sname,$sdom);
                   3794:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3795:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3796:    #
1.318     matthew  3797:    my %returnhash=();
1.319     matthew  3798:    #
                   3799:    if ($rep eq "unknown_cmd") { 
                   3800:        # an old lond will not know currentdump
                   3801:        # Do a dump and make it look like a currentdump
1.822     albertel 3802:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3803:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3804:        my %hash = @tmp;
                   3805:        @tmp=();
1.424     matthew  3806:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3807:    } else {
                   3808:        my @pairs=split(/\&/,$rep);
1.800     albertel 3809:        foreach my $pair (@pairs) {
                   3810:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3811:            my ($symb,$param) = split(/:/,$key);
                   3812:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3813:                                                         &thaw_unescape($value);
1.319     matthew  3814:        }
1.191     harris41 3815:    }
1.12      www      3816:    return %returnhash;
1.424     matthew  3817: }
                   3818: 
                   3819: sub convert_dump_to_currentdump{
                   3820:     my %hash = %{shift()};
                   3821:     my %returnhash;
                   3822:     # Code ripped from lond, essentially.  The only difference
                   3823:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3824:     # we might run in to problems with parameter names =~ /^v\./
                   3825:     while (my ($key,$value) = each(%hash)) {
                   3826:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3827: 	$symb  = &unescape($symb);
                   3828: 	$param = &unescape($param);
1.424     matthew  3829:         next if ($v eq 'version' || $symb eq 'keys');
                   3830:         next if (exists($returnhash{$symb}) &&
                   3831:                  exists($returnhash{$symb}->{$param}) &&
                   3832:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3833:         $returnhash{$symb}->{$param}=$value;
                   3834:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3835:     }
                   3836:     #
                   3837:     # Remove all of the keys in the hashes which keep track of
                   3838:     # the version of the parameter.
                   3839:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3840:         # use a foreach because we are going to delete from the hash.
                   3841:         foreach my $key (keys(%$param_hash)) {
                   3842:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3843:         }
                   3844:     }
                   3845:     return \%returnhash;
1.12      www      3846: }
                   3847: 
1.627     albertel 3848: # ------------------------------------------------------ critical inc interface
                   3849: 
                   3850: sub cinc {
                   3851:     return &inc(@_,'critical');
                   3852: }
                   3853: 
1.449     matthew  3854: # --------------------------------------------------------------- inc interface
                   3855: 
                   3856: sub inc {
1.627     albertel 3857:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3858:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3859:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3860:     my $uhome=&homeserver($uname,$udomain);
                   3861:     my $items='';
                   3862:     if (! ref($store)) {
                   3863:         # got a single value, so use that instead
                   3864:         $items = &escape($store).'=&';
                   3865:     } elsif (ref($store) eq 'SCALAR') {
                   3866:         $items = &escape($$store).'=&';        
                   3867:     } elsif (ref($store) eq 'ARRAY') {
                   3868:         $items = join('=&',map {&escape($_);} @{$store});
                   3869:     } elsif (ref($store) eq 'HASH') {
                   3870:         while (my($key,$value) = each(%{$store})) {
                   3871:             $items.= &escape($key).'='.&escape($value).'&';
                   3872:         }
                   3873:     }
                   3874:     $items=~s/\&$//;
1.627     albertel 3875:     if ($critical) {
                   3876: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3877:     } else {
                   3878: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3879:     }
1.449     matthew  3880: }
                   3881: 
1.12      www      3882: # --------------------------------------------------------------- put interface
                   3883: 
                   3884: sub put {
1.134     albertel 3885:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3886:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3887:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3888:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3889:    my $items='';
1.800     albertel 3890:    foreach my $item (keys(%$storehash)) {
                   3891:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3892:    }
1.12      www      3893:    $items=~s/\&$//;
1.134     albertel 3894:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3895: }
                   3896: 
1.631     albertel 3897: # ------------------------------------------------------------ newput interface
                   3898: 
                   3899: sub newput {
                   3900:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3901:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3902:    if (!$uname) { $uname=$env{'user.name'}; }
                   3903:    my $uhome=&homeserver($uname,$udomain);
                   3904:    my $items='';
                   3905:    foreach my $key (keys(%$storehash)) {
                   3906:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3907:    }
                   3908:    $items=~s/\&$//;
                   3909:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3910: }
                   3911: 
                   3912: # ---------------------------------------------------------  putstore interface
                   3913: 
1.524     raeburn  3914: sub putstore {
1.715     albertel 3915:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3916:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3917:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3918:    my $uhome=&homeserver($uname,$udomain);
                   3919:    my $items='';
1.715     albertel 3920:    foreach my $key (keys(%$storehash)) {
                   3921:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3922:    }
1.715     albertel 3923:    $items=~s/\&$//;
1.716     albertel 3924:    my $esc_symb=&escape($symb);
                   3925:    my $esc_v=&escape($version);
1.715     albertel 3926:    my $reply =
1.716     albertel 3927:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3928: 	      $uhome);
                   3929:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3930:        # gfall back to way things use to be done
1.715     albertel 3931:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3932: 			    $uname);
1.524     raeburn  3933:    }
1.715     albertel 3934:    return $reply;
                   3935: }
                   3936: 
                   3937: sub old_putstore {
1.716     albertel 3938:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3939:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3940:     if (!$uname) { $uname=$env{'user.name'}; }
                   3941:     my $uhome=&homeserver($uname,$udomain);
                   3942:     my %newstorehash;
1.800     albertel 3943:     foreach my $item (keys(%$storehash)) {
                   3944: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3945: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3946:     }
                   3947:     my $items='';
                   3948:     my %allitems = ();
1.800     albertel 3949:     foreach my $item (keys(%newstorehash)) {
                   3950: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3951: 	    my $key = $1.':keys:'.$2;
                   3952: 	    $allitems{$key} .= $3.':';
                   3953: 	}
1.800     albertel 3954: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3955:     }
1.800     albertel 3956:     foreach my $item (keys(%allitems)) {
                   3957: 	$allitems{$item} =~ s/\:$//;
                   3958: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3959:     }
                   3960:     $items=~s/\&$//;
                   3961:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3962: }
                   3963: 
1.47      www      3964: # ------------------------------------------------------ critical put interface
                   3965: 
                   3966: sub cput {
1.134     albertel 3967:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3968:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3969:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3970:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3971:    my $items='';
1.800     albertel 3972:    foreach my $item (keys(%$storehash)) {
                   3973:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3974:    }
1.47      www      3975:    $items=~s/\&$//;
1.134     albertel 3976:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3977: }
                   3978: 
                   3979: # -------------------------------------------------------------- eget interface
                   3980: 
                   3981: sub eget {
1.133     albertel 3982:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3983:    my $items='';
1.800     albertel 3984:    foreach my $item (@$storearr) {
                   3985:        $items.=&escape($item).'&';
1.191     harris41 3986:    }
1.12      www      3987:    $items=~s/\&$//;
1.620     albertel 3988:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3989:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3990:    my $uhome=&homeserver($uname,$udomain);
                   3991:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3992:    my @pairs=split(/\&/,$rep);
                   3993:    my %returnhash=();
1.42      www      3994:    my $i=0;
1.800     albertel 3995:    foreach my $item (@$storearr) {
                   3996:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3997:       $i++;
1.191     harris41 3998:    }
1.12      www      3999:    return %returnhash;
                   4000: }
                   4001: 
1.667     albertel 4002: # ------------------------------------------------------------ tmpput interface
                   4003: sub tmpput {
1.802     raeburn  4004:     my ($storehash,$server,$context)=@_;
1.667     albertel 4005:     my $items='';
1.800     albertel 4006:     foreach my $item (keys(%$storehash)) {
                   4007: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4008:     }
                   4009:     $items=~s/\&$//;
1.802     raeburn  4010:     if (defined($context)) {
                   4011:         $items .= ':'.&escape($context);
                   4012:     }
1.667     albertel 4013:     return &reply("tmpput:$items",$server);
                   4014: }
                   4015: 
                   4016: # ------------------------------------------------------------ tmpget interface
                   4017: sub tmpget {
1.688     albertel 4018:     my ($token,$server)=@_;
                   4019:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4020:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4021:     my %returnhash;
                   4022:     foreach my $item (split(/\&/,$rep)) {
                   4023: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4024:         next if ($key =~ /^error: 2 /);
1.667     albertel 4025: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4026:     }
                   4027:     return %returnhash;
                   4028: }
                   4029: 
1.688     albertel 4030: # ------------------------------------------------------------ tmpget interface
                   4031: sub tmpdel {
                   4032:     my ($token,$server)=@_;
                   4033:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4034:     return &reply("tmpdel:$token",$server);
                   4035: }
                   4036: 
1.765     albertel 4037: # -------------------------------------------------- portfolio access checking
                   4038: 
                   4039: sub portfolio_access {
1.766     albertel 4040:     my ($requrl) = @_;
1.765     albertel 4041:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4042:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4043:     if ($result) {
                   4044:         my %setters;
                   4045:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4046:             my ($startblock,$endblock) =
                   4047:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4048:             if ($startblock && $endblock) {
                   4049:                 return 'B';
                   4050:             }
                   4051:         } else {
                   4052:             my ($startblock,$endblock) =
                   4053:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4054:             if ($startblock && $endblock) {
                   4055:                 return 'B';
                   4056:             }
                   4057:         }
                   4058:     }
1.765     albertel 4059:     if ($result eq 'ok') {
1.766     albertel 4060:        return 'F';
1.765     albertel 4061:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4062:        return 'A';
1.765     albertel 4063:     }
1.766     albertel 4064:     return '';
1.765     albertel 4065: }
                   4066: 
                   4067: sub get_portfolio_access {
1.767     albertel 4068:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4069: 
                   4070:     if (!ref($access_hash)) {
                   4071: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4072: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4073: 						   $file_name);
                   4074: 	$access_hash = $access_controls{$file_name};
                   4075:     }
                   4076: 
1.765     albertel 4077:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4078:     my $now = time;
                   4079:     if (ref($access_hash) eq 'HASH') {
                   4080:         foreach my $key (keys(%{$access_hash})) {
                   4081:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4082:             if ($start > $now) {
                   4083:                 next;
                   4084:             }
                   4085:             if ($end && $end<$now) {
                   4086:                 next;
                   4087:             }
                   4088:             if ($scope eq 'public') {
                   4089:                 $public = $key;
                   4090:                 last;
                   4091:             } elsif ($scope eq 'guest') {
                   4092:                 $guest = $key;
                   4093:             } elsif ($scope eq 'domains') {
                   4094:                 push(@domains,$key);
                   4095:             } elsif ($scope eq 'users') {
                   4096:                 push(@users,$key);
                   4097:             } elsif ($scope eq 'course') {
                   4098:                 push(@courses,$key);
                   4099:             } elsif ($scope eq 'group') {
                   4100:                 push(@groups,$key);
                   4101:             }
                   4102:         }
                   4103:         if ($public) {
                   4104:             return 'ok';
                   4105:         }
                   4106:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4107:             if ($guest) {
                   4108:                 return $guest;
                   4109:             }
                   4110:         } else {
                   4111:             if (@domains > 0) {
                   4112:                 foreach my $domkey (@domains) {
                   4113:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4114:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4115:                             return 'ok';
                   4116:                         }
                   4117:                     }
                   4118:                 }
                   4119:             }
                   4120:             if (@users > 0) {
                   4121:                 foreach my $userkey (@users) {
1.865     raeburn  4122:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4123:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4124:                             if (ref($item) eq 'HASH') {
                   4125:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4126:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4127:                                     return 'ok';
                   4128:                                 }
                   4129:                             }
                   4130:                         }
                   4131:                     } 
1.765     albertel 4132:                 }
                   4133:             }
                   4134:             my %roleshash;
                   4135:             my @courses_and_groups = @courses;
                   4136:             push(@courses_and_groups,@groups); 
                   4137:             if (@courses_and_groups > 0) {
                   4138:                 my (%allgroups,%allroles); 
                   4139:                 my ($start,$end,$role,$sec,$group);
                   4140:                 foreach my $envkey (%env) {
1.811     albertel 4141:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4142:                         my $cid = $2.'_'.$3; 
                   4143:                         if ($1 eq 'gr') {
                   4144:                             $group = $4;
                   4145:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4146:                         } else {
                   4147:                             if ($4 eq '') {
                   4148:                                 $sec = 'none';
                   4149:                             } else {
                   4150:                                 $sec = $4;
                   4151:                             }
                   4152:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4153:                         }
1.811     albertel 4154:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4155:                         my $cid = $2.'_'.$3;
                   4156:                         if ($4 eq '') {
                   4157:                             $sec = 'none';
                   4158:                         } else {
                   4159:                             $sec = $4;
                   4160:                         }
                   4161:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4162:                     }
                   4163:                 }
                   4164:                 if (keys(%allroles) == 0) {
                   4165:                     return;
                   4166:                 }
                   4167:                 foreach my $key (@courses_and_groups) {
                   4168:                     my %content = %{$$access_hash{$key}};
                   4169:                     my $cnum = $content{'number'};
                   4170:                     my $cdom = $content{'domain'};
                   4171:                     my $cid = $cdom.'_'.$cnum;
                   4172:                     if (!exists($allroles{$cid})) {
                   4173:                         next;
                   4174:                     }    
                   4175:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4176:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4177:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4178:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4179:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4180:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4181:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4182:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4183:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4184:                                         if (grep/^all$/,@sections) {
                   4185:                                             return 'ok';
                   4186:                                         } else {
                   4187:                                             if (grep/^$sec$/,@sections) {
                   4188:                                                 return 'ok';
                   4189:                                             }
                   4190:                                         }
                   4191:                                     }
                   4192:                                 }
                   4193:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4194:                                     if (grep/^none$/,@groups) {
                   4195:                                         return 'ok';
                   4196:                                     }
                   4197:                                 } else {
                   4198:                                     if (grep/^all$/,@groups) {
                   4199:                                         return 'ok';
                   4200:                                     } 
                   4201:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4202:                                         if (grep/^$group$/,@groups) {
                   4203:                                             return 'ok';
                   4204:                                         }
                   4205:                                     }
                   4206:                                 } 
                   4207:                             }
                   4208:                         }
                   4209:                     }
                   4210:                 }
                   4211:             }
                   4212:             if ($guest) {
                   4213:                 return $guest;
                   4214:             }
                   4215:         }
                   4216:     }
                   4217:     return;
                   4218: }
                   4219: 
                   4220: sub course_group_datechecker {
                   4221:     my ($dates,$now,$status) = @_;
                   4222:     my ($start,$end) = split(/\./,$dates);
                   4223:     if (!$start && !$end) {
                   4224:         return 'ok';
                   4225:     }
                   4226:     if (grep/^active$/,@{$status}) {
                   4227:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4228:             return 'ok';
                   4229:         }
                   4230:     }
                   4231:     if (grep/^previous$/,@{$status}) {
                   4232:         if ($end > $now ) {
                   4233:             return 'ok';
                   4234:         }
                   4235:     }
                   4236:     if (grep/^future$/,@{$status}) {
                   4237:         if ($start > $now) {
                   4238:             return 'ok';
                   4239:         }
                   4240:     }
                   4241:     return; 
                   4242: }
                   4243: 
                   4244: sub parse_portfolio_url {
                   4245:     my ($url) = @_;
                   4246: 
                   4247:     my ($type,$udom,$unum,$group,$file_name);
                   4248:     
1.823     albertel 4249:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4250: 	$type = 1;
                   4251:         $udom = $1;
                   4252:         $unum = $2;
                   4253:         $file_name = $3;
1.823     albertel 4254:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4255: 	$type = 2;
                   4256:         $udom = $1;
                   4257:         $unum = $2;
                   4258:         $group = $3;
                   4259:         $file_name = $3.'/'.$4;
                   4260:     }
                   4261:     if (wantarray) {
                   4262: 	return ($type,$udom,$unum,$file_name,$group);
                   4263:     }
                   4264:     return $type;
                   4265: }
                   4266: 
                   4267: sub is_portfolio_url {
                   4268:     my ($url) = @_;
                   4269:     return scalar(&parse_portfolio_url($url));
                   4270: }
                   4271: 
1.798     raeburn  4272: sub is_portfolio_file {
                   4273:     my ($file) = @_;
1.820     raeburn  4274:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4275:         return 1;
                   4276:     }
                   4277:     return;
                   4278: }
                   4279: 
                   4280: 
1.341     www      4281: # ---------------------------------------------- Custom access rule evaluation
                   4282: 
                   4283: sub customaccess {
                   4284:     my ($priv,$uri)=@_;
1.807     albertel 4285:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4286:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4287:     $udom = &LONCAPA::clean_domain($udom);
                   4288:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4289:     my $access=0;
1.800     albertel 4290:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4291: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4292: 	if ($type eq 'user') {
                   4293: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4294: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4295: 		if ($tdom) {
                   4296: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4297: 		}
1.896     albertel 4298: 		if ($tuname) {
                   4299: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4300: 		}
                   4301: 		$access=($effect eq 'allow');
                   4302: 		last;
                   4303: 	    }
                   4304: 	} else {
                   4305: 	    if ($role) {
                   4306: 		if ($role ne $urole) { next; }
                   4307: 	    }
                   4308: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4309: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4310: 		if ($tdom) {
                   4311: 		    if ($tdom ne $udom) { next; }
                   4312: 		}
                   4313: 		if ($tcrs) {
                   4314: 		    if ($tcrs ne $ucrs) { next; }
                   4315: 		}
                   4316: 		if ($tsec) {
                   4317: 		    if ($tsec ne $usec) { next; }
                   4318: 		}
                   4319: 		$access=($effect eq 'allow');
                   4320: 		last;
                   4321: 	    }
                   4322: 	    if ($realm eq '' && $role eq '') {
                   4323: 		$access=($effect eq 'allow');
                   4324: 	    }
1.402     bowersj2 4325: 	}
1.341     www      4326:     }
                   4327:     return $access;
                   4328: }
                   4329: 
1.103     harris41 4330: # ------------------------------------------------- Check for a user privilege
1.12      www      4331: 
                   4332: sub allowed {
1.810     raeburn  4333:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4334:     my $ver_orguri=$uri;
1.439     www      4335:     $uri=&deversion($uri);
1.152     www      4336:     my $orguri=$uri;
1.52      www      4337:     $uri=&declutter($uri);
1.809     raeburn  4338: 
1.810     raeburn  4339:     if ($priv eq 'evb') {
                   4340: # Evade communication block restrictions for specified role in a course
                   4341:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4342:             return $1;
                   4343:         } else {
                   4344:             return;
                   4345:         }
                   4346:     }
                   4347: 
1.620     albertel 4348:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4349: # Free bre access to adm and meta resources
1.775     albertel 4350:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4351: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4352: 	&& ($priv eq 'bre')) {
1.14      www      4353: 	return 'F';
1.159     www      4354:     }
                   4355: 
1.545     banghart 4356: # Free bre access to user's own portfolio contents
1.714     raeburn  4357:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4358:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4359: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4360:         my %setters;
                   4361:         my ($startblock,$endblock) = 
                   4362:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4363:         if ($startblock && $endblock) {
                   4364:             return 'B';
                   4365:         } else {
                   4366:             return 'F';
                   4367:         }
1.545     banghart 4368:     }
                   4369: 
1.762     raeburn  4370: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4371:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4372:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4373:         if (exists($env{'request.course.id'})) {
                   4374:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4375:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4376:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4377:                 my $courseprivid=$env{'request.course.id'};
                   4378:                 $courseprivid=~s/\_/\//;
                   4379:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4380:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4381:                     return $1; 
1.762     raeburn  4382:                 } else {
                   4383:                     if ($env{'request.course.sec'}) {
                   4384:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4385:                     }
                   4386:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4387:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4388:                         return $2;
                   4389:                     }
1.714     raeburn  4390:                 }
                   4391:             }
                   4392:         }
                   4393:     }
                   4394: 
1.159     www      4395: # Free bre to public access
                   4396: 
                   4397:     if ($priv eq 'bre') {
1.238     www      4398:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4399: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4400:            return 'F'; 
                   4401:         }
1.238     www      4402:         if ($copyright eq 'priv') {
                   4403:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4404: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4405: 		return '';
                   4406:             }
                   4407:         }
                   4408:         if ($copyright eq 'domain') {
                   4409:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4410: 	    unless (($env{'user.domain'} eq $1) ||
                   4411:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4412: 		return '';
                   4413:             }
1.262     matthew  4414:         }
1.620     albertel 4415:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4416:             # Library role, so allow browsing of resources in this domain.
                   4417:             return 'F';
1.238     www      4418:         }
1.341     www      4419:         if ($copyright eq 'custom') {
                   4420: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4421:         }
1.14      www      4422:     }
1.264     matthew  4423:     # Domain coordinator is trying to create a course
1.620     albertel 4424:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4425:         # uri is the requested domain in this case.
                   4426:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4427:         # a role of dc for the domain in question.
1.620     albertel 4428:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4429:     }
1.29      www      4430: 
1.52      www      4431:     my $thisallowed='';
                   4432:     my $statecond=0;
                   4433:     my $courseprivid='';
                   4434: 
                   4435: # Course
                   4436: 
1.620     albertel 4437:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4438:        $thisallowed.=$1;
                   4439:     }
1.29      www      4440: 
1.52      www      4441: # Domain
                   4442: 
1.620     albertel 4443:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4444:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4445:        $thisallowed.=$1;
                   4446:     }
1.52      www      4447: 
                   4448: # Course: uri itself is a course
1.66      www      4449:     my $courseuri=$uri;
                   4450:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4451:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4452: 
1.620     albertel 4453:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4454:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4455:        $thisallowed.=$1;
                   4456:     }
1.29      www      4457: 
1.665     albertel 4458: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4459: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4460:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4461: 	$thisallowed='';
1.671     raeburn  4462:         my ($match)=&is_on_map($uri);
                   4463:         if ($match) {
                   4464:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4465:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4466:                 $thisallowed.=$1;
                   4467:             }
                   4468:         } else {
1.705     albertel 4469:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4470:             if ($refuri) {
                   4471:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4472:                     $thisallowed='F';
1.671     raeburn  4473:                 } else {
                   4474:                     $refuri=&declutter($refuri);
                   4475:                     my ($match) = &is_on_map($refuri);
                   4476:                     if ($match) {
                   4477:                         $thisallowed='F';
                   4478:                     }
1.669     raeburn  4479:                 }
1.671     raeburn  4480:             }
                   4481:         }
1.314     www      4482:     }
1.492     albertel 4483: 
1.766     albertel 4484:     if ($priv eq 'bre'
                   4485: 	&& $thisallowed ne 'F' 
                   4486: 	&& $thisallowed ne '2'
                   4487: 	&& &is_portfolio_url($uri)) {
                   4488: 	$thisallowed = &portfolio_access($uri);
                   4489:     }
                   4490:     
1.52      www      4491: # Full access at system, domain or course-wide level? Exit.
1.29      www      4492: 
                   4493:     if ($thisallowed=~/F/) {
                   4494: 	return 'F';
                   4495:     }
                   4496: 
1.52      www      4497: # If this is generating or modifying users, exit with special codes
1.29      www      4498: 
1.643     www      4499:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4500: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4501: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4502: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4503: 	    unless ($auname) { return $thisallowed; }
                   4504: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4505: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4506: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4507: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4508: 	}
1.52      www      4509: 	return $thisallowed;
                   4510:     }
                   4511: #
1.103     harris41 4512: # Gathered so far: system, domain and course wide privileges
1.52      www      4513: #
                   4514: # Course: See if uri or referer is an individual resource that is part of 
                   4515: # the course
                   4516: 
1.620     albertel 4517:     if ($env{'request.course.id'}) {
1.232     www      4518: 
1.620     albertel 4519:        $courseprivid=$env{'request.course.id'};
                   4520:        if ($env{'request.course.sec'}) {
                   4521:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4522:        }
                   4523:        $courseprivid=~s/\_/\//;
                   4524:        my $checkreferer=1;
1.232     www      4525:        my ($match,$cond)=&is_on_map($uri);
                   4526:        if ($match) {
                   4527:            $statecond=$cond;
1.620     albertel 4528:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4529:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4530:                $thisallowed.=$1;
                   4531:                $checkreferer=0;
                   4532:            }
1.29      www      4533:        }
1.83      www      4534:        
1.148     www      4535:        if ($checkreferer) {
1.620     albertel 4536: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4537:             unless ($refuri) {
1.800     albertel 4538:                 foreach my $key (keys(%env)) {
                   4539: 		    if ($key=~/^httpref\..*\*/) {
                   4540: 			my $pattern=$key;
1.156     www      4541:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4542:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4543:                         $pattern=~s/\//\\\//g;
1.152     www      4544:                         if ($orguri=~/$pattern/) {
1.800     albertel 4545: 			    $refuri=$env{$key};
1.148     www      4546:                         }
                   4547:                     }
1.191     harris41 4548:                 }
1.148     www      4549:             }
1.232     www      4550: 
1.148     www      4551:          if ($refuri) { 
1.152     www      4552: 	  $refuri=&declutter($refuri);
1.232     www      4553:           my ($match,$cond)=&is_on_map($refuri);
                   4554:             if ($match) {
                   4555:               my $refstatecond=$cond;
1.620     albertel 4556:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4557:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4558:                   $thisallowed.=$1;
1.53      www      4559:                   $uri=$refuri;
                   4560:                   $statecond=$refstatecond;
1.52      www      4561:               }
                   4562:           }
1.148     www      4563:         }
1.29      www      4564:        }
1.52      www      4565:    }
1.29      www      4566: 
1.52      www      4567: #
1.103     harris41 4568: # Gathered now: all privileges that could apply, and condition number
1.52      www      4569: # 
                   4570: #
                   4571: # Full or no access?
                   4572: #
1.29      www      4573: 
1.52      www      4574:     if ($thisallowed=~/F/) {
                   4575: 	return 'F';
                   4576:     }
1.29      www      4577: 
1.52      www      4578:     unless ($thisallowed) {
                   4579:         return '';
                   4580:     }
1.29      www      4581: 
1.52      www      4582: # Restrictions exist, deal with them
                   4583: #
                   4584: #   C:according to course preferences
                   4585: #   R:according to resource settings
                   4586: #   L:unless locked
                   4587: #   X:according to user session state
                   4588: #
                   4589: 
                   4590: # Possibly locked functionality, check all courses
1.54      www      4591: # Locks might take effect only after 10 minutes cache expiration for other
                   4592: # courses, and 2 minutes for current course
1.52      www      4593: 
                   4594:     my $envkey;
                   4595:     if ($thisallowed=~/L/) {
1.620     albertel 4596:         foreach $envkey (keys %env) {
1.54      www      4597:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4598:                my $courseid=$2;
                   4599:                my $roleid=$1.'.'.$2;
1.92      www      4600:                $courseid=~s/^\///;
1.54      www      4601:                my $expiretime=600;
1.620     albertel 4602:                if ($env{'request.role'} eq $roleid) {
1.54      www      4603: 		  $expiretime=120;
                   4604:                }
                   4605: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4606:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4607:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4608: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4609:                }
1.620     albertel 4610:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4611:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4612: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4613:                        &log($env{'user.domain'},$env{'user.name'},
                   4614:                             $env{'user.home'},
1.57      www      4615:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4616:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4617:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4618: 		       return '';
                   4619:                    }
                   4620:                }
1.620     albertel 4621:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4622:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4623: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4624:                        &log($env{'user.domain'},$env{'user.name'},
                   4625:                             $env{'user.home'},
1.57      www      4626:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4627:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4628:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4629: 		       return '';
                   4630:                    }
                   4631:                }
                   4632: 	   }
1.29      www      4633:        }
1.52      www      4634:     }
                   4635:    
                   4636: #
                   4637: # Rest of the restrictions depend on selected course
                   4638: #
                   4639: 
1.620     albertel 4640:     unless ($env{'request.course.id'}) {
1.766     albertel 4641: 	if ($thisallowed eq 'A') {
                   4642: 	    return 'A';
1.814     raeburn  4643:         } elsif ($thisallowed eq 'B') {
                   4644:             return 'B';
1.766     albertel 4645: 	} else {
                   4646: 	    return '1';
                   4647: 	}
1.52      www      4648:     }
1.29      www      4649: 
1.52      www      4650: #
                   4651: # Now user is definitely in a course
                   4652: #
1.53      www      4653: 
                   4654: 
                   4655: # Course preferences
                   4656: 
                   4657:    if ($thisallowed=~/C/) {
1.620     albertel 4658:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4659:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4660:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4661: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4662: 	   if ($priv ne 'pch') { 
                   4663: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4664: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4665: 			$env{'request.course.id'});
                   4666: 	   }
1.237     www      4667:            return '';
                   4668:        }
                   4669: 
1.620     albertel 4670:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4671: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4672: 	   if ($priv ne 'pch') { 
                   4673: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4674: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4675: 			$env{'request.course.id'});
                   4676: 	   }
1.54      www      4677:            return '';
                   4678:        }
1.53      www      4679:    }
                   4680: 
                   4681: # Resource preferences
                   4682: 
                   4683:    if ($thisallowed=~/R/) {
1.620     albertel 4684:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4685:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4686: 	   if ($priv ne 'pch') { 
                   4687: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4688: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4689: 	   }
                   4690: 	   return '';
1.54      www      4691:        }
1.53      www      4692:    }
1.30      www      4693: 
1.246     www      4694: # Restricted by state or randomout?
1.30      www      4695: 
1.52      www      4696:    if ($thisallowed=~/X/) {
1.620     albertel 4697:       if ($env{'acc.randomout'}) {
1.579     albertel 4698: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4699:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4700:             return ''; 
                   4701:          }
1.247     www      4702:       }
                   4703:       if (&condval($statecond)) {
1.52      www      4704: 	 return '2';
                   4705:       } else {
                   4706:          return '';
                   4707:       }
                   4708:    }
1.30      www      4709: 
1.766     albertel 4710:     if ($thisallowed eq 'A') {
                   4711: 	return 'A';
1.814     raeburn  4712:     } elsif ($thisallowed eq 'B') {
                   4713:         return 'B';
1.766     albertel 4714:     }
1.52      www      4715:    return 'F';
1.232     www      4716: }
                   4717: 
1.710     albertel 4718: sub split_uri_for_cond {
                   4719:     my $uri=&deversion(&declutter(shift));
                   4720:     my @uriparts=split(/\//,$uri);
                   4721:     my $filename=pop(@uriparts);
                   4722:     my $pathname=join('/',@uriparts);
                   4723:     return ($pathname,$filename);
                   4724: }
1.232     www      4725: # --------------------------------------------------- Is a resource on the map?
                   4726: 
                   4727: sub is_on_map {
1.710     albertel 4728:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4729:     #Trying to find the conditional for the file
1.620     albertel 4730:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4731: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4732:     if ($match) {
1.289     bowersj2 4733: 	return (1,$1);
                   4734:     } else {
1.434     www      4735: 	return (0,0);
1.289     bowersj2 4736:     }
1.12      www      4737: }
                   4738: 
1.427     www      4739: # --------------------------------------------------------- Get symb from alias
                   4740: 
                   4741: sub get_symb_from_alias {
                   4742:     my $symb=shift;
                   4743:     my ($map,$resid,$url)=&decode_symb($symb);
                   4744: # Already is a symb
                   4745:     if ($url) { return $symb; }
                   4746: # Must be an alias
                   4747:     my $aliassymb='';
                   4748:     my %bighash;
1.620     albertel 4749:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4750:                             &GDBM_READER(),0640)) {
                   4751:         my $rid=$bighash{'mapalias_'.$symb};
                   4752: 	if ($rid) {
                   4753: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4754: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4755: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4756: 	}
                   4757:         untie %bighash;
                   4758:     }
                   4759:     return $aliassymb;
                   4760: }
                   4761: 
1.12      www      4762: # ----------------------------------------------------------------- Define Role
                   4763: 
                   4764: sub definerole {
                   4765:   if (allowed('mcr','/')) {
                   4766:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4767:     foreach my $role (split(':',$sysrole)) {
                   4768: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4769:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4770:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4771: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4772:                return "refused:s:$crole&$cqual"; 
                   4773:             }
                   4774:         }
1.191     harris41 4775:     }
1.800     albertel 4776:     foreach my $role (split(':',$domrole)) {
                   4777: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4778:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4779:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4780: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4781:                return "refused:d:$crole&$cqual"; 
                   4782:             }
                   4783:         }
1.191     harris41 4784:     }
1.800     albertel 4785:     foreach my $role (split(':',$courole)) {
                   4786: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4787:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4788:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4789: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4790:                return "refused:c:$crole&$cqual"; 
                   4791:             }
                   4792:         }
1.191     harris41 4793:     }
1.620     albertel 4794:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4795:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4796: 	        "rolesdef_$rolename=".
                   4797:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4798:     return reply($command,$env{'user.home'});
1.12      www      4799:   } else {
                   4800:     return 'refused';
                   4801:   }
1.105     harris41 4802: }
                   4803: 
                   4804: # ---------------- Make a metadata query against the network of library servers
                   4805: 
                   4806: sub metadata_query {
1.244     matthew  4807:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4808:     my %rhash;
1.845     albertel 4809:     my %libserv = &all_library();
1.244     matthew  4810:     my @server_list = (defined($server_array) ? @$server_array
                   4811:                                               : keys(%libserv) );
                   4812:     for my $server (@server_list) {
1.118     harris41 4813: 	unless ($custom or $customshow) {
                   4814: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4815: 	    $rhash{$server}=$reply;
                   4816: 	}
                   4817: 	else {
                   4818: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4819: 			     &escape($custom).':'.&escape($customshow),
                   4820: 			     $server);
                   4821: 	    $rhash{$server}=$reply;
                   4822: 	}
1.112     harris41 4823:     }
1.118     harris41 4824:     return \%rhash;
1.240     www      4825: }
                   4826: 
                   4827: # ----------------------------------------- Send log queries and wait for reply
                   4828: 
                   4829: sub log_query {
                   4830:     my ($uname,$udom,$query,%filters)=@_;
                   4831:     my $uhome=&homeserver($uname,$udom);
                   4832:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4833:     my $uhost=&hostname($uhome);
1.800     albertel 4834:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4835:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4836:                        $uhome);
1.479     albertel 4837:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4838:     return get_query_reply($queryid);
                   4839: }
                   4840: 
1.818     raeburn  4841: # -------------------------- Update MySQL table for portfolio file
                   4842: 
                   4843: sub update_portfolio_table {
1.821     raeburn  4844:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4845:     my $homeserver = &homeserver($uname,$udom);
                   4846:     my $queryid=
1.821     raeburn  4847:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4848:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4849:     my $reply = &get_query_reply($queryid);
                   4850:     return $reply;
                   4851: }
                   4852: 
1.899     raeburn  4853: # -------------------------- Update MySQL allusers table
                   4854: 
                   4855: sub update_allusers_table {
                   4856:     my ($uname,$udom,$names) = @_;
                   4857:     my $homeserver = &homeserver($uname,$udom);
                   4858:     my $queryid=
                   4859:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4860:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4861:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4862:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4863:                'generation='.&escape($names->{'generation'}).'%%'.
                   4864:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4865:                'id='.&escape($names->{'id'}),$homeserver);
                   4866:     my $reply = &get_query_reply($queryid);
                   4867:     return $reply;
                   4868: }
                   4869: 
1.508     raeburn  4870: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4871: 
                   4872: sub fetch_enrollment_query {
1.511     raeburn  4873:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4874:     my $homeserver;
1.547     raeburn  4875:     my $maxtries = 1;
1.508     raeburn  4876:     if ($context eq 'automated') {
                   4877:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4878:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4879:     } else {
                   4880:         $homeserver = &homeserver($cnum,$dom);
                   4881:     }
1.838     albertel 4882:     my $host=&hostname($homeserver);
1.506     raeburn  4883:     my $cmd = '';
1.800     albertel 4884:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4885:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4886:     }
                   4887:     $cmd =~ s/%%$//;
                   4888:     $cmd = &escape($cmd);
                   4889:     my $query = 'fetchenrollment';
1.620     albertel 4890:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4891:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4892:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4893:         return 'error: '.$queryid;
                   4894:     }
1.506     raeburn  4895:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4896:     my $tries = 1;
                   4897:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4898:         $reply = &get_query_reply($queryid);
                   4899:         $tries ++;
                   4900:     }
1.526     raeburn  4901:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4902:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4903:     } else {
1.901     albertel 4904:         my @responses = split(/:/,$reply);
1.515     raeburn  4905:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4906:             foreach my $line (@responses) {
                   4907:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4908:                 $$replyref{$key} = $value;
                   4909:             }
                   4910:         } else {
1.506     raeburn  4911:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4912:             foreach my $line (@responses) {
                   4913:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4914:                 $$replyref{$key} = $value;
                   4915:                 if ($value > 0) {
1.800     albertel 4916:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4917:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4918:                         my $destname = $pathname.'/'.$filename;
                   4919:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4920:                         if ($xml_classlist =~ /^error/) {
                   4921:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4922:                         } else {
1.506     raeburn  4923:                             if ( open(FILE,">$destname") ) {
                   4924:                                 print FILE &unescape($xml_classlist);
                   4925:                                 close(FILE);
1.526     raeburn  4926:                             } else {
                   4927:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4928:                             }
                   4929:                         }
                   4930:                     }
                   4931:                 }
                   4932:             }
                   4933:         }
                   4934:         return 'ok';
                   4935:     }
                   4936:     return 'error';
                   4937: }
                   4938: 
1.242     www      4939: sub get_query_reply {
                   4940:     my $queryid=shift;
1.240     www      4941:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4942:     my $reply='';
                   4943:     for (1..100) {
                   4944: 	sleep 2;
                   4945:         if (-e $replyfile.'.end') {
1.448     albertel 4946: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4947: 		$reply = join('',<$fh>);
                   4948: 		close($fh);
1.240     www      4949: 	   } else { return 'error: reply_file_error'; }
1.242     www      4950:            return &unescape($reply);
                   4951: 	}
1.240     www      4952:     }
1.242     www      4953:     return 'timeout:'.$queryid;
1.240     www      4954: }
                   4955: 
                   4956: sub courselog_query {
1.241     www      4957: #
                   4958: # possible filters:
                   4959: # url: url or symb
                   4960: # username
                   4961: # domain
                   4962: # action: view, submit, grade
                   4963: # start: timestamp
                   4964: # end: timestamp
                   4965: #
1.240     www      4966:     my (%filters)=@_;
1.620     albertel 4967:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4968:     if ($filters{'url'}) {
                   4969: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4970:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4971:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4972:     }
1.620     albertel 4973:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4974:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4975:     return &log_query($cname,$cdom,'courselog',%filters);
                   4976: }
                   4977: 
                   4978: sub userlog_query {
1.858     raeburn  4979: #
                   4980: # possible filters:
                   4981: # action: log check role
                   4982: # start: timestamp
                   4983: # end: timestamp
                   4984: #
1.240     www      4985:     my ($uname,$udom,%filters)=@_;
                   4986:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4987: }
                   4988: 
1.506     raeburn  4989: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4990: 
                   4991: sub auto_run {
1.508     raeburn  4992:     my ($cnum,$cdom) = @_;
1.876     raeburn  4993:     my $response = 0;
                   4994:     my $settings;
                   4995:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4996:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4997:         $settings = $domconfig{'autoenroll'};
                   4998:         if ($settings->{'run'} eq '1') {
                   4999:             $response = 1;
                   5000:         }
                   5001:     } else {
1.934     raeburn  5002:         my $homeserver;
                   5003:         if (&is_course($cdom,$cnum)) {
                   5004:             $homeserver = &homeserver($cnum,$cdom);
                   5005:         } else {
                   5006:             $homeserver = &domain($cdom,'primary');
                   5007:         }
                   5008:         if ($homeserver ne 'no_host') {
                   5009:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5010:         }
1.876     raeburn  5011:     }
1.506     raeburn  5012:     return $response;
                   5013: }
1.776     albertel 5014: 
1.506     raeburn  5015: sub auto_get_sections {
1.508     raeburn  5016:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5017:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5018:     my @secs = ();
1.511     raeburn  5019:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5020:     unless ($response eq 'refused') {
1.901     albertel 5021:         @secs = split(/:/,$response);
1.506     raeburn  5022:     }
                   5023:     return @secs;
                   5024: }
1.776     albertel 5025: 
1.506     raeburn  5026: sub auto_new_course {
1.508     raeburn  5027:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5028:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5029:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5030:     return $response;
                   5031: }
1.776     albertel 5032: 
1.506     raeburn  5033: sub auto_validate_courseID {
1.508     raeburn  5034:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5035:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5036:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5037:     return $response;
                   5038: }
1.776     albertel 5039: 
1.506     raeburn  5040: sub auto_create_password {
1.873     raeburn  5041:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5042:     my ($homeserver,$response);
1.506     raeburn  5043:     my $create_passwd = 0;
                   5044:     my $authchk = '';
1.873     raeburn  5045:     if ($udom =~ /^$match_domain$/) {
                   5046:         $homeserver = &domain($udom,'primary');
                   5047:     }
                   5048:     if ($homeserver eq '') {
                   5049:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5050:             $homeserver = &homeserver($cnum,$cdom);
                   5051:         }
                   5052:     }
                   5053:     if ($homeserver eq '') {
                   5054:         $authchk = 'nodomain';
1.506     raeburn  5055:     } else {
1.873     raeburn  5056:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5057:         if ($response eq 'refused') {
                   5058:             $authchk = 'refused';
                   5059:         } else {
1.901     albertel 5060:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5061:         }
1.506     raeburn  5062:     }
                   5063:     return ($authparam,$create_passwd,$authchk);
                   5064: }
                   5065: 
1.706     raeburn  5066: sub auto_photo_permission {
                   5067:     my ($cnum,$cdom,$students) = @_;
                   5068:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5069:     my ($outcome,$perm_reqd,$conditions) = 
                   5070: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5071:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5072: 	return (undef,undef);
                   5073:     }
1.706     raeburn  5074:     return ($outcome,$perm_reqd,$conditions);
                   5075: }
                   5076: 
                   5077: sub auto_checkphotos {
                   5078:     my ($uname,$udom,$pid) = @_;
                   5079:     my $homeserver = &homeserver($uname,$udom);
                   5080:     my ($result,$resulttype);
                   5081:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5082: 				   &escape($uname).':'.&escape($pid),
                   5083: 				   $homeserver));
1.709     albertel 5084:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5085: 	return (undef,undef);
                   5086:     }
1.706     raeburn  5087:     if ($outcome) {
                   5088:         ($result,$resulttype) = split(/:/,$outcome);
                   5089:     } 
                   5090:     return ($result,$resulttype);
                   5091: }
                   5092: 
                   5093: sub auto_photochoice {
                   5094:     my ($cnum,$cdom) = @_;
                   5095:     my $homeserver = &homeserver($cnum,$cdom);
                   5096:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5097: 						       &escape($cdom),
                   5098: 						       $homeserver)));
1.709     albertel 5099:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5100: 	return (undef,undef);
                   5101:     }
1.706     raeburn  5102:     return ($update,$comment);
                   5103: }
                   5104: 
                   5105: sub auto_photoupdate {
                   5106:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5107:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5108:     my $host=&hostname($homeserver);
1.706     raeburn  5109:     my $cmd = '';
                   5110:     my $maxtries = 1;
1.800     albertel 5111:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5112:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5113:     }
                   5114:     $cmd =~ s/%%$//;
                   5115:     $cmd = &escape($cmd);
                   5116:     my $query = 'institutionalphotos';
                   5117:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5118:     unless ($queryid=~/^\Q$host\E\_/) {
                   5119:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5120:         return 'error: '.$queryid;
                   5121:     }
                   5122:     my $reply = &get_query_reply($queryid);
                   5123:     my $tries = 1;
                   5124:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5125:         $reply = &get_query_reply($queryid);
                   5126:         $tries ++;
                   5127:     }
                   5128:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5129:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5130:     } else {
                   5131:         my @responses = split(/:/,$reply);
                   5132:         my $outcome = shift(@responses); 
                   5133:         foreach my $item (@responses) {
                   5134:             my ($key,$value) = split(/=/,$item);
                   5135:             $$photo{$key} = $value;
                   5136:         }
                   5137:         return $outcome;
                   5138:     }
                   5139:     return 'error';
                   5140: }
                   5141: 
1.521     raeburn  5142: sub auto_instcode_format {
1.793     albertel 5143:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5144: 	$cat_order) = @_;
1.521     raeburn  5145:     my $courses = '';
1.772     raeburn  5146:     my @homeservers;
1.521     raeburn  5147:     if ($caller eq 'global') {
1.841     albertel 5148: 	my %servers = &get_servers($codedom,'library');
                   5149: 	foreach my $tryserver (keys(%servers)) {
                   5150: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5151: 		push(@homeservers,$tryserver);
                   5152: 	    }
1.584     raeburn  5153:         }
1.521     raeburn  5154:     } else {
1.772     raeburn  5155:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5156:     }
1.793     albertel 5157:     foreach my $code (keys(%{$instcodes})) {
                   5158:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5159:     }
                   5160:     chop($courses);
1.772     raeburn  5161:     my $ok_response = 0;
                   5162:     my $response;
                   5163:     while (@homeservers > 0 && $ok_response == 0) {
                   5164:         my $server = shift(@homeservers); 
                   5165:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5166:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5167:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5168: 		split(/:/,$response);
1.772     raeburn  5169:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5170:             push(@{$codetitles},&str2array($codetitles_str));
                   5171:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5172:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5173:             $ok_response = 1;
                   5174:         }
                   5175:     }
                   5176:     if ($ok_response) {
1.521     raeburn  5177:         return 'ok';
1.772     raeburn  5178:     } else {
                   5179:         return $response;
1.521     raeburn  5180:     }
                   5181: }
                   5182: 
1.792     raeburn  5183: sub auto_instcode_defaults {
                   5184:     my ($domain,$returnhash,$code_order) = @_;
                   5185:     my @homeservers;
1.841     albertel 5186: 
                   5187:     my %servers = &get_servers($domain,'library');
                   5188:     foreach my $tryserver (keys(%servers)) {
                   5189: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5190: 	    push(@homeservers,$tryserver);
                   5191: 	}
1.792     raeburn  5192:     }
1.841     albertel 5193: 
1.792     raeburn  5194:     my $response;
1.841     albertel 5195:     foreach my $server (@homeservers) {
1.792     raeburn  5196:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5197:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5198: 	
                   5199: 	foreach my $pair (split(/\&/,$response)) {
                   5200: 	    my ($name,$value)=split(/\=/,$pair);
                   5201: 	    if ($name eq 'code_order') {
                   5202: 		@{$code_order} = split(/\&/,&unescape($value));
                   5203: 	    } else {
                   5204: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5205: 	    }
                   5206: 	}
                   5207: 	return 'ok';
1.792     raeburn  5208:     }
1.841     albertel 5209: 
                   5210:     return $response;
1.792     raeburn  5211: } 
                   5212: 
1.777     albertel 5213: sub auto_validate_class_sec {
1.918     raeburn  5214:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5215:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5216:     my $ownerlist;
                   5217:     if (ref($owners) eq 'ARRAY') {
                   5218:         $ownerlist = join(',',@{$owners});
                   5219:     } else {
                   5220:         $ownerlist = $owners;
                   5221:     }
1.773     raeburn  5222:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5223:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5224:     return $response;
                   5225: }
                   5226: 
1.679     raeburn  5227: # ------------------------------------------------------- Course Group routines
                   5228: 
                   5229: sub get_coursegroups {
1.809     raeburn  5230:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5231:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5232: }
                   5233: 
1.679     raeburn  5234: sub modify_coursegroup {
                   5235:     my ($cdom,$cnum,$groupsettings) = @_;
                   5236:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5237: }
                   5238: 
1.809     raeburn  5239: sub toggle_coursegroup_status {
                   5240:     my ($cdom,$cnum,$group,$action) = @_;
                   5241:     my ($from_namespace,$to_namespace);
                   5242:     if ($action eq 'delete') {
                   5243:         $from_namespace = 'coursegroups';
                   5244:         $to_namespace = 'deleted_groups';
                   5245:     } else {
                   5246:         $from_namespace = 'deleted_groups';
                   5247:         $to_namespace = 'coursegroups';
                   5248:     }
                   5249:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5250:     if (my $tmp = &error(%curr_group)) {
                   5251:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5252:         return ('read error',$tmp);
                   5253:     } else {
                   5254:         my %savedsettings = %curr_group; 
1.809     raeburn  5255:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5256:         my $deloutcome;
                   5257:         if ($result eq 'ok') {
1.809     raeburn  5258:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5259:         } else {
                   5260:             return ('write error',$result);
                   5261:         }
                   5262:         if ($deloutcome eq 'ok') {
                   5263:             return 'ok';
                   5264:         } else {
                   5265:             return ('delete error',$deloutcome);
                   5266:         }
                   5267:     }
                   5268: }
                   5269: 
1.679     raeburn  5270: sub modify_group_roles {
1.957   ! raeburn  5271:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5272:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5273:     my $role = 'gr/'.&escape($userprivs);
                   5274:     my ($uname,$udom) = split(/:/,$user);
1.957   ! raeburn  5275:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5276:     if ($result eq 'ok') {
                   5277:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5278:     }
1.679     raeburn  5279:     return $result;
                   5280: }
                   5281: 
                   5282: sub modify_coursegroup_membership {
                   5283:     my ($cdom,$cnum,$membership) = @_;
                   5284:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5285:     return $result;
                   5286: }
                   5287: 
1.682     raeburn  5288: sub get_active_groups {
                   5289:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5290:     my $now = time;
                   5291:     my %groups = ();
                   5292:     foreach my $key (keys(%env)) {
1.811     albertel 5293:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5294:             my ($start,$end) = split(/\./,$env{$key});
                   5295:             if (($end!=0) && ($end<$now)) { next; }
                   5296:             if (($start!=0) && ($start>$now)) { next; }
                   5297:             if ($1 eq $cdom && $2 eq $cnum) {
                   5298:                 $groups{$3} = $env{$key} ;
                   5299:             }
                   5300:         }
                   5301:     }
                   5302:     return %groups;
                   5303: }
                   5304: 
1.683     raeburn  5305: sub get_group_membership {
                   5306:     my ($cdom,$cnum,$group) = @_;
                   5307:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5308: }
                   5309: 
                   5310: sub get_users_groups {
                   5311:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5312:     my @usersgroups;
1.683     raeburn  5313:     my $cachetime=1800;
                   5314: 
                   5315:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5316:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5317:     if (defined($cached)) {
1.734     albertel 5318:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5319:     } else {  
                   5320:         $grouplist = '';
1.816     raeburn  5321:         my $courseurl = &courseid_to_courseurl($courseid);
                   5322:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5323:         my $access_end = $env{'course.'.$courseid.
                   5324:                               '.default_enrollment_end_date'};
                   5325:         my $now = time;
                   5326:         foreach my $key (keys(%roleshash)) {
                   5327:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5328:                 my $group = $1;
                   5329:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5330:                     my $start = $2;
                   5331:                     my $end = $1;
                   5332:                     if ($start == -1) { next; } # deleted from group
                   5333:                     if (($start!=0) && ($start>$now)) { next; }
                   5334:                     if (($end!=0) && ($end<$now)) {
                   5335:                         if ($access_end && $access_end < $now) {
                   5336:                             if ($access_end - $end < 86400) {
                   5337:                                 push(@usersgroups,$group);
1.733     raeburn  5338:                             }
                   5339:                         }
1.817     raeburn  5340:                         next;
1.733     raeburn  5341:                     }
1.817     raeburn  5342:                     push(@usersgroups,$group);
1.683     raeburn  5343:                 }
                   5344:             }
                   5345:         }
1.817     raeburn  5346:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5347:         $grouplist = join(':',@usersgroups);
                   5348:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5349:     }
1.733     raeburn  5350:     return @usersgroups;
1.683     raeburn  5351: }
                   5352: 
                   5353: sub devalidate_getgroups_cache {
                   5354:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5355:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5356: 
1.683     raeburn  5357:     my $hashid="$udom:$uname:$courseid";
                   5358:     &devalidate_cache_new('getgroups',$hashid);
                   5359: }
                   5360: 
1.12      www      5361: # ------------------------------------------------------------------ Plain Text
                   5362: 
                   5363: sub plaintext {
1.742     raeburn  5364:     my ($short,$type,$cid) = @_;
1.758     albertel 5365:     if ($short =~ /^cr/) {
                   5366: 	return (split('/',$short))[-1];
                   5367:     }
1.742     raeburn  5368:     if (!defined($cid)) {
                   5369:         $cid = $env{'request.course.id'};
                   5370:     }
                   5371:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5372:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5373:                                           '.plaintext'});
                   5374:     }
                   5375:     my %rolenames = (
                   5376:                       Course => 'std',
                   5377:                       Group => 'alt1',
                   5378:                     );
                   5379:     if (defined($type) && 
                   5380:          defined($rolenames{$type}) && 
                   5381:          defined($prp{$short}{$rolenames{$type}})) {
                   5382:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5383:     } else {
                   5384:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5385:     }
1.12      www      5386: }
                   5387: 
                   5388: # ----------------------------------------------------------------- Assign Role
                   5389: 
                   5390: sub assignrole {
1.957   ! raeburn  5391:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
        !          5392:         $context)=@_;
1.21      www      5393:     my $mrole;
                   5394:     if ($role =~ /^cr\//) {
1.393     www      5395:         my $cwosec=$url;
1.811     albertel 5396:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5397: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5398:            &logthis('Refused custom assignrole: '.
                   5399:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5400: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5401:            return 'refused'; 
                   5402:         }
1.21      www      5403:         $mrole='cr';
1.678     raeburn  5404:     } elsif ($role =~ /^gr\//) {
                   5405:         my $cwogrp=$url;
1.811     albertel 5406:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5407:         unless (&allowed('mdg',$cwogrp)) {
                   5408:             &logthis('Refused group assignrole: '.
                   5409:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5410:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5411:             return 'refused';
                   5412:         }
                   5413:         $mrole='gr';
1.21      www      5414:     } else {
1.82      www      5415:         my $cwosec=$url;
1.811     albertel 5416:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5417:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5418:             my $refused;
                   5419:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5420:                 if (!(&allowed('c'.$role,$url))) {
                   5421:                     $refused = 1;
                   5422:                 }
                   5423:             } else {
                   5424:                 $refused = 1;
                   5425:             }
1.947     raeburn  5426:             if ($refused) {
                   5427:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5428:                     $refused = '';
                   5429:                 } else {
                   5430:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5431:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5432: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5433:                     return 'refused';
                   5434:                 }
1.932     raeburn  5435:             }
1.104     www      5436:         }
1.21      www      5437:         $mrole=$role;
                   5438:     }
1.620     albertel 5439:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5440:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5441:     if ($end) { $command.='_'.$end; }
1.21      www      5442:     if ($start) {
                   5443: 	if ($end) { 
1.81      www      5444:            $command.='_'.$start; 
1.21      www      5445:         } else {
1.81      www      5446:            $command.='_0_'.$start;
1.21      www      5447:         }
                   5448:     }
1.739     raeburn  5449:     my $origstart = $start;
                   5450:     my $origend = $end;
1.957   ! raeburn  5451:     my $delflag;
1.357     www      5452: # actually delete
                   5453:     if ($deleteflag) {
1.373     www      5454: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5455: # modify command to delete the role
1.620     albertel 5456:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5457:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5458: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5459: # set start and finish to negative values for userrolelog
                   5460:            $start=-1;
                   5461:            $end=-1;
1.957   ! raeburn  5462:            $delflag = 1;
1.357     www      5463:         }
                   5464:     }
                   5465: # send command
1.349     www      5466:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5467: # log new user role if status is ok
1.349     www      5468:     if ($answer eq 'ok') {
1.663     raeburn  5469: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5470: # for course roles, perform group memberships changes triggered by role change.
1.957   ! raeburn  5471:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5472:         unless ($role =~ /^gr/) {
                   5473:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957   ! raeburn  5474:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5475:         }
1.349     www      5476:     }
                   5477:     return $answer;
1.169     harris41 5478: }
                   5479: 
                   5480: # -------------------------------------------------- Modify user authentication
1.197     www      5481: # Overrides without validation
                   5482: 
1.169     harris41 5483: sub modifyuserauth {
                   5484:     my ($udom,$uname,$umode,$upass)=@_;
                   5485:     my $uhome=&homeserver($uname,$udom);
1.197     www      5486:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5487:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5488:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5489:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5490:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5491: 		     &escape($upass),$uhome);
1.620     albertel 5492:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5493:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5494:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5495:     &log($udom,,$uname,$uhome,
1.620     albertel 5496:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5497:                                      $env{'user.name'}.', '.$umode.
1.197     www      5498:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5499:     unless ($reply eq 'ok') {
1.197     www      5500:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5501: 	return 'error: '.$reply;
                   5502:     }   
1.170     harris41 5503:     return 'ok';
1.80      www      5504: }
                   5505: 
1.81      www      5506: # --------------------------------------------------------------- Modify a user
1.80      www      5507: 
1.81      www      5508: sub modifyuser {
1.206     matthew  5509:     my ($udom,    $uname, $uid,
                   5510:         $umode,   $upass, $first,
                   5511:         $middle,  $last,  $gene,
1.387     www      5512:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5513:     $udom= &LONCAPA::clean_domain($udom);
                   5514:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5515:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5516:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5517: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5518:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5519:                                      ' desiredhome not specified'). 
1.620     albertel 5520:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5521:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5522:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5523: # ----------------------------------------------------------------- Create User
1.406     albertel 5524:     if (($uhome eq 'no_host') && 
                   5525: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5526:         my $unhome='';
1.844     albertel 5527:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5528:             $unhome = $desiredhome;
1.620     albertel 5529: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5530: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5531:         } else { # load balancing routine for determining $unhome
1.81      www      5532:             my $loadm=10000000;
1.841     albertel 5533: 	    my %servers = &get_servers($udom,'library');
                   5534: 	    foreach my $tryserver (keys(%servers)) {
                   5535: 		my $answer=reply('load',$tryserver);
                   5536: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5537: 		    $loadm=$answer;
                   5538: 		    $unhome=$tryserver;
                   5539: 		}
1.80      www      5540: 	    }
                   5541:         }
                   5542:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5543: 	    return 'error: unable to find a home server for '.$uname.
                   5544:                    ' in domain '.$udom;
1.80      www      5545:         }
                   5546:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5547:                          &escape($upass),$unhome);
                   5548: 	unless ($reply eq 'ok') {
                   5549:             return 'error: '.$reply;
                   5550:         }   
1.230     stredwic 5551:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5552:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5553: 	    return 'error: unable verify users home machine.';
1.80      www      5554:         }
1.209     matthew  5555:     }   # End of creation of new user
1.80      www      5556: # ---------------------------------------------------------------------- Add ID
                   5557:     if ($uid) {
                   5558:        $uid=~tr/A-Z/a-z/;
                   5559:        my %uidhash=&idrget($udom,$uname);
1.196     www      5560:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5561:          && (!$forceid)) {
1.80      www      5562: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5563: 	      return 'error: user id "'.$uid.'" does not match '.
                   5564:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5565:           }
                   5566:        } else {
                   5567: 	  &idput($udom,($uname => $uid));
                   5568:        }
                   5569:     }
                   5570: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5571:     my @tmp=&get('environment',
1.899     raeburn  5572: 		   ['firstname','middlename','lastname','generation','id',
                   5573:                     'permanentemail'],
1.134     albertel 5574: 		   $udom,$uname);
1.313     matthew  5575:     my %names;
                   5576:     if ($tmp[0] =~ m/^error:.*/) { 
                   5577:         %names=(); 
                   5578:     } else {
                   5579:         %names = @tmp;
                   5580:     }
1.388     www      5581: #
                   5582: # Make sure to not trash student environment if instructor does not bother
                   5583: # to supply name and email information
                   5584: #
                   5585:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5586:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5587:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5588:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5589:     if ($email) {
                   5590:        $email=~s/[^\w\@\.\-\,]//gs;
                   5591:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5592: 			   $names{'critnotification'} = $email;
                   5593: 			   $names{'permanentemail'} = $email; }
                   5594:     }
1.899     raeburn  5595:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5596:     my $reply = &put('environment', \%names, $udom,$uname);
                   5597:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5598:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5599:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5600:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5601:              $umode.', '.$first.', '.$middle.', '.
                   5602: 	     $last.', '.$gene.' by '.
1.620     albertel 5603:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5604:     return 'ok';
1.80      www      5605: }
                   5606: 
1.81      www      5607: # -------------------------------------------------------------- Modify student
1.80      www      5608: 
1.81      www      5609: sub modifystudent {
                   5610:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957   ! raeburn  5611:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
        !          5612:         $selfenroll,$context)=@_;
1.455     albertel 5613:     if (!$cid) {
1.620     albertel 5614: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5615: 	    return 'not_in_class';
                   5616: 	}
1.80      www      5617:     }
                   5618: # --------------------------------------------------------------- Make the user
1.81      www      5619:     my $reply=&modifyuser
1.209     matthew  5620: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5621:          $desiredhome,$email);
1.80      www      5622:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5623:     # This will cause &modify_student_enrollment to get the uid from the
                   5624:     # students environment
                   5625:     $uid = undef if (!$forceid);
1.455     albertel 5626:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957   ! raeburn  5627: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5628:     return $reply;
                   5629: }
                   5630: 
                   5631: sub modify_student_enrollment {
1.957   ! raeburn  5632:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5633:     my ($cdom,$cnum,$chome);
                   5634:     if (!$cid) {
1.620     albertel 5635: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5636: 	    return 'not_in_class';
                   5637: 	}
1.620     albertel 5638: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5639: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5640:     } else {
                   5641: 	($cdom,$cnum)=split(/_/,$cid);
                   5642:     }
1.620     albertel 5643:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5644:     if (!$chome) {
1.457     raeburn  5645: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5646:     }
1.455     albertel 5647:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5648:     # Make sure the user exists
1.81      www      5649:     my $uhome=&homeserver($uname,$udom);
                   5650:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5651: 	return 'error: no such user';
                   5652:     }
1.297     matthew  5653:     # Get student data if we were not given enough information
                   5654:     if (!defined($first)  || $first  eq '' || 
                   5655:         !defined($last)   || $last   eq '' || 
                   5656:         !defined($uid)    || $uid    eq '' || 
                   5657:         !defined($middle) || $middle eq '' || 
                   5658:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5659:         # They did not supply us with enough data to enroll the student, so
                   5660:         # we need to pick up more information.
1.297     matthew  5661:         my %tmp = &get('environment',
1.294     matthew  5662:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5663:                        ,$udom,$uname);
                   5664: 
1.800     albertel 5665:         #foreach my $key (keys(%tmp)) {
                   5666:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5667:         #}
1.294     matthew  5668:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5669:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5670:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5671:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5672:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5673:     }
1.556     albertel 5674:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5675:     my $reply=cput('classlist',
                   5676: 		   {"$uname:$udom" => 
1.515     raeburn  5677: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5678: 		   $cdom,$cnum);
1.81      www      5679:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5680: 	return 'error: '.$reply;
1.652     albertel 5681:     } else {
                   5682: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5683:     }
1.297     matthew  5684:     # Add student role to user
1.83      www      5685:     my $uurl='/'.$cid;
1.81      www      5686:     $uurl=~s/\_/\//g;
                   5687:     if ($usec) {
                   5688: 	$uurl.='/'.$usec;
                   5689:     }
1.957   ! raeburn  5690:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5691: }
                   5692: 
1.556     albertel 5693: sub format_name {
                   5694:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5695:     my $name;
                   5696:     if ($first ne 'lastname') {
                   5697: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5698:     } else {
                   5699: 	if ($lastname=~/\S/) {
                   5700: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5701: 	    $name=~s/\s+,/,/;
                   5702: 	} else {
                   5703: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5704: 	}
                   5705:     }
                   5706:     $name=~s/^\s+//;
                   5707:     $name=~s/\s+$//;
                   5708:     $name=~s/\s+/ /g;
                   5709:     return $name;
                   5710: }
                   5711: 
1.84      www      5712: # ------------------------------------------------- Write to course preferences
                   5713: 
                   5714: sub writecoursepref {
                   5715:     my ($courseid,%prefs)=@_;
                   5716:     $courseid=~s/^\///;
                   5717:     $courseid=~s/\_/\//g;
                   5718:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5719:     my $chome=homeserver($cnum,$cdomain);
                   5720:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5721: 	return 'error: no such course';
                   5722:     }
                   5723:     my $cstring='';
1.800     albertel 5724:     foreach my $pref (keys(%prefs)) {
                   5725: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5726:     }
1.84      www      5727:     $cstring=~s/\&$//;
                   5728:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5729: }
                   5730: 
                   5731: # ---------------------------------------------------------- Make/modify course
                   5732: 
                   5733: sub createcourse {
1.741     raeburn  5734:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5735:         $course_owner,$crstype)=@_;
1.84      www      5736:     $url=&declutter($url);
                   5737:     my $cid='';
1.264     matthew  5738:     unless (&allowed('ccc',$udom)) {
1.84      www      5739:         return 'refused';
                   5740:     }
                   5741: # ------------------------------------------------------------------- Create ID
1.674     www      5742:    my $uname=int(1+rand(9)).
                   5743:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5744:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5745:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5746: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5747:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5748:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5749:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5750:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5751:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5752:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5753:            return 'error: unable to generate unique course-ID';
                   5754:        } 
                   5755:    }
1.264     matthew  5756: # ------------------------------------------------ Check supplied server name
1.620     albertel 5757:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5758:     if (! &is_library($course_server)) {
1.264     matthew  5759:         return 'error:bad server name '.$course_server;
                   5760:     }
1.84      www      5761: # ------------------------------------------------------------- Make the course
                   5762:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5763:                       $course_server);
1.84      www      5764:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5765:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5766:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5767: 	return 'error: no such course';
                   5768:     }
1.271     www      5769: # ----------------------------------------------------------------- Course made
1.516     raeburn  5770: # log existence
1.918     raeburn  5771:     my $newcourse = {
                   5772:                     $udom.'_'.$uname => {
1.921     raeburn  5773:                                      description => $description,
                   5774:                                      inst_code   => $inst_code,
                   5775:                                      owner       => $course_owner,
                   5776:                                      type        => $crstype,
1.918     raeburn  5777:                                                 },
                   5778:                     };
1.921     raeburn  5779:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5780: # set toplevel url
1.271     www      5781:     my $topurl=$url;
                   5782:     unless ($nonstandard) {
                   5783: # ------------------------------------------ For standard courses, make top url
                   5784:         my $mapurl=&clutter($url);
1.278     www      5785:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5786:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5787: <map>
                   5788: <resource id="1" type="start"></resource>
                   5789: <resource id="2" src="$mapurl"></resource>
                   5790: <resource id="3" type="finish"></resource>
                   5791: <link index="1" from="1" to="2"></link>
                   5792: <link index="2" from="2" to="3"></link>
                   5793: </map>
                   5794: ENDINITMAP
                   5795:         $topurl=&declutter(
1.638     albertel 5796:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5797:                           );
                   5798:     }
                   5799: # ----------------------------------------------------------- Write preferences
1.84      www      5800:     &writecoursepref($udom.'_'.$uname,
                   5801:                      ('description' => $description,
1.271     www      5802:                       'url'         => $topurl));
1.84      www      5803:     return '/'.$udom.'/'.$uname;
                   5804: }
                   5805: 
1.813     albertel 5806: sub is_course {
                   5807:     my ($cdom,$cnum) = @_;
                   5808:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5809: 				undef,'.');
1.813     albertel 5810:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5811:         return 1;
                   5812:     }
                   5813:     return 0;
                   5814: }
                   5815: 
1.21      www      5816: # ---------------------------------------------------------- Assign Custom Role
                   5817: 
                   5818: sub assigncustomrole {
1.957   ! raeburn  5819:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5820:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957   ! raeburn  5821:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      5822: }
                   5823: 
                   5824: # ----------------------------------------------------------------- Revoke Role
                   5825: 
                   5826: sub revokerole {
1.957   ! raeburn  5827:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5828:     my $now=time;
1.957   ! raeburn  5829:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag,$selfenroll,$context);
1.21      www      5830: }
                   5831: 
                   5832: # ---------------------------------------------------------- Revoke Custom Role
                   5833: 
                   5834: sub revokecustomrole {
1.957   ! raeburn  5835:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5836:     my $now=time;
1.357     www      5837:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957   ! raeburn  5838:            $deleteflag,$selfenroll,$context);
1.17      www      5839: }
                   5840: 
1.533     banghart 5841: # ------------------------------------------------------------ Disk usage
1.535     albertel 5842: sub diskusage {
1.955     raeburn  5843:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   5844:     $directorypath =~ s/\/$//;
                   5845:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   5846:                        .&escape($getpropath).':'.&escape($uname).':'
                   5847:                        .&escape($udom),homeserver($uname,$udom));
                   5848:     if ($listing eq 'unknown_cmd') {
                   5849:         if ($getpropath) {
                   5850:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   5851:         }
                   5852:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   5853:     }
1.514     albertel 5854:     return $listing;
1.512     banghart 5855: }
                   5856: 
1.566     banghart 5857: sub is_locked {
                   5858:     my ($file_name, $domain, $user) = @_;
                   5859:     my @check;
                   5860:     my $is_locked;
                   5861:     push @check, $file_name;
1.613     albertel 5862:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5863: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5864:     my ($tmp)=keys(%locked);
                   5865:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5866:     
1.566     banghart 5867:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5868:         $is_locked = 'false';
                   5869:         foreach my $entry (@{$locked{$file_name}}) {
                   5870:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5871:                $is_locked = 'true';
                   5872:                last;
1.745     raeburn  5873:            }
                   5874:        }
1.566     banghart 5875:     } else {
                   5876:         $is_locked = 'false';
                   5877:     }
                   5878: }
                   5879: 
1.759     albertel 5880: sub declutter_portfile {
                   5881:     my ($file) = @_;
1.833     albertel 5882:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5883:     return $file;
                   5884: }
                   5885: 
1.559     banghart 5886: # ------------------------------------------------------------- Mark as Read Only
                   5887: 
                   5888: sub mark_as_readonly {
                   5889:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5890:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5891:     my ($tmp)=keys(%current_permissions);
                   5892:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5893:     foreach my $file (@{$files}) {
1.759     albertel 5894: 	$file = &declutter_portfile($file);
1.561     banghart 5895:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5896:     }
1.613     albertel 5897:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5898:     return;
                   5899: }
                   5900: 
1.572     banghart 5901: # ------------------------------------------------------------Save Selected Files
                   5902: 
                   5903: sub save_selected_files {
                   5904:     my ($user, $path, @files) = @_;
                   5905:     my $filename = $user."savedfiles";
1.573     banghart 5906:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5907:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5908:     foreach my $file (@files) {
1.620     albertel 5909:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5910:     }
                   5911:     foreach my $file (@other_files) {
1.574     banghart 5912:         print (OUT $file."\n");
1.572     banghart 5913:     }
1.574     banghart 5914:     close (OUT);
1.572     banghart 5915:     return 'ok';
                   5916: }
                   5917: 
1.574     banghart 5918: sub clear_selected_files {
                   5919:     my ($user) = @_;
                   5920:     my $filename = $user."savedfiles";
                   5921:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5922:     print (OUT undef);
                   5923:     close (OUT);
                   5924:     return ("ok");    
                   5925: }
                   5926: 
1.572     banghart 5927: sub files_in_path {
                   5928:     my ($user, $path) = @_;
                   5929:     my $filename = $user."savedfiles";
                   5930:     my %return_files;
1.574     banghart 5931:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5932:     while (my $line_in = <IN>) {
1.574     banghart 5933:         chomp ($line_in);
                   5934:         my @paths_and_file = split (m!/!, $line_in);
                   5935:         my $file_part = pop (@paths_and_file);
                   5936:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5937:         $path_part.='/';
                   5938:         my $path_and_file = $path_part.$file_part;
                   5939:         if ($path_part eq $path) {
                   5940:             $return_files{$file_part}= 'selected';
                   5941:         }
                   5942:     }
1.574     banghart 5943:     close (IN);
                   5944:     return (\%return_files);
1.572     banghart 5945: }
                   5946: 
                   5947: # called in portfolio select mode, to show files selected NOT in current directory
                   5948: sub files_not_in_path {
                   5949:     my ($user, $path) = @_;
                   5950:     my $filename = $user."savedfiles";
                   5951:     my @return_files;
                   5952:     my $path_part;
1.800     albertel 5953:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5954:     while (my $line = <IN>) {
1.572     banghart 5955:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5956:         my @paths_and_file = split(m|/|, $line);
                   5957:         my $file_part = pop(@paths_and_file);
                   5958:         chomp($file_part);
                   5959:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5960:         $path_part .= '/';
                   5961:         my $path_and_file = $path_part.$file_part;
                   5962:         if ($path_part ne $path) {
1.800     albertel 5963:             push(@return_files, ($path_and_file));
1.572     banghart 5964:         }
                   5965:     }
1.800     albertel 5966:     close(OUT);
1.574     banghart 5967:     return (@return_files);
1.572     banghart 5968: }
                   5969: 
1.745     raeburn  5970: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5971: 
1.745     raeburn  5972: sub get_portfile_permissions {
                   5973:     my ($domain,$user) = @_;
1.613     albertel 5974:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5975:     my ($tmp)=keys(%current_permissions);
                   5976:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5977:     return \%current_permissions;
                   5978: }
                   5979: 
                   5980: #---------------------------------------------Get portfolio file access controls
                   5981: 
1.749     raeburn  5982: sub get_access_controls {
1.745     raeburn  5983:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5984:     my %access;
                   5985:     my $real_file = $file;
                   5986:     $file =~ s/\.meta$//;
1.745     raeburn  5987:     if (defined($file)) {
1.749     raeburn  5988:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5989:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5990:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5991:             }
                   5992:         }
1.745     raeburn  5993:     } else {
1.749     raeburn  5994:         foreach my $key (keys(%{$current_permissions})) {
                   5995:             if ($key =~ /\0accesscontrol$/) {
                   5996:                 if (defined($group)) {
                   5997:                     if ($key !~ m-^\Q$group\E/-) {
                   5998:                         next;
                   5999:                     }
                   6000:                 }
                   6001:                 my ($fullpath) = split(/\0/,$key);
                   6002:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6003:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6004:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6005:                     }
                   6006:                 }
                   6007:             }
                   6008:         }
                   6009:     }
                   6010:     return %access;
                   6011: }
                   6012: 
                   6013: sub modify_access_controls {
                   6014:     my ($file_name,$changes,$domain,$user)=@_;
                   6015:     my ($outcome,$deloutcome);
                   6016:     my %store_permissions;
                   6017:     my %new_values;
                   6018:     my %new_control;
                   6019:     my %translation;
                   6020:     my @deletions = ();
                   6021:     my $now = time;
                   6022:     if (exists($$changes{'activate'})) {
                   6023:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6024:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6025:             my $numnew = scalar(@newitems);
                   6026:             for (my $i=0; $i<$numnew; $i++) {
                   6027:                 my $newkey = $newitems[$i];
                   6028:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6029:                 if ($newkey =~ /^\d+:/) { 
                   6030:                     $newkey =~ s/^(\d+)/$newid/;
                   6031:                     $translation{$1} = $newid;
                   6032:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6033:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6034:                     $translation{$1} = $newid;
                   6035:                 }
1.749     raeburn  6036:                 $new_values{$file_name."\0".$newkey} = 
                   6037:                                           $$changes{'activate'}{$newitems[$i]};
                   6038:                 $new_control{$newkey} = $now;
                   6039:             }
                   6040:         }
                   6041:     }
                   6042:     my %todelete;
                   6043:     my %changed_items;
                   6044:     foreach my $action ('delete','update') {
                   6045:         if (exists($$changes{$action})) {
                   6046:             if (ref($$changes{$action}) eq 'HASH') {
                   6047:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6048:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6049:                     if ($action eq 'delete') { 
                   6050:                         $todelete{$itemnum} = 1;
                   6051:                     } else {
                   6052:                         $changed_items{$itemnum} = $key;
                   6053:                     }
                   6054:                 }
1.745     raeburn  6055:             }
                   6056:         }
1.749     raeburn  6057:     }
                   6058:     # get lock on access controls for file.
                   6059:     my $lockhash = {
                   6060:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6061:                                                        ':'.$env{'user.domain'},
                   6062:                    }; 
                   6063:     my $tries = 0;
                   6064:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6065:    
                   6066:     while (($gotlock ne 'ok') && $tries <3) {
                   6067:         $tries ++;
                   6068:         sleep 1;
                   6069:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6070:     }
                   6071:     if ($gotlock eq 'ok') {
                   6072:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6073:         my ($tmp)=keys(%curr_permissions);
                   6074:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6075:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6076:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6077:             if (ref($curr_controls) eq 'HASH') {
                   6078:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6079:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6080:                     if (defined($todelete{$itemnum})) {
                   6081:                         push(@deletions,$file_name."\0".$control_item);
                   6082:                     } else {
                   6083:                         if (defined($changed_items{$itemnum})) {
                   6084:                             $new_control{$changed_items{$itemnum}} = $now;
                   6085:                             push(@deletions,$file_name."\0".$control_item);
                   6086:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6087:                         } else {
                   6088:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6089:                         }
                   6090:                     }
1.745     raeburn  6091:                 }
                   6092:             }
                   6093:         }
1.749     raeburn  6094:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6095:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6096:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6097:         #  remove lock
                   6098:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6099:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6100:         my ($file,$group);
                   6101:         if (&is_course($domain,$user)) {
                   6102:             ($group,$file) = split(/\//,$file_name,2);
                   6103:         } else {
                   6104:             $file = $file_name;
                   6105:         }
                   6106:         my $sqlresult =
                   6107:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6108:                                     $group);
1.749     raeburn  6109:     } else {
                   6110:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6111:     }
1.749     raeburn  6112:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6113: }
                   6114: 
1.827     raeburn  6115: sub make_public_indefinitely {
                   6116:     my ($requrl) = @_;
                   6117:     my $now = time;
                   6118:     my $action = 'activate';
                   6119:     my $aclnum = 0;
                   6120:     if (&is_portfolio_url($requrl)) {
                   6121:         my (undef,$udom,$unum,$file_name,$group) =
                   6122:             &parse_portfolio_url($requrl);
                   6123:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6124:         my %access_controls = &get_access_controls($current_perms,
                   6125:                                                    $group,$file_name);
                   6126:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6127:             my ($num,$scope,$end,$start) = 
                   6128:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6129:             if ($scope eq 'public') {
                   6130:                 if ($start <= $now && $end == 0) {
                   6131:                     $action = 'none';
                   6132:                 } else {
                   6133:                     $action = 'update';
                   6134:                     $aclnum = $num;
                   6135:                 }
                   6136:                 last;
                   6137:             }
                   6138:         }
                   6139:         if ($action eq 'none') {
                   6140:              return 'ok';
                   6141:         } else {
                   6142:             my %changes;
                   6143:             my $newend = 0;
                   6144:             my $newstart = $now;
                   6145:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6146:             $changes{$action}{$newkey} = {
                   6147:                 type => 'public',
                   6148:                 time => {
                   6149:                     start => $newstart,
                   6150:                     end   => $newend,
                   6151:                 },
                   6152:             };
                   6153:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6154:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6155:             return $outcome;
                   6156:         }
                   6157:     } else {
                   6158:         return 'invalid';
                   6159:     }
                   6160: }
                   6161: 
1.745     raeburn  6162: #------------------------------------------------------Get Marked as Read Only
                   6163: 
                   6164: sub get_marked_as_readonly {
                   6165:     my ($domain,$user,$what,$group) = @_;
                   6166:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6167:     my @readonly_files;
1.629     banghart 6168:     my $cmp1=$what;
                   6169:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6170:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6171:         if (defined($group)) {
                   6172:             if ($file_name !~ m-^\Q$group\E/-) {
                   6173:                 next;
                   6174:             }
                   6175:         }
1.561     banghart 6176:         if (ref($value) eq "ARRAY"){
                   6177:             foreach my $stored_what (@{$value}) {
1.629     banghart 6178:                 my $cmp2=$stored_what;
1.759     albertel 6179:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6180:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6181:                 }
1.629     banghart 6182:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6183:                     push(@readonly_files, $file_name);
1.745     raeburn  6184:                     last;
1.563     banghart 6185:                 } elsif (!defined($what)) {
                   6186:                     push(@readonly_files, $file_name);
1.745     raeburn  6187:                     last;
1.561     banghart 6188:                 }
                   6189:             }
1.745     raeburn  6190:         }
1.561     banghart 6191:     }
                   6192:     return @readonly_files;
                   6193: }
1.577     banghart 6194: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6195: 
1.577     banghart 6196: sub get_marked_as_readonly_hash {
1.745     raeburn  6197:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6198:     my %readonly_files;
1.745     raeburn  6199:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6200:         if (defined($group)) {
                   6201:             if ($file_name !~ m-^\Q$group\E/-) {
                   6202:                 next;
                   6203:             }
                   6204:         }
1.577     banghart 6205:         if (ref($value) eq "ARRAY"){
                   6206:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6207:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6208:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6209:                         if ($lock_descriptor eq 'graded') {
                   6210:                             $readonly_files{$file_name} = 'graded';
                   6211:                         } elsif ($lock_descriptor eq 'handback') {
                   6212:                             $readonly_files{$file_name} = 'handback';
                   6213:                         } else {
                   6214:                             if (!exists($readonly_files{$file_name})) {
                   6215:                                 $readonly_files{$file_name} = 'locked';
                   6216:                             }
                   6217:                         }
1.745     raeburn  6218:                     }
1.750     banghart 6219:                 } 
1.577     banghart 6220:             }
                   6221:         } 
                   6222:     }
                   6223:     return %readonly_files;
                   6224: }
1.559     banghart 6225: # ------------------------------------------------------------ Unmark as Read Only
                   6226: 
                   6227: sub unmark_as_readonly {
1.629     banghart 6228:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6229:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6230:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6231:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6232:     my $symb_crs = $what;
                   6233:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6234:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6235:     my ($tmp)=keys(%current_permissions);
                   6236:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6237:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6238:     foreach my $file (@readonly_files) {
1.759     albertel 6239: 	my $clean_file = &declutter_portfile($file);
                   6240: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6241: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6242:         my @new_locks;
                   6243:         my @del_keys;
                   6244:         if (ref($current_locks) eq "ARRAY"){
                   6245:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6246:                 my $compare=$locker;
1.749     raeburn  6247:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6248:                     $compare=join('',@{$locker});
1.746     raeburn  6249:                     if ($compare ne $symb_crs) {
                   6250:                         push(@new_locks, $locker);
                   6251:                     }
1.563     banghart 6252:                 }
                   6253:             }
1.650     albertel 6254:             if (scalar(@new_locks) > 0) {
1.563     banghart 6255:                 $current_permissions{$file} = \@new_locks;
                   6256:             } else {
                   6257:                 push(@del_keys, $file);
1.613     albertel 6258:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6259:                 delete($current_permissions{$file});
1.563     banghart 6260:             }
                   6261:         }
1.561     banghart 6262:     }
1.613     albertel 6263:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6264:     return;
                   6265: }
1.512     banghart 6266: 
1.17      www      6267: # ------------------------------------------------------------ Directory lister
                   6268: 
                   6269: sub dirlist {
1.955     raeburn  6270:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6271:     $uri=~s/^\///;
                   6272:     $uri=~s/\/$//;
1.253     stredwic 6273:     my ($udom, $uname);
1.955     raeburn  6274:     if ($getuserdir) {
1.253     stredwic 6275:         $udom = $userdomain;
                   6276:         $uname = $username;
1.955     raeburn  6277:     } else {
                   6278:         (undef,$udom,$uname)=split(/\//,$uri);
                   6279:         if(defined($userdomain)) {
                   6280:             $udom = $userdomain;
                   6281:         }
                   6282:         if(defined($username)) {
                   6283:             $uname = $username;
                   6284:         }
1.253     stredwic 6285:     }
1.955     raeburn  6286:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6287: 
1.955     raeburn  6288:     $dirRoot = $perlvar{'lonDocRoot'};
                   6289:     if (defined($getpropath)) {
                   6290:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6291:         $dirRoot =~ s/\/$//;
1.955     raeburn  6292:     } elsif (defined($getuserdir)) {
                   6293:         my $subdir=$uname.'__';
                   6294:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6295:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6296:                    ."/$udom/$subdir/$uname";
                   6297:     } elsif (defined($alternateRoot)) {
                   6298:         $dirRoot = $alternateRoot;
1.751     banghart 6299:     }
1.253     stredwic 6300: 
                   6301:     if($udom) {
                   6302:         if($uname) {
1.955     raeburn  6303:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6304:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6305:                               .':'.&escape($uname).':'.&escape($udom),
                   6306:                               &homeserver($uname,$udom));
                   6307:             if ($listing eq 'unknown_cmd') {
                   6308:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6309:                                   &homeserver($uname,$udom));
                   6310:             } else {
                   6311:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6312:             }
1.605     matthew  6313:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6314:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6315: 				  &homeserver($uname,$udom));
1.605     matthew  6316:                 @listing_results = split(/:/,$listing);
                   6317:             } else {
                   6318:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6319:             }
                   6320:             return @listing_results;
1.955     raeburn  6321:         } elsif(!$alternateRoot) {
1.800     albertel 6322:             my %allusers;
1.841     albertel 6323: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6324:  	    foreach my $tryserver (keys(%servers)) {
                   6325:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6326:                                   &escape($udom),$tryserver);
                   6327:                 if ($listing eq 'unknown_cmd') {
                   6328: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6329: 				      $udom, $tryserver);
                   6330:                 } else {
                   6331:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6332:                 }
1.841     albertel 6333: 		if ($listing eq 'unknown_cmd') {
                   6334: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6335: 				      $udom, $tryserver);
                   6336: 		    @listing_results = split(/:/,$listing);
                   6337: 		} else {
                   6338: 		    @listing_results =
                   6339: 			map { &unescape($_); } split(/:/,$listing);
                   6340: 		}
                   6341: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6342: 		    $listing_results[0] ne 'empty'       &&
                   6343: 		    $listing_results[0] ne 'con_lost') {
                   6344: 		    foreach my $line (@listing_results) {
                   6345: 			my ($entry) = split(/&/,$line,2);
                   6346: 			$allusers{$entry} = 1;
                   6347: 		    }
                   6348: 		}
1.253     stredwic 6349:             }
                   6350:             my $alluserstr='';
1.800     albertel 6351:             foreach my $user (sort(keys(%allusers))) {
                   6352:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6353:             }
                   6354:             $alluserstr=~s/:$//;
                   6355:             return split(/:/,$alluserstr);
                   6356:         } else {
1.800     albertel 6357:             return ('missing user name');
1.253     stredwic 6358:         }
1.955     raeburn  6359:     } elsif(!defined($getpropath)) {
1.841     albertel 6360:         my @all_domains = sort(&all_domains());
1.955     raeburn  6361:         foreach my $domain (@all_domains) {
                   6362:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6363:         }
                   6364:         return @all_domains;
                   6365:     } else {
1.800     albertel 6366:         return ('missing domain');
1.275     stredwic 6367:     }
                   6368: }
                   6369: 
                   6370: # --------------------------------------------- GetFileTimestamp
                   6371: # This function utilizes dirlist and returns the date stamp for
                   6372: # when it was last modified.  It will also return an error of -1
                   6373: # if an error occurs
                   6374: 
                   6375: sub GetFileTimestamp {
1.955     raeburn  6376:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6377:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6378:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6379:     my ($fileStat) = 
                   6380:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6381:                                  undef,$getuserdir);
1.275     stredwic 6382:     my @stats = split('&', $fileStat);
                   6383:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6384:         # @stats contains first the filename, then the stat output
                   6385:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6386:     } else {
                   6387:         return -1;
1.253     stredwic 6388:     }
1.26      www      6389: }
                   6390: 
1.712     albertel 6391: sub stat_file {
                   6392:     my ($uri) = @_;
1.787     albertel 6393:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6394: 
1.955     raeburn  6395:     my ($udom,$uname,$file);
1.712     albertel 6396:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6397: 	($udom,$uname,$file) =
1.811     albertel 6398: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6399: 	$file = 'userfiles/'.$file;
                   6400:     }
                   6401:     if ($uri =~ m-^/res/-) {
                   6402: 	($udom,$uname) = 
1.807     albertel 6403: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6404: 	$file = $uri;
                   6405:     }
                   6406: 
                   6407:     if (!$udom || !$uname || !$file) {
                   6408: 	# unable to handle the uri
                   6409: 	return ();
                   6410:     }
1.956     raeburn  6411:     my $getpropath;
                   6412:     if ($file =~ /^userfiles\//) {
                   6413:         $getpropath = 1;
                   6414:     }
1.955     raeburn  6415:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6416:     my @stats = split('&', $result);
1.721     banghart 6417:     
1.712     albertel 6418:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6419: 	shift(@stats); #filename is first
                   6420: 	return @stats;
                   6421:     }
                   6422:     return ();
                   6423: }
                   6424: 
1.26      www      6425: # -------------------------------------------------------- Value of a Condition
                   6426: 
1.713     albertel 6427: # gets the value of a specific preevaluated condition
                   6428: #    stored in the string  $env{user.state.<cid>}
                   6429: # or looks up a condition reference in the bighash and if if hasn't
                   6430: # already been evaluated recurses into docondval to get the value of
                   6431: # the condition, then memoizing it to 
                   6432: #   $env{user.state.<cid>.<condition>}
1.40      www      6433: sub directcondval {
                   6434:     my $number=shift;
1.620     albertel 6435:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6436: 	&Apache::lonuserstate::evalstate();
                   6437:     }
1.713     albertel 6438:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6439: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6440:     } elsif ($number =~ /^_/) {
                   6441: 	my $sub_condition;
                   6442: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6443: 		&GDBM_READER(),0640)) {
                   6444: 	    $sub_condition=$bighash{'conditions'.$number};
                   6445: 	    untie(%bighash);
                   6446: 	}
                   6447: 	my $value = &docondval($sub_condition);
1.949     raeburn  6448: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6449: 	return $value;
                   6450:     }
1.620     albertel 6451:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6452:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6453:     } else {
                   6454:        return 2;
                   6455:     }
                   6456: }
                   6457: 
1.713     albertel 6458: # get the collection of conditions for this resource
1.26      www      6459: sub condval {
                   6460:     my $condidx=shift;
1.54      www      6461:     my $allpathcond='';
1.713     albertel 6462:     foreach my $cond (split(/\|/,$condidx)) {
                   6463: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6464: 	    $allpathcond.=
                   6465: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6466: 	}
1.191     harris41 6467:     }
1.54      www      6468:     $allpathcond=~s/\|$//;
1.713     albertel 6469:     return &docondval($allpathcond);
                   6470: }
                   6471: 
                   6472: #evaluates an expression of conditions
                   6473: sub docondval {
                   6474:     my ($allpathcond) = @_;
                   6475:     my $result=0;
                   6476:     if ($env{'request.course.id'}
                   6477: 	&& defined($allpathcond)) {
                   6478: 	my $operand='|';
                   6479: 	my @stack;
                   6480: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6481: 	    if ($chunk eq '(') {
                   6482: 		push @stack,($operand,$result);
                   6483: 	    } elsif ($chunk eq ')') {
                   6484: 		my $before=pop @stack;
                   6485: 		if (pop @stack eq '&') {
                   6486: 		    $result=$result>$before?$before:$result;
                   6487: 		} else {
                   6488: 		    $result=$result>$before?$result:$before;
                   6489: 		}
                   6490: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6491: 		$operand=$chunk;
                   6492: 	    } else {
                   6493: 		my $new=directcondval($chunk);
                   6494: 		if ($operand eq '&') {
                   6495: 		    $result=$result>$new?$new:$result;
                   6496: 		} else {
                   6497: 		    $result=$result>$new?$result:$new;
                   6498: 		}
                   6499: 	    }
                   6500: 	}
1.26      www      6501:     }
                   6502:     return $result;
1.421     albertel 6503: }
                   6504: 
                   6505: # ---------------------------------------------------- Devalidate courseresdata
                   6506: 
                   6507: sub devalidatecourseresdata {
                   6508:     my ($coursenum,$coursedomain)=@_;
                   6509:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6510:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6511: }
                   6512: 
1.763     www      6513: 
1.200     www      6514: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6515: #
                   6516: #  Parameters:
                   6517: #      $coursenum    - Number of the course.
                   6518: #      $coursedomain - Domain at which the course was created.
                   6519: #  Returns:
                   6520: #     A hash of the course parameters along (I think) with timestamps
                   6521: #     and version info.
1.877     foxr     6522: 
1.624     albertel 6523: sub get_courseresdata {
                   6524:     my ($coursenum,$coursedomain)=@_;
1.200     www      6525:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6526:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6527:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6528:     my %dumpreply;
1.417     albertel 6529:     unless (defined($cached)) {
1.624     albertel 6530: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6531: 	$result=\%dumpreply;
1.251     albertel 6532: 	my ($tmp) = keys(%dumpreply);
                   6533: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6534: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6535: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6536: 	    return $tmp;
1.416     albertel 6537: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6538: 	    $result=undef;
1.599     albertel 6539: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6540: 	}
                   6541:     }
1.624     albertel 6542:     return $result;
                   6543: }
                   6544: 
1.633     albertel 6545: sub devalidateuserresdata {
                   6546:     my ($uname,$udom)=@_;
                   6547:     my $hashid="$udom:$uname";
                   6548:     &devalidate_cache_new('userres',$hashid);
                   6549: }
                   6550: 
1.624     albertel 6551: sub get_userresdata {
                   6552:     my ($uname,$udom)=@_;
                   6553:     #most student don\'t have any data set, check if there is some data
                   6554:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6555: 
                   6556:     my $hashid="$udom:$uname";
                   6557:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6558:     if (!defined($cached)) {
                   6559: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6560: 	$result=\%resourcedata;
                   6561: 	&do_cache_new('userres',$hashid,$result,600);
                   6562:     }
                   6563:     my ($tmp)=keys(%$result);
                   6564:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6565: 	return $result;
                   6566:     }
                   6567:     #error 2 occurs when the .db doesn't exist
                   6568:     if ($tmp!~/error: 2 /) {
1.672     albertel 6569: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6570: 		 " Trying to get resource data for ".
                   6571: 		 $uname." at ".$udom.": ".
                   6572: 		 $tmp."</font>");
                   6573:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6574: 	#&EXT_cache_set($udom,$uname);
                   6575: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6576: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6577:     }
                   6578:     return $tmp;
                   6579: }
1.879     foxr     6580: #----------------------------------------------- resdata - return resource data
                   6581: #  Purpose:
                   6582: #    Return resource data for either users or for a course.
                   6583: #  Parameters:
                   6584: #     $name      - Course/user name.
                   6585: #     $domain    - Name of the domain the user/course is registered on.
                   6586: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6587: #     @which     - Array of names of resources desired.
                   6588: #  Returns:
                   6589: #     The value of the first reasource in @which that is found in the
                   6590: #     resource hash.
                   6591: #  Exceptional Conditions:
                   6592: #     If the $type passed in is not valid (not the string 'course' or 
                   6593: #     'user', an undefined  reference is returned.
                   6594: #     If none of the resources are found, an undef is returned
1.624     albertel 6595: sub resdata {
                   6596:     my ($name,$domain,$type,@which)=@_;
                   6597:     my $result;
                   6598:     if ($type eq 'course') {
                   6599: 	$result=&get_courseresdata($name,$domain);
                   6600:     } elsif ($type eq 'user') {
                   6601: 	$result=&get_userresdata($name,$domain);
                   6602:     }
                   6603:     if (!ref($result)) { return $result; }    
1.251     albertel 6604:     foreach my $item (@which) {
1.927     albertel 6605: 	if (defined($result->{$item->[0]})) {
                   6606: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6607: 	}
1.250     albertel 6608:     }
1.291     albertel 6609:     return undef;
1.200     www      6610: }
                   6611: 
1.379     matthew  6612: #
                   6613: # EXT resource caching routines
                   6614: #
                   6615: 
                   6616: sub clear_EXT_cache_status {
1.383     albertel 6617:     &delenv('cache.EXT.');
1.379     matthew  6618: }
                   6619: 
                   6620: sub EXT_cache_status {
                   6621:     my ($target_domain,$target_user) = @_;
1.383     albertel 6622:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6623:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6624:         # We know already the user has no data
                   6625:         return 1;
                   6626:     } else {
                   6627:         return 0;
                   6628:     }
                   6629: }
                   6630: 
                   6631: sub EXT_cache_set {
                   6632:     my ($target_domain,$target_user) = @_;
1.383     albertel 6633:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6634:     #&appenv({$cachename => time});
1.379     matthew  6635: }
                   6636: 
1.28      www      6637: # --------------------------------------------------------- Value of a Variable
1.58      www      6638: sub EXT {
1.715     albertel 6639: 
1.395     albertel 6640:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6641:     unless ($varname) { return ''; }
1.218     albertel 6642:     #get real user name/domain, courseid and symb
                   6643:     my $courseid;
1.359     albertel 6644:     my $publicuser;
1.427     www      6645:     if ($symbparm) {
                   6646: 	$symbparm=&get_symb_from_alias($symbparm);
                   6647:     }
1.218     albertel 6648:     if (!($uname && $udom)) {
1.790     albertel 6649:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6650:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6651:     } else {
1.620     albertel 6652: 	$courseid=$env{'request.course.id'};
1.218     albertel 6653:     }
1.48      www      6654:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6655:     my $rest;
1.320     albertel 6656:     if (defined($therest[0])) {
1.48      www      6657:        $rest=join('.',@therest);
                   6658:     } else {
                   6659:        $rest='';
                   6660:     }
1.320     albertel 6661: 
1.57      www      6662:     my $qualifierrest=$qualifier;
                   6663:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6664:     my $spacequalifierrest=$space;
                   6665:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6666:     if ($realm eq 'user') {
1.48      www      6667: # --------------------------------------------------------------- user.resource
                   6668: 	if ($space eq 'resource') {
1.651     albertel 6669: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6670: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6671: 		 &&
1.744     albertel 6672: 		 ($symbparm eq &symbread()) ) {	
                   6673: 		# if we are in the middle of processing the resource the
                   6674: 		# get the value we are planning on committing
                   6675:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6676:                     return $Apache::lonhomework::results{$qualifierrest};
                   6677:                 } else {
                   6678:                     return $Apache::lonhomework::history{$qualifierrest};
                   6679:                 }
1.335     albertel 6680: 	    } else {
1.359     albertel 6681: 		my %restored;
1.620     albertel 6682: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6683: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6684: 		} else {
                   6685: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6686: 		}
1.335     albertel 6687: 		return $restored{$qualifierrest};
                   6688: 	    }
1.48      www      6689: # ----------------------------------------------------------------- user.access
                   6690:         } elsif ($space eq 'access') {
1.218     albertel 6691: 	    # FIXME - not supporting calls for a specific user
1.48      www      6692:             return &allowed($qualifier,$rest);
                   6693: # ------------------------------------------ user.preferences, user.environment
                   6694:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6695: 	    if (($uname eq $env{'user.name'}) &&
                   6696: 		($udom eq $env{'user.domain'})) {
                   6697: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6698: 	    } else {
1.359     albertel 6699: 		my %returnhash;
                   6700: 		if (!$publicuser) {
                   6701: 		    %returnhash=&userenvironment($udom,$uname,
                   6702: 						 $qualifierrest);
                   6703: 		}
1.218     albertel 6704: 		return $returnhash{$qualifierrest};
                   6705: 	    }
1.48      www      6706: # ----------------------------------------------------------------- user.course
                   6707:         } elsif ($space eq 'course') {
1.218     albertel 6708: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6709:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6710: # ------------------------------------------------------------------- user.role
                   6711:         } elsif ($space eq 'role') {
1.218     albertel 6712: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6713:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6714:             if ($qualifier eq 'value') {
                   6715: 		return $role;
                   6716:             } elsif ($qualifier eq 'extent') {
                   6717:                 return $where;
                   6718:             }
                   6719: # ----------------------------------------------------------------- user.domain
                   6720:         } elsif ($space eq 'domain') {
1.218     albertel 6721:             return $udom;
1.48      www      6722: # ------------------------------------------------------------------- user.name
                   6723:         } elsif ($space eq 'name') {
1.218     albertel 6724:             return $uname;
1.48      www      6725: # ---------------------------------------------------- Any other user namespace
1.29      www      6726:         } else {
1.359     albertel 6727: 	    my %reply;
                   6728: 	    if (!$publicuser) {
                   6729: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6730: 	    }
                   6731: 	    return $reply{$qualifierrest};
1.48      www      6732:         }
1.236     www      6733:     } elsif ($realm eq 'query') {
                   6734: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6735:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6736: 						[$spacequalifierrest]);
1.620     albertel 6737: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6738:    } elsif ($realm eq 'request') {
1.48      www      6739: # ------------------------------------------------------------- request.browser
                   6740:         if ($space eq 'browser') {
1.430     www      6741: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6742: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6743: 		    return 1;
                   6744: 		} else {
                   6745: 		    return 0;
                   6746: 		}
                   6747: 	    } else {
1.620     albertel 6748: 		return $env{'browser.'.$qualifier};
1.430     www      6749: 	    }
1.57      www      6750: # ------------------------------------------------------------ request.filename
                   6751:         } else {
1.620     albertel 6752:             return $env{'request.'.$spacequalifierrest};
1.29      www      6753:         }
1.28      www      6754:     } elsif ($realm eq 'course') {
1.48      www      6755: # ---------------------------------------------------------- course.description
1.620     albertel 6756:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6757:     } elsif ($realm eq 'resource') {
1.165     www      6758: 
1.620     albertel 6759: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6760: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6761: 	}
1.693     albertel 6762: 
                   6763: 	if ($space eq 'title') {
                   6764: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6765: 	    return &gettitle($symbparm);
                   6766: 	}
                   6767: 	
                   6768: 	if ($space eq 'map') {
                   6769: 	    my ($map) = &decode_symb($symbparm);
                   6770: 	    return &symbread($map);
                   6771: 	}
1.905     albertel 6772: 	if ($space eq 'filename') {
                   6773: 	    if ($symbparm) {
                   6774: 		return &clutter((&decode_symb($symbparm))[2]);
                   6775: 	    }
                   6776: 	    return &hreflocation('',$env{'request.filename'});
                   6777: 	}
1.693     albertel 6778: 
                   6779: 	my ($section, $group, @groups);
1.593     albertel 6780: 	my ($courselevelm,$courselevel);
1.539     albertel 6781: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6782: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6783: 
1.218     albertel 6784: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6785: 
1.60      www      6786: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6787: 	    my $symbp=$symbparm;
1.735     albertel 6788: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6789: 
                   6790: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6791: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6792: 
1.620     albertel 6793: 	    if (($env{'user.name'} eq $uname) &&
                   6794: 		($env{'user.domain'} eq $udom)) {
                   6795: 		$section=$env{'request.course.sec'};
1.733     raeburn  6796:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6797:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6798: 	    } else {
1.539     albertel 6799: 		if (! defined($usection)) {
1.551     albertel 6800: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6801: 		} else {
                   6802: 		    $section = $usection;
                   6803: 		}
1.733     raeburn  6804:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6805: 	    }
                   6806: 
                   6807: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6808: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6809: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6810: 
1.593     albertel 6811: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6812: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6813: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6814: 
1.60      www      6815: # ----------------------------------------------------------- first, check user
1.624     albertel 6816: 
                   6817: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6818: 				       ([$courselevelr,'resource'],
                   6819: 					[$courselevelm,'map'     ],
                   6820: 					[$courselevel, 'course'  ]));
1.931     albertel 6821: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6822: 
1.594     albertel 6823: # ------------------------------------------------ second, check some of course
1.684     raeburn  6824:             my $coursereply;
1.691     raeburn  6825:             if (@groups > 0) {
                   6826:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6827:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6828:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6829:             }
1.96      www      6830: 
1.684     raeburn  6831: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6832: 				  $env{'course.'.$courseid.'.domain'},
                   6833: 				  'course',
                   6834: 				  ([$seclevelr,   'resource'],
                   6835: 				   [$seclevelm,   'map'     ],
                   6836: 				   [$seclevel,    'course'  ],
                   6837: 				   [$courselevelr,'resource']));
                   6838: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6839: 
1.60      www      6840: # ------------------------------------------------------ third, check map parms
1.218     albertel 6841: 	    my %parmhash=();
                   6842: 	    my $thisparm='';
                   6843: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6844: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6845: 		    &GDBM_READER(),0640)) {
1.218     albertel 6846: 		$thisparm=$parmhash{$symbparm};
                   6847: 		untie(%parmhash);
                   6848: 	    }
1.927     albertel 6849: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6850: 	}
1.594     albertel 6851: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6852: 
1.218     albertel 6853: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6854: 	my $filename;
                   6855: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6856: 	if ($symbparm) {
1.409     www      6857: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6858: 	} else {
1.620     albertel 6859: 	    $filename=$env{'request.filename'};
1.282     albertel 6860: 	}
                   6861: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6862: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6863: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6864: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6865: 
1.927     albertel 6866: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6867: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6868: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6869: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6870: 				     $env{'course.'.$courseid.'.domain'},
                   6871: 				     'course',
1.927     albertel 6872: 				     ([$courselevelm,'map'   ],
                   6873: 				      [$courselevel, 'course']));
                   6874: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6875: 	}
1.145     www      6876: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6877: 	unless ($space eq '0') {
1.336     albertel 6878: 	    my @parts=split(/_/,$space);
                   6879: 	    my $id=pop(@parts);
                   6880: 	    my $part=join('_',@parts);
                   6881: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6882: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6883: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6884: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6885: 	}
1.395     albertel 6886: 	if ($recurse) { return undef; }
                   6887: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6888: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6889: # ---------------------------------------------------- Any other user namespace
                   6890:     } elsif ($realm eq 'environment') {
                   6891: # ----------------------------------------------------------------- environment
1.620     albertel 6892: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6893: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6894: 	} else {
1.770     albertel 6895: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6896: 		return '';
                   6897: 	    }
1.219     albertel 6898: 	    my %returnhash=&userenvironment($udom,$uname,
                   6899: 					    $spacequalifierrest);
                   6900: 	    return $returnhash{$spacequalifierrest};
                   6901: 	}
1.28      www      6902:     } elsif ($realm eq 'system') {
1.48      www      6903: # ----------------------------------------------------------------- system.time
                   6904: 	if ($space eq 'time') {
                   6905: 	    return time;
                   6906:         }
1.696     albertel 6907:     } elsif ($realm eq 'server') {
                   6908: # ----------------------------------------------------------------- system.time
                   6909: 	if ($space eq 'name') {
                   6910: 	    return $ENV{'SERVER_NAME'};
                   6911:         }
1.28      www      6912:     }
1.48      www      6913:     return '';
1.61      www      6914: }
                   6915: 
1.927     albertel 6916: sub get_reply {
                   6917:     my ($reply_value) = @_;
1.940     raeburn  6918:     if (ref($reply_value) eq 'ARRAY') {
                   6919:         if (wantarray) {
                   6920: 	    return @$reply_value;
                   6921:         }
                   6922:         return $reply_value->[0];
                   6923:     } else {
                   6924:         return $reply_value;
1.927     albertel 6925:     }
                   6926: }
                   6927: 
1.691     raeburn  6928: sub check_group_parms {
                   6929:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6930:     my @groupitems = ();
                   6931:     my $resultitem;
1.927     albertel 6932:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6933:     foreach my $group (@{$groups}) {
                   6934:         foreach my $level (@levels) {
1.927     albertel 6935:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6936:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6937:         }
                   6938:     }
                   6939:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6940:                             $env{'course.'.$courseid.'.domain'},
                   6941:                                      'course',@groupitems);
                   6942:     return $coursereply;
                   6943: }
                   6944: 
                   6945: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6946:     my ($courseid,@groups) = @_;
                   6947:     @groups = sort(@groups);
1.691     raeburn  6948:     return @groups;
                   6949: }
                   6950: 
1.395     albertel 6951: sub packages_tab_default {
                   6952:     my ($uri,$varname)=@_;
                   6953:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6954: 
                   6955:     my (@extension,@specifics,$do_default);
                   6956:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6957: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6958: 	if ($pack_type eq 'default') {
                   6959: 	    $do_default=1;
                   6960: 	} elsif ($pack_type eq 'extension') {
                   6961: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6962: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6963: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6964: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6965: 	}
                   6966:     }
                   6967:     # first look for a package that matches the requested part id
                   6968:     foreach my $package (@specifics) {
                   6969: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6970: 	next if ($pack_part ne $part);
                   6971: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6972: 	    return $packagetab{"$pack_type&$name&default"};
                   6973: 	}
                   6974:     }
                   6975:     # look for any possible matching non extension_ package
                   6976:     foreach my $package (@specifics) {
                   6977: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6978: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6979: 	    return $packagetab{"$pack_type&$name&default"};
                   6980: 	}
1.585     albertel 6981: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6982: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6983: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6984: 	}
                   6985:     }
1.738     albertel 6986:     # look for any posible extension_ match
                   6987:     foreach my $package (@extension) {
                   6988: 	my ($package,$pack_type)=@{$package};
                   6989: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6990: 	    return $packagetab{"$pack_type&$name&default"};
                   6991: 	}
                   6992: 	if (defined($packagetab{$package."&$name&default"})) {
                   6993: 	    return $packagetab{$package."&$name&default"};
                   6994: 	}
                   6995:     }
                   6996:     # look for a global default setting
                   6997:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6998: 	return $packagetab{"default&$name&default"};
                   6999:     }
1.395     albertel 7000:     return undef;
                   7001: }
                   7002: 
1.334     albertel 7003: sub add_prefix_and_part {
                   7004:     my ($prefix,$part)=@_;
                   7005:     my $keyroot;
                   7006:     if (defined($prefix) && $prefix !~ /^__/) {
                   7007: 	# prefix that has a part already
                   7008: 	$keyroot=$prefix;
                   7009:     } elsif (defined($prefix)) {
                   7010: 	# prefix that is missing a part
                   7011: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7012:     } else {
                   7013: 	# no prefix at all
                   7014: 	if (defined($part)) { $keyroot='_'.$part; }
                   7015:     }
                   7016:     return $keyroot;
                   7017: }
                   7018: 
1.71      www      7019: # ---------------------------------------------------------------- Get metadata
                   7020: 
1.599     albertel 7021: my %metaentry;
1.71      www      7022: sub metadata {
1.176     www      7023:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7024:     $uri=&declutter($uri);
1.288     albertel 7025:     # if it is a non metadata possible uri return quickly
1.529     albertel 7026:     if (($uri eq '') || 
                   7027: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7028: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7029:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7030: 	return undef;
                   7031:     }
                   7032:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7033: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7034: 	return undef;
1.288     albertel 7035:     }
1.73      www      7036:     my $filename=$uri;
                   7037:     $uri=~s/\.meta$//;
1.172     www      7038: #
                   7039: # Is the metadata already cached?
1.177     www      7040: # Look at timestamp of caching
1.172     www      7041: # Everything is cached by the main uri, libraries are never directly cached
                   7042: #
1.428     albertel 7043:     if (!defined($liburi)) {
1.599     albertel 7044: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7045: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7046:     }
                   7047:     {
1.172     www      7048: #
                   7049: # Is this a recursive call for a library?
                   7050: #
1.599     albertel 7051: #	if (! exists($metacache{$uri})) {
                   7052: #	    $metacache{$uri}={};
                   7053: #	}
1.924     albertel 7054: 	my $cachetime = 60*60;
1.171     www      7055:         if ($liburi) {
                   7056: 	    $liburi=&declutter($liburi);
                   7057:             $filename=$liburi;
1.401     bowersj2 7058:         } else {
1.599     albertel 7059: 	    &devalidate_cache_new('meta',$uri);
                   7060: 	    undef(%metaentry);
1.401     bowersj2 7061: 	}
1.140     www      7062:         my %metathesekeys=();
1.73      www      7063:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7064: 	my $metastring;
1.924     albertel 7065: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7066: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7067: 	    $metastring = 
1.929     albertel 7068: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7069: 					  ('grade_target' => 'meta'));
                   7070: 	    $cachetime = 1; # only want this cached in the child not long term
                   7071: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7072: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7073: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7074: 	    $metastring=&getfile($file);
1.489     albertel 7075: 	}
1.208     albertel 7076:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7077:         my $token;
1.140     www      7078:         undef %metathesekeys;
1.71      www      7079:         while ($token=$parser->get_token) {
1.339     albertel 7080: 	    if ($token->[0] eq 'S') {
                   7081: 		if (defined($token->[2]->{'package'})) {
1.172     www      7082: #
                   7083: # This is a package - get package info
                   7084: #
1.339     albertel 7085: 		    my $package=$token->[2]->{'package'};
                   7086: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7087: 		    if (defined($token->[2]->{'id'})) { 
                   7088: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7089: 		    }
1.599     albertel 7090: 		    if ($metaentry{':packages'}) {
                   7091: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7092: 		    } else {
1.599     albertel 7093: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7094: 		    }
1.736     albertel 7095: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7096: 			my $part=$keyroot;
                   7097: 			$part=~s/^\_//;
1.736     albertel 7098: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7099: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7100: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7101: 			    # ignore package.tab specified default values
                   7102:                             # here &package_tab_default() will fetch those
                   7103: 			    if ($subp eq 'default') { next; }
1.736     albertel 7104: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7105: 			    my $unikey;
                   7106: 			    if ($pack =~ /_0$/) {
                   7107: 				$unikey='parameter_0_'.$name;
                   7108: 				$part=0;
                   7109: 			    } else {
                   7110: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7111: 			    }
1.339     albertel 7112: 			    if ($subp eq 'display') {
                   7113: 				$value.=' [Part: '.$part.']';
                   7114: 			    }
1.599     albertel 7115: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7116: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7117: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7118: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7119: 			    }
1.599     albertel 7120: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7121: 				$metaentry{':'.$unikey}=
                   7122: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7123: 			    }
1.339     albertel 7124: 			}
                   7125: 		    }
                   7126: 		} else {
1.172     www      7127: #
                   7128: # This is not a package - some other kind of start tag
1.339     albertel 7129: #
                   7130: 		    my $entry=$token->[1];
                   7131: 		    my $unikey;
                   7132: 		    if ($entry eq 'import') {
                   7133: 			$unikey='';
                   7134: 		    } else {
                   7135: 			$unikey=$entry;
                   7136: 		    }
                   7137: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7138: 
                   7139: 		    if (defined($token->[2]->{'id'})) { 
                   7140: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7141: 		    }
1.175     www      7142: 
1.339     albertel 7143: 		    if ($entry eq 'import') {
1.175     www      7144: #
                   7145: # Importing a library here
1.339     albertel 7146: #
                   7147: 			if ($depthcount<20) {
                   7148: 			    my $location=$parser->get_text('/import');
                   7149: 			    my $dir=$filename;
                   7150: 			    $dir=~s|[^/]*$||;
                   7151: 			    $location=&filelocation($dir,$location);
1.736     albertel 7152: 			    my $metadata = 
                   7153: 				&metadata($uri,'keys', $location,$unikey,
                   7154: 					  $depthcount+1);
                   7155: 			    foreach my $meta (split(',',$metadata)) {
                   7156: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7157: 				$metathesekeys{$meta}=1;
1.339     albertel 7158: 			    }
                   7159: 			}
                   7160: 		    } else { 
                   7161: 			
                   7162: 			if (defined($token->[2]->{'name'})) { 
                   7163: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7164: 			}
                   7165: 			$metathesekeys{$unikey}=1;
1.736     albertel 7166: 			foreach my $param (@{$token->[3]}) {
                   7167: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7168: 				$token->[2]->{$param};
1.339     albertel 7169: 			}
                   7170: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7171: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7172: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7173: 		 # only ws inside the tag, and not in default, so use default
                   7174: 		 # as value
1.599     albertel 7175: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7176: 			} elsif ( $internaltext =~ /\S/ ) {
                   7177: 		  # something interesting inside the tag
                   7178: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7179: 			} else {
1.908     albertel 7180: 		  # no interesting values, don't set a default
1.339     albertel 7181: 			}
1.172     www      7182: # end of not-a-package not-a-library import
1.339     albertel 7183: 		    }
1.172     www      7184: # end of not-a-package start tag
1.339     albertel 7185: 		}
1.172     www      7186: # the next is the end of "start tag"
1.339     albertel 7187: 	    }
                   7188: 	}
1.483     albertel 7189: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7190: 	$extension = lc($extension);
                   7191: 	if ($extension eq 'htm') { $extension='html'; }
                   7192: 
1.737     albertel 7193: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7194: 	    #no specific packages #how's our extension
                   7195: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7196: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7197: 					 \%metathesekeys);
                   7198: 	}
1.883     albertel 7199: 
                   7200: 	if (!exists($metaentry{':packages'})
                   7201: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7202: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7203: 		#no specific packages well let's get default then
                   7204: 		if ($key!~/^default&/) { next; }
1.488     albertel 7205: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7206: 					     \%metathesekeys);
                   7207: 	    }
                   7208: 	}
1.338     www      7209: # are there custom rights to evaluate
1.599     albertel 7210: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7211: 
1.338     www      7212:     #
                   7213:     # Importing a rights file here
1.339     albertel 7214:     #
                   7215: 	    unless ($depthcount) {
1.599     albertel 7216: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7217: 		my $dir=$filename;
                   7218: 		$dir=~s|[^/]*$||;
                   7219: 		$location=&filelocation($dir,$location);
1.736     albertel 7220: 		my $rights_metadata =
                   7221: 		    &metadata($uri,'keys',$location,'_rights',
                   7222: 			      $depthcount+1);
                   7223: 		foreach my $rights (split(',',$rights_metadata)) {
                   7224: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7225: 		    $metathesekeys{$rights}=1;
1.339     albertel 7226: 		}
                   7227: 	    }
                   7228: 	}
1.737     albertel 7229: 	# uniqifiy package listing
                   7230: 	my %seen;
                   7231: 	my @uniq_packages =
                   7232: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7233: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7234: 
                   7235: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7236: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7237: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7238: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7239: # this is the end of "was not already recently cached
1.71      www      7240:     }
1.599     albertel 7241:     return $metaentry{':'.$what};
1.261     albertel 7242: }
                   7243: 
1.488     albertel 7244: sub metadata_create_package_def {
1.483     albertel 7245:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7246:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7247:     if ($subp eq 'default') { next; }
                   7248:     
1.599     albertel 7249:     if (defined($metaentry{':packages'})) {
                   7250: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7251:     } else {
1.599     albertel 7252: 	$metaentry{':packages'}=$package;
1.483     albertel 7253:     }
                   7254:     my $value=$packagetab{$key};
                   7255:     my $unikey;
                   7256:     $unikey='parameter_0_'.$name;
1.599     albertel 7257:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7258:     $$metathesekeys{$unikey}=1;
1.599     albertel 7259:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7260: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7261:     }
1.599     albertel 7262:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7263: 	$metaentry{':'.$unikey}=
                   7264: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7265:     }
                   7266: }
                   7267: 
1.261     albertel 7268: sub metadata_generate_part0 {
                   7269:     my ($metadata,$metacache,$uri) = @_;
                   7270:     my %allnames;
1.737     albertel 7271:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7272: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7273: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7274: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7275: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7276: 	    $allnames{$name}=$part;
                   7277: 	  }
                   7278: 	}
                   7279:     }
                   7280:     foreach my $name (keys(%allnames)) {
                   7281:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7282:       my $key=":parameter_0_$name";
1.261     albertel 7283:       $$metacache{"$key.part"}='0';
                   7284:       $$metacache{"$key.name"}=$name;
1.428     albertel 7285:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7286: 					   $allnames{$name}.'_'.$name.
                   7287: 					   '.type'};
1.428     albertel 7288:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7289: 			     '.display'};
1.644     www      7290:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7291:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7292:       $$metacache{"$key.display"}=$olddis;
                   7293:     }
1.71      www      7294: }
                   7295: 
1.764     albertel 7296: # ------------------------------------------------------ Devalidate title cache
                   7297: 
                   7298: sub devalidate_title_cache {
                   7299:     my ($url)=@_;
                   7300:     if (!$env{'request.course.id'}) { return; }
                   7301:     my $symb=&symbread($url);
                   7302:     if (!$symb) { return; }
                   7303:     my $key=$env{'request.course.id'}."\0".$symb;
                   7304:     &devalidate_cache_new('title',$key);
                   7305: }
                   7306: 
1.301     www      7307: # ------------------------------------------------- Get the title of a resource
                   7308: 
                   7309: sub gettitle {
                   7310:     my $urlsymb=shift;
                   7311:     my $symb=&symbread($urlsymb);
1.534     albertel 7312:     if ($symb) {
1.620     albertel 7313: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7314: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7315: 	if (defined($cached)) { 
                   7316: 	    return $result;
                   7317: 	}
1.534     albertel 7318: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7319: 	my $title='';
1.907     albertel 7320: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7321: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7322: 	} else {
                   7323: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7324: 		    &GDBM_READER(),0640)) {
                   7325: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7326: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7327: 		untie(%bighash);
                   7328: 	    }
1.534     albertel 7329: 	}
                   7330: 	$title=~s/\&colon\;/\:/gs;
                   7331: 	if ($title) {
1.599     albertel 7332: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7333: 	}
                   7334: 	$urlsymb=$url;
                   7335:     }
                   7336:     my $title=&metadata($urlsymb,'title');
                   7337:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7338:     return $title;
1.301     www      7339: }
1.613     albertel 7340: 
1.614     albertel 7341: sub get_slot {
                   7342:     my ($which,$cnum,$cdom)=@_;
                   7343:     if (!$cnum || !$cdom) {
1.790     albertel 7344: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7345: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7346: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7347:     }
1.703     albertel 7348:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7349:     my %slotinfo;
                   7350:     if (exists($remembered{$key})) {
                   7351: 	$slotinfo{$which} = $remembered{$key};
                   7352:     } else {
                   7353: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7354: 	&Apache::lonhomework::showhash(%slotinfo);
                   7355: 	my ($tmp)=keys(%slotinfo);
                   7356: 	if ($tmp=~/^error:/) { return (); }
                   7357: 	$remembered{$key} = $slotinfo{$which};
                   7358:     }
1.616     albertel 7359:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7360: 	return %{$slotinfo{$which}};
                   7361:     }
                   7362:     return $slotinfo{$which};
1.614     albertel 7363: }
1.31      www      7364: # ------------------------------------------------- Update symbolic store links
                   7365: 
                   7366: sub symblist {
                   7367:     my ($mapname,%newhash)=@_;
1.438     www      7368:     $mapname=&deversion(&declutter($mapname));
1.31      www      7369:     my %hash;
1.620     albertel 7370:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7371:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7372:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7373: 	    foreach my $url (keys %newhash) {
                   7374: 		next if ($url eq 'last_known'
                   7375: 			 && $env{'form.no_update_last_known'});
                   7376: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7377: 						    $newhash{$url}->[1],
                   7378: 						    $newhash{$url}->[0]);
1.191     harris41 7379:             }
1.31      www      7380:             if (untie(%hash)) {
                   7381: 		return 'ok';
                   7382:             }
                   7383:         }
                   7384:     }
                   7385:     return 'error';
1.212     www      7386: }
                   7387: 
                   7388: # --------------------------------------------------------------- Verify a symb
                   7389: 
                   7390: sub symbverify {
1.510     www      7391:     my ($symb,$thisurl)=@_;
                   7392:     my $thisfn=$thisurl;
1.439     www      7393:     $thisfn=&declutter($thisfn);
1.215     www      7394: # direct jump to resource in page or to a sequence - will construct own symbs
                   7395:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7396: # check URL part
1.409     www      7397:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7398: 
1.431     www      7399:     unless ($url eq $thisfn) { return 0; }
1.213     www      7400: 
1.216     www      7401:     $symb=&symbclean($symb);
1.510     www      7402:     $thisurl=&deversion($thisurl);
1.439     www      7403:     $thisfn=&deversion($thisfn);
1.213     www      7404: 
                   7405:     my %bighash;
                   7406:     my $okay=0;
1.431     www      7407: 
1.620     albertel 7408:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7409:                             &GDBM_READER(),0640)) {
1.510     www      7410:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7411:         unless ($ids) { 
1.510     www      7412:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7413:         }
                   7414:         if ($ids) {
                   7415: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7416: 	    foreach my $id (split(/\,/,$ids)) {
                   7417: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7418:                if (
                   7419:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7420:    eq $symb) { 
1.620     albertel 7421: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7422: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7423: 		       $okay=1; 
                   7424: 		   }
                   7425: 	       }
1.216     www      7426: 	   }
                   7427:         }
1.213     www      7428: 	untie(%bighash);
                   7429:     }
                   7430:     return $okay;
1.31      www      7431: }
                   7432: 
1.210     www      7433: # --------------------------------------------------------------- Clean-up symb
                   7434: 
                   7435: sub symbclean {
                   7436:     my $symb=shift;
1.568     albertel 7437:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7438: # remove version from map
                   7439:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7440: 
1.210     www      7441: # remove version from URL
                   7442:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7443: 
1.507     www      7444: # remove wrapper
                   7445: 
1.510     www      7446:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7447:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7448:     return $symb;
1.409     www      7449: }
                   7450: 
                   7451: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7452: 
                   7453: sub encode_symb {
                   7454:     my ($map,$resid,$url)=@_;
                   7455:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7456: }
1.409     www      7457: 
                   7458: sub decode_symb {
1.568     albertel 7459:     my $symb=shift;
                   7460:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7461:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7462:     return (&fixversion($map),$resid,&fixversion($url));
                   7463: }
                   7464: 
                   7465: sub fixversion {
                   7466:     my $fn=shift;
1.609     banghart 7467:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7468:     my %bighash;
                   7469:     my $uri=&clutter($fn);
1.620     albertel 7470:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7471: # is this cached?
1.599     albertel 7472:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7473:     if (defined($cached)) { return $result; }
                   7474: # unfortunately not cached, or expired
1.620     albertel 7475:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7476: 	    &GDBM_READER(),0640)) {
                   7477:  	if ($bighash{'version_'.$uri}) {
                   7478:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7479:  	    unless (($version eq 'mostrecent') || 
                   7480: 		    ($version==&getversion($uri))) {
1.440     www      7481:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7482:  	    }
                   7483:  	}
                   7484:  	untie %bighash;
1.413     www      7485:     }
1.599     albertel 7486:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7487: }
                   7488: 
                   7489: sub deversion {
                   7490:     my $url=shift;
                   7491:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7492:     return $url;
1.210     www      7493: }
                   7494: 
1.31      www      7495: # ------------------------------------------------------ Return symb list entry
                   7496: 
                   7497: sub symbread {
1.249     www      7498:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7499:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7500:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7501: # no filename provided? try from environment
1.44      www      7502:     unless ($thisfn) {
1.620     albertel 7503:         if ($env{'request.symb'}) {
                   7504: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7505: 	}
1.620     albertel 7506: 	$thisfn=$env{'request.filename'};
1.44      www      7507:     }
1.569     albertel 7508:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7509: # is that filename actually a symb? Verify, clean, and return
                   7510:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7511: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7512: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7513: 	}
1.242     www      7514:     }
1.44      www      7515:     $thisfn=declutter($thisfn);
1.31      www      7516:     my %hash;
1.37      www      7517:     my %bighash;
                   7518:     my $syval='';
1.620     albertel 7519:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7520:         my $targetfn = $thisfn;
1.609     banghart 7521:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7522:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7523:         }
1.687     albertel 7524: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7525: 	    $targetfn=$1;
                   7526: 	}
1.620     albertel 7527:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7528:                       &GDBM_READER(),0640)) {
1.481     raeburn  7529: 	    $syval=$hash{$targetfn};
1.37      www      7530:             untie(%hash);
                   7531:         }
                   7532: # ---------------------------------------------------------- There was an entry
                   7533:         if ($syval) {
1.601     albertel 7534: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7535: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7536: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7537: 		    #return $env{$cache_str}='';
1.601     albertel 7538: 		#}    
                   7539: 		#$syval.=$1;
                   7540: 	    #}
1.37      www      7541:         } else {
                   7542: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7543:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7544:                             &GDBM_READER(),0640)) {
1.37      www      7545: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7546:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7547:               unless ($ids) { 
                   7548:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7549:               }
                   7550:               unless ($ids) {
                   7551: # alias?
                   7552: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7553:               }
1.37      www      7554:               if ($ids) {
                   7555: # ------------------------------------------------------------------- Has ID(s)
                   7556:                  my @possibilities=split(/\,/,$ids);
1.39      www      7557:                  if ($#possibilities==0) {
                   7558: # ----------------------------------------------- There is only one possibility
1.37      www      7559: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7560: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7561: 						    $resid,$thisfn);
1.249     www      7562:                  } elsif (!$donotrecurse) {
1.39      www      7563: # ------------------------------------------ There is more than one possibility
                   7564:                      my $realpossible=0;
1.800     albertel 7565:                      foreach my $id (@possibilities) {
                   7566: 			 my $file=$bighash{'src_'.$id};
1.39      www      7567:                          if (&allowed('bre',$file)) {
1.800     albertel 7568:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7569:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7570: 				$realpossible++;
1.626     albertel 7571:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7572: 						    $resid,$thisfn);
1.39      www      7573:                             }
                   7574: 			 }
1.191     harris41 7575:                      }
1.39      www      7576: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7577:                  } else {
                   7578:                      $syval='';
1.37      www      7579:                  }
                   7580: 	      }
                   7581:               untie(%bighash)
1.481     raeburn  7582:            }
1.31      www      7583:         }
1.62      www      7584:         if ($syval) {
1.620     albertel 7585: 	    return $env{$cache_str}=$syval;
1.62      www      7586:         }
1.31      www      7587:     }
1.949     raeburn  7588:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7589:     return $env{$cache_str}='';
1.31      www      7590: }
                   7591: 
                   7592: # ---------------------------------------------------------- Return random seed
                   7593: 
1.32      www      7594: sub numval {
                   7595:     my $txt=shift;
                   7596:     $txt=~tr/A-J/0-9/;
                   7597:     $txt=~tr/a-j/0-9/;
                   7598:     $txt=~tr/K-T/0-9/;
                   7599:     $txt=~tr/k-t/0-9/;
                   7600:     $txt=~tr/U-Z/0-5/;
                   7601:     $txt=~tr/u-z/0-5/;
                   7602:     $txt=~s/\D//g;
1.564     albertel 7603:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7604:     return int($txt);
1.368     albertel 7605: }
                   7606: 
1.484     albertel 7607: sub numval2 {
                   7608:     my $txt=shift;
                   7609:     $txt=~tr/A-J/0-9/;
                   7610:     $txt=~tr/a-j/0-9/;
                   7611:     $txt=~tr/K-T/0-9/;
                   7612:     $txt=~tr/k-t/0-9/;
                   7613:     $txt=~tr/U-Z/0-5/;
                   7614:     $txt=~tr/u-z/0-5/;
                   7615:     $txt=~s/\D//g;
                   7616:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7617:     my $total;
                   7618:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7619:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7620:     return int($total);
                   7621: }
                   7622: 
1.575     albertel 7623: sub numval3 {
                   7624:     use integer;
                   7625:     my $txt=shift;
                   7626:     $txt=~tr/A-J/0-9/;
                   7627:     $txt=~tr/a-j/0-9/;
                   7628:     $txt=~tr/K-T/0-9/;
                   7629:     $txt=~tr/k-t/0-9/;
                   7630:     $txt=~tr/U-Z/0-5/;
                   7631:     $txt=~tr/u-z/0-5/;
                   7632:     $txt=~s/\D//g;
                   7633:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7634:     my $total;
                   7635:     foreach my $val (@txts) { $total+=$val; }
                   7636:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7637:     return $total;
                   7638: }
                   7639: 
1.675     albertel 7640: sub digest {
                   7641:     my ($data)=@_;
                   7642:     my $digest=&Digest::MD5::md5($data);
                   7643:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7644:     my ($e,$f);
                   7645:     {
                   7646:         use integer;
                   7647:         $e=($a+$b);
                   7648:         $f=($c+$d);
                   7649:         if ($_64bit) {
                   7650:             $e=(($e<<32)>>32);
                   7651:             $f=(($f<<32)>>32);
                   7652:         }
                   7653:     }
                   7654:     if (wantarray) {
                   7655: 	return ($e,$f);
                   7656:     } else {
                   7657: 	my $g;
                   7658: 	{
                   7659: 	    use integer;
                   7660: 	    $g=($e+$f);
                   7661: 	    if ($_64bit) {
                   7662: 		$g=(($g<<32)>>32);
                   7663: 	    }
                   7664: 	}
                   7665: 	return $g;
                   7666:     }
                   7667: }
                   7668: 
1.368     albertel 7669: sub latest_rnd_algorithm_id {
1.675     albertel 7670:     return '64bit5';
1.366     albertel 7671: }
1.32      www      7672: 
1.503     albertel 7673: sub get_rand_alg {
                   7674:     my ($courseid)=@_;
1.790     albertel 7675:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7676:     if ($courseid) {
1.620     albertel 7677: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7678:     }
                   7679:     return &latest_rnd_algorithm_id();
                   7680: }
                   7681: 
1.562     albertel 7682: sub validCODE {
                   7683:     my ($CODE)=@_;
                   7684:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7685:     return 0;
                   7686: }
                   7687: 
1.491     albertel 7688: sub getCODE {
1.620     albertel 7689:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7690:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7691: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7692: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7693: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7694:     }
                   7695:     return undef;
                   7696: }
                   7697: 
1.31      www      7698: sub rndseed {
1.155     albertel 7699:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7700:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7701:     if (!defined($symb)) {
1.366     albertel 7702: 	unless ($symb=$wsymb) { return time; }
                   7703:     }
                   7704:     if (!$courseid) { $courseid=$wcourseid; }
                   7705:     if (!$domain) { $domain=$wdomain; }
                   7706:     if (!$username) { $username=$wusername }
1.503     albertel 7707:     my $which=&get_rand_alg();
1.803     albertel 7708: 
1.491     albertel 7709:     if (defined(&getCODE())) {
1.675     albertel 7710: 	if ($which eq '64bit5') {
                   7711: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7712: 	} elsif ($which eq '64bit4') {
1.575     albertel 7713: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7714: 	} else {
                   7715: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7716: 	}
1.675     albertel 7717:     } elsif ($which eq '64bit5') {
                   7718: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7719:     } elsif ($which eq '64bit4') {
                   7720: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7721:     } elsif ($which eq '64bit3') {
                   7722: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7723:     } elsif ($which eq '64bit2') {
                   7724: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7725:     } elsif ($which eq '64bit') {
                   7726: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7727:     }
                   7728:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7729: }
                   7730: 
                   7731: sub rndseed_32bit {
                   7732:     my ($symb,$courseid,$domain,$username)=@_;
                   7733:     {
                   7734: 	use integer;
                   7735: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7736: 	my $symbseed=numval($symb) << 22;
                   7737: 	my $namechck=unpack("%32C*",$username) << 17;
                   7738: 	my $nameseed=numval($username) << 12;
                   7739: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7740: 	my $courseseed=unpack("%32C*",$courseid);
                   7741: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7742: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7743: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7744: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7745: 	return $num;
                   7746:     }
                   7747: }
                   7748: 
                   7749: sub rndseed_64bit {
                   7750:     my ($symb,$courseid,$domain,$username)=@_;
                   7751:     {
                   7752: 	use integer;
                   7753: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7754: 	my $symbseed=numval($symb) << 10;
                   7755: 	my $namechck=unpack("%32S*",$username);
                   7756: 	
                   7757: 	my $nameseed=numval($username) << 21;
                   7758: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7759: 	my $courseseed=unpack("%32S*",$courseid);
                   7760: 	
                   7761: 	my $num1=$symbchck+$symbseed+$namechck;
                   7762: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7763: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7764: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7765: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7766: 	return "$num1,$num2";
1.155     albertel 7767:     }
1.366     albertel 7768: }
                   7769: 
1.443     albertel 7770: sub rndseed_64bit2 {
                   7771:     my ($symb,$courseid,$domain,$username)=@_;
                   7772:     {
                   7773: 	use integer;
                   7774: 	# strings need to be an even # of cahracters long, it it is odd the
                   7775:         # last characters gets thrown away
                   7776: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7777: 	my $symbseed=numval($symb) << 10;
                   7778: 	my $namechck=unpack("%32S*",$username.' ');
                   7779: 	
                   7780: 	my $nameseed=numval($username) << 21;
1.501     albertel 7781: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7782: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7783: 	
                   7784: 	my $num1=$symbchck+$symbseed+$namechck;
                   7785: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7786: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7787: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7788: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7789: 	return "$num1,$num2";
                   7790:     }
                   7791: }
                   7792: 
                   7793: sub rndseed_64bit3 {
                   7794:     my ($symb,$courseid,$domain,$username)=@_;
                   7795:     {
                   7796: 	use integer;
                   7797: 	# strings need to be an even # of cahracters long, it it is odd the
                   7798:         # last characters gets thrown away
                   7799: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7800: 	my $symbseed=numval2($symb) << 10;
                   7801: 	my $namechck=unpack("%32S*",$username.' ');
                   7802: 	
                   7803: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7804: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7805: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7806: 	
                   7807: 	my $num1=$symbchck+$symbseed+$namechck;
                   7808: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7809: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7810: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7811: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7812: 	
1.503     albertel 7813: 	return "$num1:$num2";
1.443     albertel 7814:     }
                   7815: }
                   7816: 
1.575     albertel 7817: sub rndseed_64bit4 {
                   7818:     my ($symb,$courseid,$domain,$username)=@_;
                   7819:     {
                   7820: 	use integer;
                   7821: 	# strings need to be an even # of cahracters long, it it is odd the
                   7822:         # last characters gets thrown away
                   7823: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7824: 	my $symbseed=numval3($symb) << 10;
                   7825: 	my $namechck=unpack("%32S*",$username.' ');
                   7826: 	
                   7827: 	my $nameseed=numval3($username) << 21;
                   7828: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7829: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7830: 	
                   7831: 	my $num1=$symbchck+$symbseed+$namechck;
                   7832: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7833: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7834: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7835: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7836: 	
                   7837: 	return "$num1:$num2";
                   7838:     }
                   7839: }
                   7840: 
1.675     albertel 7841: sub rndseed_64bit5 {
                   7842:     my ($symb,$courseid,$domain,$username)=@_;
                   7843:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7844:     return "$num1:$num2";
                   7845: }
                   7846: 
1.366     albertel 7847: sub rndseed_CODE_64bit {
                   7848:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7849:     {
1.366     albertel 7850: 	use integer;
1.443     albertel 7851: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7852: 	my $symbseed=numval2($symb);
1.491     albertel 7853: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7854: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7855: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7856: 	my $num1=$symbseed+$CODEchck;
                   7857: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7858: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7859: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7860: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7861: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7862: 	return "$num1:$num2";
1.366     albertel 7863:     }
                   7864: }
                   7865: 
1.575     albertel 7866: sub rndseed_CODE_64bit4 {
                   7867:     my ($symb,$courseid,$domain,$username)=@_;
                   7868:     {
                   7869: 	use integer;
                   7870: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7871: 	my $symbseed=numval3($symb);
                   7872: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7873: 	my $CODEseed=numval3(&getCODE());
                   7874: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7875: 	my $num1=$symbseed+$CODEchck;
                   7876: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7877: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7878: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7879: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7880: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7881: 	return "$num1:$num2";
                   7882:     }
                   7883: }
                   7884: 
1.675     albertel 7885: sub rndseed_CODE_64bit5 {
                   7886:     my ($symb,$courseid,$domain,$username)=@_;
                   7887:     my $code = &getCODE();
                   7888:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7889:     return "$num1:$num2";
                   7890: }
                   7891: 
1.366     albertel 7892: sub setup_random_from_rndseed {
                   7893:     my ($rndseed)=@_;
1.503     albertel 7894:     if ($rndseed =~/([,:])/) {
                   7895: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7896: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7897:     } else {
                   7898: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7899:     }
1.36      albertel 7900: }
                   7901: 
1.474     albertel 7902: sub latest_receipt_algorithm_id {
1.835     albertel 7903:     return 'receipt3';
1.474     albertel 7904: }
                   7905: 
1.480     www      7906: sub recunique {
                   7907:     my $fucourseid=shift;
                   7908:     my $unique;
1.835     albertel 7909:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7910: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7911: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7912:     } else {
                   7913: 	$unique=$perlvar{'lonReceipt'};
                   7914:     }
                   7915:     return unpack("%32C*",$unique);
                   7916: }
                   7917: 
                   7918: sub recprefix {
                   7919:     my $fucourseid=shift;
                   7920:     my $prefix;
1.835     albertel 7921:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7922: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7923: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7924:     } else {
                   7925: 	$prefix=$perlvar{'lonHostID'};
                   7926:     }
                   7927:     return unpack("%32C*",$prefix);
                   7928: }
                   7929: 
1.76      www      7930: sub ireceipt {
1.474     albertel 7931:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7932: 
                   7933:     my $return =&recprefix($fucourseid).'-';
                   7934: 
                   7935:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7936: 	$env{'request.state'} eq 'construct') {
                   7937: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7938: 	return $return;
                   7939:     }
                   7940: 
1.76      www      7941:     my $cuname=unpack("%32C*",$funame);
                   7942:     my $cudom=unpack("%32C*",$fudom);
                   7943:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7944:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7945:     my $cunique=&recunique($fucourseid);
1.474     albertel 7946:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7947:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7948: 
1.790     albertel 7949: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7950: 			       
                   7951: 	$return.= ($cunique%$cuname+
                   7952: 		   $cunique%$cudom+
                   7953: 		   $cusymb%$cuname+
                   7954: 		   $cusymb%$cudom+
                   7955: 		   $cucourseid%$cuname+
                   7956: 		   $cucourseid%$cudom+
                   7957: 		   $cpart%$cuname+
                   7958: 		   $cpart%$cudom);
                   7959:     } else {
                   7960: 	$return.= ($cunique%$cuname+
                   7961: 		   $cunique%$cudom+
                   7962: 		   $cusymb%$cuname+
                   7963: 		   $cusymb%$cudom+
                   7964: 		   $cucourseid%$cuname+
                   7965: 		   $cucourseid%$cudom);
                   7966:     }
                   7967:     return $return;
1.76      www      7968: }
                   7969: 
                   7970: sub receipt {
1.474     albertel 7971:     my ($part)=@_;
1.790     albertel 7972:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7973:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7974: }
1.260     ng       7975: 
1.790     albertel 7976: sub whichuser {
                   7977:     my ($passedsymb)=@_;
                   7978:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7979:     if (defined($env{'form.grade_symb'})) {
                   7980: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7981: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7982: 	if (!$allowed &&
                   7983: 	    exists($env{'request.course.sec'}) &&
                   7984: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7985: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7986: 			      '/'.$env{'request.course.sec'});
                   7987: 	}
                   7988: 	if ($allowed) {
                   7989: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7990: 	    $courseid=$tmp_courseid;
                   7991: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7992: 	    ($name)=&get_env_multiple('form.grade_username');
                   7993: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7994: 	}
                   7995:     }
                   7996:     if (!$passedsymb) {
                   7997: 	$symb=&symbread();
                   7998:     } else {
                   7999: 	$symb=$passedsymb;
                   8000:     }
                   8001:     $courseid=$env{'request.course.id'};
                   8002:     $domain=$env{'user.domain'};
                   8003:     $name=$env{'user.name'};
                   8004:     if ($name eq 'public' && $domain eq 'public') {
                   8005: 	if (!defined($env{'form.username'})) {
                   8006: 	    $env{'form.username'}.=time.rand(10000000);
                   8007: 	}
                   8008: 	$name.=$env{'form.username'};
                   8009:     }
                   8010:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8011: 
                   8012: }
                   8013: 
1.36      albertel 8014: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8015: # returns either the contents of the file or 
                   8016: # -1 if the file doesn't exist
1.481     raeburn  8017: #
                   8018: # if the target is a file that was uploaded via DOCS, 
                   8019: # a check will be made to see if a current copy exists on the local server,
                   8020: # if it does this will be served, otherwise a copy will be retrieved from
                   8021: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8022: # the local server.   
1.472     albertel 8023: 
1.36      albertel 8024: sub getfile {
1.538     albertel 8025:     my ($file) = @_;
1.609     banghart 8026:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8027:     &repcopy($file);
                   8028:     return &readfile($file);
                   8029: }
                   8030: 
                   8031: sub repcopy_userfile {
                   8032:     my ($file)=@_;
1.609     banghart 8033:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8034:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8035:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8036: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8037:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8038:     if (-e "$file") {
1.828     www      8039: # we already have a local copy, check it out
1.538     albertel 8040: 	my @fileinfo = stat($file);
1.828     www      8041: 	my $rtncode;
                   8042: 	my $info;
1.538     albertel 8043: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8044: 	if ($lwpresp ne 'ok') {
1.828     www      8045: # there is no such file anymore, even though we had a local copy
1.482     albertel 8046: 	    if ($rtncode eq '404') {
1.538     albertel 8047: 		unlink($file);
1.482     albertel 8048: 	    }
                   8049: 	    return -1;
                   8050: 	}
                   8051: 	if ($info < $fileinfo[9]) {
1.828     www      8052: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8053: 	    return 'ok';
1.828     www      8054: 	} else {
                   8055: # the file is outdated, get rid of it
                   8056: 	    unlink($file);
1.482     albertel 8057: 	}
1.828     www      8058:     }
                   8059: # one way or the other, at this point, we don't have the file
                   8060: # construct the correct path for the file
                   8061:     my @parts = ($cdom,$cnum); 
                   8062:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8063: 	push @parts, split(/\//,$1);
                   8064:     }
                   8065:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8066:     foreach my $part (@parts) {
                   8067: 	$path .= '/'.$part;
                   8068: 	if (!-e $path) {
                   8069: 	    mkdir($path,0770);
1.482     albertel 8070: 	}
                   8071:     }
1.828     www      8072: # now the path exists for sure
                   8073: # get a user agent
                   8074:     my $ua=new LWP::UserAgent;
                   8075:     my $transferfile=$file.'.in.transfer';
                   8076: # FIXME: this should flock
                   8077:     if (-e $transferfile) { return 'ok'; }
                   8078:     my $request;
                   8079:     $uri=~s/^\///;
1.838     albertel 8080:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8081:     my $response=$ua->request($request,$transferfile);
                   8082: # did it work?
                   8083:     if ($response->is_error()) {
                   8084: 	unlink($transferfile);
                   8085: 	&logthis("Userfile repcopy failed for $uri");
                   8086: 	return -1;
                   8087:     }
                   8088: # worked, rename the transfer file
                   8089:     rename($transferfile,$file);
1.607     raeburn  8090:     return 'ok';
1.481     raeburn  8091: }
                   8092: 
1.517     albertel 8093: sub tokenwrapper {
                   8094:     my $uri=shift;
1.552     albertel 8095:     $uri=~s|^http\://([^/]+)||;
                   8096:     $uri=~s|^/||;
1.620     albertel 8097:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8098:     my $token=$1;
1.552     albertel 8099:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8100:     if ($udom && $uname && $file) {
                   8101: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8102:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8103:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8104:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8105:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8106:     } else {
                   8107:         return '/adm/notfound.html';
                   8108:     }
                   8109: }
                   8110: 
1.828     www      8111: # call with reqtype HEAD: get last modification time
                   8112: # call with reqtype GET: get the file contents
                   8113: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8114: #
1.481     raeburn  8115: sub getuploaded {
                   8116:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8117:     $uri=~s/^\///;
1.838     albertel 8118:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8119:     my $ua=new LWP::UserAgent;
                   8120:     my $request=new HTTP::Request($reqtype,$uri);
                   8121:     my $response=$ua->request($request);
                   8122:     $$rtncode = $response->code;
1.482     albertel 8123:     if (! $response->is_success()) {
                   8124: 	return 'failed';
                   8125:     }      
                   8126:     if ($reqtype eq 'HEAD') {
1.486     www      8127: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8128:     } elsif ($reqtype eq 'GET') {
                   8129: 	$$info = $response->content;
1.472     albertel 8130:     }
1.482     albertel 8131:     return 'ok';
1.36      albertel 8132: }
                   8133: 
1.481     raeburn  8134: sub readfile {
                   8135:     my $file = shift;
                   8136:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8137:     my $fh;
                   8138:     open($fh,"<$file");
                   8139:     my $a='';
1.800     albertel 8140:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8141:     return $a;
                   8142: }
                   8143: 
1.36      albertel 8144: sub filelocation {
1.590     banghart 8145:     my ($dir,$file) = @_;
                   8146:     my $location;
                   8147:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8148: 
                   8149:     if ($file =~ m-^/adm/-) {
                   8150: 	$file=~s-^/adm/wrapper/-/-;
                   8151: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8152:     }
1.882     albertel 8153: 
1.590     banghart 8154:     if ($file=~m:^/~:) { # is a contruction space reference
                   8155:         $location = $file;
                   8156:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8157:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8158: 	# is a correct contruction space reference
                   8159:         $location = $file;
1.956     raeburn  8160:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8161:         $location = $file;
1.609     banghart 8162:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8163:         my ($udom,$uname,$filename)=
1.811     albertel 8164:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8165:         my $home=&homeserver($uname,$udom);
                   8166:         my $is_me=0;
                   8167:         my @ids=&current_machine_ids();
                   8168:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8169:         if ($is_me) {
1.955     raeburn  8170:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8171:         } else {
                   8172:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8173:   	      $udom.'/'.$uname.'/'.$filename;
                   8174:         }
1.882     albertel 8175:     } elsif ($file =~ m-^/adm/-) {
                   8176: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8177:     } else {
                   8178:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8179:         $file=~s:^/res/:/:;
                   8180:         if ( !( $file =~ m:^/:) ) {
                   8181:             $location = $dir. '/'.$file;
                   8182:         } else {
                   8183:             $location = '/home/httpd/html/res'.$file;
                   8184:         }
1.59      albertel 8185:     }
1.590     banghart 8186:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8187:     while ($location=~m{/\.\./}) {
                   8188: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8189: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8190: 	} else {
                   8191: 	    $location=~ s{/\.\./}{/}g;
                   8192: 	}
                   8193:     } #remove dir/..
1.590     banghart 8194:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8195:     return $location;
1.46      www      8196: }
1.36      albertel 8197: 
1.46      www      8198: sub hreflocation {
                   8199:     my ($dir,$file)=@_;
1.460     albertel 8200:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8201: 	$file=filelocation($dir,$file);
1.700     albertel 8202:     } elsif ($file=~m-^/adm/-) {
                   8203: 	$file=~s-^/adm/wrapper/-/-;
                   8204: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8205:     }
                   8206:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8207: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8208:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8209: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8210:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8211: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8212: 	    -/uploaded/$1/$2/-x;
1.46      www      8213:     }
1.913     albertel 8214:     if ($file=~ m{^/userfiles/}) {
                   8215: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8216:     }
1.462     albertel 8217:     return $file;
1.465     albertel 8218: }
                   8219: 
                   8220: sub current_machine_domains {
1.853     albertel 8221:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8222: }
                   8223: 
                   8224: sub machine_domains {
                   8225:     my ($hostname) = @_;
1.465     albertel 8226:     my @domains;
1.838     albertel 8227:     my %hostname = &all_hostnames();
1.465     albertel 8228:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8229: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8230: 	if ($hostname eq $name) {
1.844     albertel 8231: 	    push(@domains,&host_domain($id));
1.465     albertel 8232: 	}
                   8233:     }
                   8234:     return @domains;
                   8235: }
                   8236: 
                   8237: sub current_machine_ids {
1.853     albertel 8238:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8239: }
                   8240: 
                   8241: sub machine_ids {
                   8242:     my ($hostname) = @_;
                   8243:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8244:     my @ids;
1.888     albertel 8245:     my %name_to_host = &all_names();
1.889     albertel 8246:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8247: 	return @{ $name_to_host{$hostname} };
                   8248:     }
                   8249:     return;
1.31      www      8250: }
                   8251: 
1.824     raeburn  8252: sub additional_machine_domains {
                   8253:     my @domains;
                   8254:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8255:     while( my $line = <$fh>) {
                   8256:         $line =~ s/\s//g;
                   8257:         push(@domains,$line);
                   8258:     }
                   8259:     return @domains;
                   8260: }
                   8261: 
                   8262: sub default_login_domain {
                   8263:     my $domain = $perlvar{'lonDefDomain'};
                   8264:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8265:     foreach my $posdom (&current_machine_domains(),
                   8266:                         &additional_machine_domains()) {
                   8267:         if (lc($posdom) eq lc($testdomain)) {
                   8268:             $domain=$posdom;
                   8269:             last;
                   8270:         }
                   8271:     }
                   8272:     return $domain;
                   8273: }
                   8274: 
1.31      www      8275: # ------------------------------------------------------------- Declutters URLs
                   8276: 
                   8277: sub declutter {
                   8278:     my $thisfn=shift;
1.569     albertel 8279:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8280:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8281:     $thisfn=~s/^\///;
1.697     albertel 8282:     $thisfn=~s|^adm/wrapper/||;
                   8283:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8284:     $thisfn=~s/^res\///;
1.235     www      8285:     $thisfn=~s/\?.+$//;
1.268     www      8286:     return $thisfn;
                   8287: }
                   8288: 
                   8289: # ------------------------------------------------------------- Clutter up URLs
                   8290: 
                   8291: sub clutter {
                   8292:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8293:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8294: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8295:        $thisfn='/res'.$thisfn; 
                   8296:     }
1.694     albertel 8297:     if ($thisfn !~m|/adm|) {
1.695     albertel 8298: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8299: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8300: 	} else {
                   8301: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8302: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8303: 	    if ($embstyle eq 'ssi'
                   8304: 		|| ($embstyle eq 'hdn')
                   8305: 		|| ($embstyle eq 'rat')
                   8306: 		|| ($embstyle eq 'prv')
                   8307: 		|| ($embstyle eq 'ign')) {
                   8308: 		#do nothing with these
                   8309: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8310: 		|| ($embstyle eq 'emb')
                   8311: 		|| ($embstyle eq 'wrp')) {
                   8312: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8313: 	    } elsif ($embstyle eq 'unk'
                   8314: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8315: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8316: 	    } else {
1.718     www      8317: #		&logthis("Got a blank emb style");
1.695     albertel 8318: 	    }
1.694     albertel 8319: 	}
                   8320:     }
1.31      www      8321:     return $thisfn;
1.12      www      8322: }
                   8323: 
1.787     albertel 8324: sub clutter_with_no_wrapper {
                   8325:     my $uri = &clutter(shift);
                   8326:     if ($uri =~ m-^/adm/-) {
                   8327: 	$uri =~ s-^/adm/wrapper/-/-;
                   8328: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8329:     }
                   8330:     return $uri;
                   8331: }
                   8332: 
1.557     albertel 8333: sub freeze_escape {
                   8334:     my ($value)=@_;
                   8335:     if (ref($value)) {
                   8336: 	$value=&nfreeze($value);
                   8337: 	return '__FROZEN__'.&escape($value);
                   8338:     }
                   8339:     return &escape($value);
                   8340: }
                   8341: 
1.11      www      8342: 
1.557     albertel 8343: sub thaw_unescape {
                   8344:     my ($value)=@_;
                   8345:     if ($value =~ /^__FROZEN__/) {
                   8346: 	substr($value,0,10,undef);
                   8347: 	$value=&unescape($value);
                   8348: 	return &thaw($value);
                   8349:     }
                   8350:     return &unescape($value);
                   8351: }
                   8352: 
1.436     albertel 8353: sub correct_line_ends {
                   8354:     my ($result)=@_;
                   8355:     $$result =~s/\r\n/\n/mg;
                   8356:     $$result =~s/\r/\n/mg;
1.415     albertel 8357: }
1.1       albertel 8358: # ================================================================ Main Program
                   8359: 
1.184     www      8360: sub goodbye {
1.204     albertel 8361:    &logthis("Starting Shut down");
1.443     albertel 8362: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8363:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8364: #converted
1.599     albertel 8365: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8366:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8367: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8368: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8369: #1.1 only
1.870     albertel 8370: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8371: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8372: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8373: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8374:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8375:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8376:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8377:    &flushcourselogs();
                   8378:    &logthis("Shutting down");
                   8379: }
                   8380: 
1.852     albertel 8381: sub get_dns {
1.869     albertel 8382:     my ($url,$func,$ignore_cache) = @_;
                   8383:     if (!$ignore_cache) {
                   8384: 	my ($content,$cached)=
                   8385: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8386: 	if ($cached) {
                   8387: 	    &$func($content);
                   8388: 	    return;
                   8389: 	}
                   8390:     }
                   8391: 
                   8392:     my %alldns;
1.852     albertel 8393:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8394:     foreach my $dns (<$config>) {
                   8395: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8396: 	$alldns{$1} = 1;
                   8397:     }
                   8398:     while (%alldns) {
                   8399: 	my ($dns) = keys(%alldns);
                   8400: 	delete($alldns{$dns});
1.852     albertel 8401: 	my $ua=new LWP::UserAgent;
                   8402: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8403: 	my $response=$ua->request($request);
                   8404: 	next if ($response->is_error());
                   8405: 	my @content = split("\n",$response->content);
1.869     albertel 8406: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8407: 	&$func(\@content);
1.869     albertel 8408: 	return;
1.852     albertel 8409:     }
                   8410:     close($config);
1.871     albertel 8411:     my $which = (split('/',$url))[3];
                   8412:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8413:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8414:     my @content = <$config>;
                   8415:     &$func(\@content);
                   8416:     return;
1.852     albertel 8417: }
1.327     albertel 8418: # ------------------------------------------------------------ Read domain file
                   8419: {
1.852     albertel 8420:     my $loaded;
1.846     albertel 8421:     my %domain;
                   8422: 
1.852     albertel 8423:     sub parse_domain_tab {
                   8424: 	my ($lines) = @_;
                   8425: 	foreach my $line (@$lines) {
                   8426: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8427: 
1.846     albertel 8428: 	    chomp($line);
1.852     albertel 8429: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8430: 	    my %this_domain;
                   8431: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8432: 			       'lang_def', 'city', 'longi', 'lati',
                   8433: 			       'primary') {
                   8434: 		$this_domain{$field} = shift(@elements);
                   8435: 	    }
                   8436: 	    $domain{$name} = \%this_domain;
1.852     albertel 8437: 	}
                   8438:     }
1.864     albertel 8439: 
                   8440:     sub reset_domain_info {
                   8441: 	undef($loaded);
                   8442: 	undef(%domain);
                   8443:     }
                   8444: 
1.852     albertel 8445:     sub load_domain_tab {
1.869     albertel 8446: 	my ($ignore_cache) = @_;
                   8447: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8448: 	my $fh;
                   8449: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8450: 	    my @lines = <$fh>;
                   8451: 	    &parse_domain_tab(\@lines);
1.448     albertel 8452: 	}
1.852     albertel 8453: 	close($fh);
                   8454: 	$loaded = 1;
1.327     albertel 8455:     }
1.846     albertel 8456: 
                   8457:     sub domain {
1.852     albertel 8458: 	&load_domain_tab() if (!$loaded);
                   8459: 
1.846     albertel 8460: 	my ($name,$what) = @_;
                   8461: 	return if ( !exists($domain{$name}) );
                   8462: 
                   8463: 	if (!$what) {
                   8464: 	    return $domain{$name}{'description'};
                   8465: 	}
                   8466: 	return $domain{$name}{$what};
                   8467:     }
1.327     albertel 8468: }
                   8469: 
                   8470: 
1.1       albertel 8471: # ------------------------------------------------------------- Read hosts file
                   8472: {
1.838     albertel 8473:     my %hostname;
1.844     albertel 8474:     my %hostdom;
1.845     albertel 8475:     my %libserv;
1.852     albertel 8476:     my $loaded;
1.888     albertel 8477:     my %name_to_host;
1.852     albertel 8478: 
                   8479:     sub parse_hosts_tab {
                   8480: 	my ($file) = @_;
                   8481: 	foreach my $configline (@$file) {
                   8482: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8483: 	    next if ($configline =~ /^\^/);
                   8484: 	    chomp($configline);
                   8485: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8486: 	    $name=~s/\s//g;
                   8487: 	    if ($id && $domain && $role && $name) {
                   8488: 		$hostname{$id}=$name;
1.888     albertel 8489: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8490: 		$hostdom{$id}=$domain;
                   8491: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8492: 	    }
                   8493: 	}
                   8494:     }
1.864     albertel 8495:     
                   8496:     sub reset_hosts_info {
1.897     albertel 8497: 	&purge_remembered();
1.864     albertel 8498: 	&reset_domain_info();
                   8499: 	&reset_hosts_ip_info();
1.892     albertel 8500: 	undef(%name_to_host);
1.864     albertel 8501: 	undef(%hostname);
                   8502: 	undef(%hostdom);
                   8503: 	undef(%libserv);
                   8504: 	undef($loaded);
                   8505:     }
1.1       albertel 8506: 
1.852     albertel 8507:     sub load_hosts_tab {
1.869     albertel 8508: 	my ($ignore_cache) = @_;
                   8509: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8510: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8511: 	my @config = <$config>;
                   8512: 	&parse_hosts_tab(\@config);
                   8513: 	close($config);
                   8514: 	$loaded=1;
1.1       albertel 8515:     }
1.852     albertel 8516: 
1.838     albertel 8517:     sub hostname {
1.852     albertel 8518: 	&load_hosts_tab() if (!$loaded);
                   8519: 
1.838     albertel 8520: 	my ($lonid) = @_;
                   8521: 	return $hostname{$lonid};
                   8522:     }
1.845     albertel 8523: 
1.838     albertel 8524:     sub all_hostnames {
1.852     albertel 8525: 	&load_hosts_tab() if (!$loaded);
                   8526: 
1.838     albertel 8527: 	return %hostname;
                   8528:     }
1.845     albertel 8529: 
1.888     albertel 8530:     sub all_names {
                   8531: 	&load_hosts_tab() if (!$loaded);
                   8532: 
                   8533: 	return %name_to_host;
                   8534:     }
                   8535: 
1.845     albertel 8536:     sub is_library {
1.852     albertel 8537: 	&load_hosts_tab() if (!$loaded);
                   8538: 
1.845     albertel 8539: 	return exists($libserv{$_[0]});
                   8540:     }
                   8541: 
                   8542:     sub all_library {
1.852     albertel 8543: 	&load_hosts_tab() if (!$loaded);
                   8544: 
1.845     albertel 8545: 	return %libserv;
                   8546:     }
                   8547: 
1.841     albertel 8548:     sub get_servers {
1.852     albertel 8549: 	&load_hosts_tab() if (!$loaded);
                   8550: 
1.841     albertel 8551: 	my ($domain,$type) = @_;
                   8552: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8553: 	                                          : %hostname;
                   8554: 	my %result;
1.842     albertel 8555: 	if (ref($domain) eq 'ARRAY') {
                   8556: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8557: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8558: 		    $result{$host} = $hostname;
                   8559: 		}
                   8560: 	    }
                   8561: 	} else {
                   8562: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8563: 		if ($hostdom{$host} eq $domain) {
                   8564: 		    $result{$host} = $hostname;
                   8565: 		}
1.841     albertel 8566: 	    }
                   8567: 	}
                   8568: 	return %result;
                   8569:     }
1.845     albertel 8570: 
1.844     albertel 8571:     sub host_domain {
1.852     albertel 8572: 	&load_hosts_tab() if (!$loaded);
                   8573: 
1.844     albertel 8574: 	my ($lonid) = @_;
                   8575: 	return $hostdom{$lonid};
                   8576:     }
                   8577: 
1.841     albertel 8578:     sub all_domains {
1.852     albertel 8579: 	&load_hosts_tab() if (!$loaded);
                   8580: 
1.841     albertel 8581: 	my %seen;
                   8582: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8583: 	return @uniq;
                   8584:     }
1.1       albertel 8585: }
                   8586: 
1.847     albertel 8587: { 
                   8588:     my %iphost;
1.856     albertel 8589:     my %name_to_ip;
                   8590:     my %lonid_to_ip;
1.869     albertel 8591: 
1.847     albertel 8592:     sub get_hosts_from_ip {
                   8593: 	my ($ip) = @_;
                   8594: 	my %iphosts = &get_iphost();
                   8595: 	if (ref($iphosts{$ip})) {
                   8596: 	    return @{$iphosts{$ip}};
                   8597: 	}
                   8598: 	return;
1.839     albertel 8599:     }
1.864     albertel 8600:     
                   8601:     sub reset_hosts_ip_info {
                   8602: 	undef(%iphost);
                   8603: 	undef(%name_to_ip);
                   8604: 	undef(%lonid_to_ip);
                   8605:     }
1.856     albertel 8606: 
                   8607:     sub get_host_ip {
                   8608: 	my ($lonid) = @_;
                   8609: 	if (exists($lonid_to_ip{$lonid})) {
                   8610: 	    return $lonid_to_ip{$lonid};
                   8611: 	}
                   8612: 	my $name=&hostname($lonid);
                   8613:    	my $ip = gethostbyname($name);
                   8614: 	return if (!$ip || length($ip) ne 4);
                   8615: 	$ip=inet_ntoa($ip);
                   8616: 	$name_to_ip{$name}   = $ip;
                   8617: 	$lonid_to_ip{$lonid} = $ip;
                   8618: 	return $ip;
                   8619:     }
1.847     albertel 8620:     
                   8621:     sub get_iphost {
1.869     albertel 8622: 	my ($ignore_cache) = @_;
1.894     albertel 8623: 
1.869     albertel 8624: 	if (!$ignore_cache) {
                   8625: 	    if (%iphost) {
                   8626: 		return %iphost;
                   8627: 	    }
                   8628: 	    my ($ip_info,$cached)=
                   8629: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8630: 	    if ($cached) {
                   8631: 		%iphost      = %{$ip_info->[0]};
                   8632: 		%name_to_ip  = %{$ip_info->[1]};
                   8633: 		%lonid_to_ip = %{$ip_info->[2]};
                   8634: 		return %iphost;
                   8635: 	    }
                   8636: 	}
1.894     albertel 8637: 
                   8638: 	# get yesterday's info for fallback
                   8639: 	my %old_name_to_ip;
                   8640: 	my ($ip_info,$cached)=
                   8641: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8642: 	if ($cached) {
                   8643: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8644: 	}
                   8645: 
1.888     albertel 8646: 	my %name_to_host = &all_names();
                   8647: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8648: 	    my $ip;
                   8649: 	    if (!exists($name_to_ip{$name})) {
                   8650: 		$ip = gethostbyname($name);
                   8651: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8652: 		    if (defined($old_name_to_ip{$name})) {
                   8653: 			$ip = $old_name_to_ip{$name};
                   8654: 			&logthis("Can't find $name defaulting to old $ip");
                   8655: 		    } else {
                   8656: 			&logthis("Name $name no IP found");
                   8657: 			next;
                   8658: 		    }
                   8659: 		} else {
                   8660: 		    $ip=inet_ntoa($ip);
1.847     albertel 8661: 		}
                   8662: 		$name_to_ip{$name} = $ip;
                   8663: 	    } else {
                   8664: 		$ip = $name_to_ip{$name};
1.653     albertel 8665: 	    }
1.888     albertel 8666: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8667: 		$lonid_to_ip{$id} = $ip;
                   8668: 	    }
                   8669: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8670: 	}
1.869     albertel 8671: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8672: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8673: 				      48*60*60);
1.869     albertel 8674: 
1.847     albertel 8675: 	return %iphost;
1.598     albertel 8676:     }
                   8677: }
                   8678: 
1.862     albertel 8679: BEGIN {
                   8680: 
                   8681: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8682:     unless ($readit) {
                   8683: {
                   8684:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8685:     %perlvar = (%perlvar,%{$configvars});
                   8686: }
                   8687: 
                   8688: 
1.1       albertel 8689: # ------------------------------------------------------ Read spare server file
                   8690: {
1.448     albertel 8691:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8692: 
                   8693:     while (my $configline=<$config>) {
                   8694:        chomp($configline);
1.284     matthew  8695:        if ($configline) {
1.784     albertel 8696: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8697: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8698: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8699:        }
                   8700:     }
1.448     albertel 8701:     close($config);
1.1       albertel 8702: }
1.11      www      8703: # ------------------------------------------------------------ Read permissions
                   8704: {
1.448     albertel 8705:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8706: 
                   8707:     while (my $configline=<$config>) {
1.448     albertel 8708: 	chomp($configline);
                   8709: 	if ($configline) {
                   8710: 	    my ($role,$perm)=split(/ /,$configline);
                   8711: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8712: 	}
1.11      www      8713:     }
1.448     albertel 8714:     close($config);
1.11      www      8715: }
                   8716: 
                   8717: # -------------------------------------------- Read plain texts for permissions
                   8718: {
1.448     albertel 8719:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8720: 
                   8721:     while (my $configline=<$config>) {
1.448     albertel 8722: 	chomp($configline);
                   8723: 	if ($configline) {
1.742     raeburn  8724: 	    my ($short,@plain)=split(/:/,$configline);
                   8725:             %{$prp{$short}} = ();
                   8726: 	    if (@plain > 0) {
                   8727:                 $prp{$short}{'std'} = $plain[0];
                   8728:                 for (my $i=1; $i<@plain; $i++) {
                   8729:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8730:                 }
                   8731:             }
1.448     albertel 8732: 	}
1.135     www      8733:     }
1.448     albertel 8734:     close($config);
1.135     www      8735: }
                   8736: 
                   8737: # ---------------------------------------------------------- Read package table
                   8738: {
1.448     albertel 8739:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8740: 
                   8741:     while (my $configline=<$config>) {
1.483     albertel 8742: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8743: 	chomp($configline);
                   8744: 	my ($short,$plain)=split(/:/,$configline);
                   8745: 	my ($pack,$name)=split(/\&/,$short);
                   8746: 	if ($plain ne '') {
                   8747: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8748: 	    $packagetab{$short}=$plain; 
                   8749: 	}
1.11      www      8750:     }
1.448     albertel 8751:     close($config);
1.329     matthew  8752: }
                   8753: 
                   8754: # ------------- set up temporary directory
                   8755: {
                   8756:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8757: 
1.11      www      8758: }
                   8759: 
1.794     albertel 8760: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8761: 				'compress_threshold'=> 20_000,
                   8762:  			        });
1.185     www      8763: 
1.281     www      8764: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8765: $dumpcount=0;
1.22      www      8766: 
1.163     harris41 8767: &logtouch();
1.672     albertel 8768: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8769: $readit=1;
1.564     albertel 8770:     {
                   8771: 	use integer;
                   8772: 	my $test=(2**32)+1;
1.568     albertel 8773: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8774: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8775:     }
1.195     www      8776: }
1.1       albertel 8777: }
1.179     www      8778: 
1.1       albertel 8779: 1;
1.191     harris41 8780: __END__
                   8781: 
1.243     albertel 8782: =pod
                   8783: 
1.191     harris41 8784: =head1 NAME
                   8785: 
1.243     albertel 8786: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8787: 
                   8788: =head1 SYNOPSIS
                   8789: 
1.243     albertel 8790: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8791: 
                   8792:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8793: 
1.243     albertel 8794: Common parameters:
                   8795: 
                   8796: =over 4
                   8797: 
                   8798: =item *
                   8799: 
                   8800: $uname : an internal username (if $cname expecting a course Id specifically)
                   8801: 
                   8802: =item *
                   8803: 
                   8804: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8805: 
                   8806: =item *
                   8807: 
                   8808: $symb : a resource instance identifier
                   8809: 
                   8810: =item *
                   8811: 
                   8812: $namespace : the name of a .db file that contains the data needed or
                   8813: being set.
                   8814: 
                   8815: =back
                   8816: 
1.394     bowersj2 8817: =head1 OVERVIEW
1.191     harris41 8818: 
1.394     bowersj2 8819: lonnet provides subroutines which interact with the
                   8820: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8821: about classes, users, and resources.
1.243     albertel 8822: 
                   8823: For many of these objects you can also use this to store data about
                   8824: them or modify them in various ways.
1.191     harris41 8825: 
1.394     bowersj2 8826: =head2 Symbs
1.191     harris41 8827: 
1.394     bowersj2 8828: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8829: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8830: map, the resource number of the resource in the map, and the URL of
                   8831: the resource itself. The latter is somewhat redundant, but might help
                   8832: if maps change.
                   8833: 
                   8834: An example is
                   8835: 
                   8836:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8837: 
                   8838: The respective map entry is
                   8839: 
                   8840:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8841:   title="Problem 2">
                   8842:  </resource>
                   8843: 
                   8844: Symbs are used by the random number generator, as well as to store and
                   8845: restore data specific to a certain instance of for example a problem.
                   8846: 
                   8847: =head2 Storing And Retrieving Data
                   8848: 
                   8849: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8850: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8851: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8852: is is the non-critical message twin of cstore. These functions are for
                   8853: handlers to store a perl hash to a user's permanent data space in an
                   8854: easy manner, and to retrieve it again on another call. It is expected
                   8855: that a handler would use this once at the beginning to retrieve data,
                   8856: and then again once at the end to send only the new data back.
                   8857: 
                   8858: The data is stored in the user's data directory on the user's
                   8859: homeserver under the ID of the course.
                   8860: 
                   8861: The hash that is returned by restore will have all of the previous
                   8862: value for all of the elements of the hash.
                   8863: 
                   8864: Example:
                   8865: 
                   8866:  #creating a hash
                   8867:  my %hash;
                   8868:  $hash{'foo'}='bar';
                   8869: 
                   8870:  #storing it
                   8871:  &Apache::lonnet::cstore(\%hash);
                   8872: 
                   8873:  #changing a value
                   8874:  $hash{'foo'}='notbar';
                   8875: 
                   8876:  #adding a new value
                   8877:  $hash{'bar'}='foo';
                   8878:  &Apache::lonnet::cstore(\%hash);
                   8879: 
                   8880:  #retrieving the hash
                   8881:  my %history=&Apache::lonnet::restore();
                   8882: 
                   8883:  #print the hash
                   8884:  foreach my $key (sort(keys(%history))) {
                   8885:    print("\%history{$key} = $history{$key}");
                   8886:  }
                   8887: 
                   8888: Will print out:
1.191     harris41 8889: 
1.394     bowersj2 8890:  %history{1:foo} = bar
                   8891:  %history{1:keys} = foo:timestamp
                   8892:  %history{1:timestamp} = 990455579
                   8893:  %history{2:bar} = foo
                   8894:  %history{2:foo} = notbar
                   8895:  %history{2:keys} = foo:bar:timestamp
                   8896:  %history{2:timestamp} = 990455580
                   8897:  %history{bar} = foo
                   8898:  %history{foo} = notbar
                   8899:  %history{timestamp} = 990455580
                   8900:  %history{version} = 2
                   8901: 
                   8902: Note that the special hash entries C<keys>, C<version> and
                   8903: C<timestamp> were added to the hash. C<version> will be equal to the
                   8904: total number of versions of the data that have been stored. The
                   8905: C<timestamp> attribute will be the UNIX time the hash was
                   8906: stored. C<keys> is available in every historical section to list which
                   8907: keys were added or changed at a specific historical revision of a
                   8908: hash.
                   8909: 
                   8910: B<Warning>: do not store the hash that restore returns directly. This
                   8911: will cause a mess since it will restore the historical keys as if the
                   8912: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8913: 
1.394     bowersj2 8914: Calling convention:
1.191     harris41 8915: 
1.394     bowersj2 8916:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8917:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8918: 
1.394     bowersj2 8919: For more detailed information, see lonnet specific documentation.
1.191     harris41 8920: 
1.394     bowersj2 8921: =head1 RETURN MESSAGES
1.191     harris41 8922: 
1.394     bowersj2 8923: =over 4
1.191     harris41 8924: 
1.394     bowersj2 8925: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8926: 
1.394     bowersj2 8927: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8928: when the connection is brought back up
1.191     harris41 8929: 
1.394     bowersj2 8930: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8931: for later delivery
1.191     harris41 8932: 
1.394     bowersj2 8933: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8934: 
1.394     bowersj2 8935: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8936: that was requested
1.191     harris41 8937: 
1.243     albertel 8938: =back
1.191     harris41 8939: 
1.243     albertel 8940: =head1 PUBLIC SUBROUTINES
1.191     harris41 8941: 
1.243     albertel 8942: =head2 Session Environment Functions
1.191     harris41 8943: 
1.243     albertel 8944: =over 4
1.191     harris41 8945: 
1.394     bowersj2 8946: =item * 
                   8947: X<appenv()>
1.949     raeburn  8948: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 8949: the user envirnoment file, and will be restored for each access this
1.620     albertel 8950: user makes during this session, also modifies the %env for the current
1.949     raeburn  8951: process. Optional rolesarrayref - if defined contains a reference to an array
                   8952: of roles which are exempt from the restriction on modifying user.role entries 
                   8953: in the user's environment.db and in %env.    
1.191     harris41 8954: 
                   8955: =item *
1.394     bowersj2 8956: X<delenv()>
                   8957: B<delenv($regexp)>: removes all items from the session
                   8958: environment file that matches the regular expression in $regexp. The
1.620     albertel 8959: values are also delted from the current processes %env.
1.191     harris41 8960: 
1.795     albertel 8961: =item * get_env_multiple($name) 
                   8962: 
                   8963: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8964: values may be defined and end up as an array ref.
                   8965: 
                   8966: returns an array of values
                   8967: 
1.243     albertel 8968: =back
                   8969: 
                   8970: =head2 User Information
1.191     harris41 8971: 
1.243     albertel 8972: =over 4
1.191     harris41 8973: 
                   8974: =item *
1.394     bowersj2 8975: X<queryauthenticate()>
                   8976: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8977: authentication scheme
                   8978: 
                   8979: =item *
1.394     bowersj2 8980: X<authenticate()>
                   8981: B<authenticate($uname,$upass,$udom)>: try to
                   8982: authenticate user from domain's lib servers (first use the current
                   8983: one). C<$upass> should be the users password.
1.191     harris41 8984: 
                   8985: =item *
1.394     bowersj2 8986: X<homeserver()>
                   8987: B<homeserver($uname,$udom)>: find the server which has
                   8988: the user's directory and files (there must be only one), this caches
                   8989: the answer, and also caches if there is a borken connection.
1.191     harris41 8990: 
                   8991: =item *
1.394     bowersj2 8992: X<idget()>
                   8993: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8994: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8995: username, and only 1 username per ID in a specific domain) (returns
                   8996: hash: id=>name,id=>name)
1.191     harris41 8997: 
                   8998: =item *
1.394     bowersj2 8999: X<idrget()>
                   9000: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9001: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9002: 
                   9003: =item *
1.394     bowersj2 9004: X<idput()>
                   9005: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9006: 
                   9007: =item *
1.394     bowersj2 9008: X<rolesinit()>
                   9009: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9010: 
                   9011: =item *
1.551     albertel 9012: X<getsection()>
                   9013: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9014: course $cname, return section name/number or '' for "not in course"
                   9015: and '-1' for "no section"
                   9016: 
                   9017: =item *
1.394     bowersj2 9018: X<userenvironment()>
                   9019: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9020: passed in @what from the requested user's environment, returns a hash
                   9021: 
1.858     raeburn  9022: =item * 
                   9023: X<userlog_query()>
1.859     albertel 9024: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9025: activity.log file. %filters defines filters applied when parsing the
                   9026: log file. These can be start or end timestamps, or the type of action
                   9027: - log to look for Login or Logout events, check for Checkin or
                   9028: Checkout, role for role selection. The response is in the form
                   9029: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9030: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9031: 
1.243     albertel 9032: =back
                   9033: 
                   9034: =head2 User Roles
                   9035: 
                   9036: =over 4
                   9037: 
                   9038: =item *
                   9039: 
1.810     raeburn  9040: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9041:  F: full access
                   9042:  U,I,K: authentication modes (cxx only)
                   9043:  '': forbidden
                   9044:  1: user needs to choose course
                   9045:  2: browse allowed
1.766     albertel 9046:  A: passphrase authentication needed
1.243     albertel 9047: 
                   9048: =item *
                   9049: 
                   9050: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9051: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9052: and course level
                   9053: 
                   9054: =item *
                   9055: 
                   9056: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9057: explanation of a user role term
                   9058: 
1.832     raeburn  9059: =item *
                   9060: 
1.935     raeburn  9061: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9062: All arguments are optional. Returns a hash of a roles, either for
                   9063: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9064: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9065: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9066: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9067: For each key, value is set to colon-separated start and end times for
                   9068: the role.  If no username and domain are specified, will default to
1.934     raeburn  9069: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9070: of role statuses (active, future or previous), roles 
                   9071: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9072: to restrict the list of roles reported. If no array ref is 
                   9073: provided for types, will default to return only active roles.
1.834     albertel 9074: 
1.243     albertel 9075: =back
                   9076: 
                   9077: =head2 User Modification
                   9078: 
                   9079: =over 4
                   9080: 
                   9081: =item *
                   9082: 
1.957   ! raeburn  9083: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9084: user for the level given by URL.  Optional start and end dates (leave empty
                   9085: string or zero for "no date")
1.191     harris41 9086: 
                   9087: =item *
                   9088: 
1.243     albertel 9089: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9090: change a users, password, possible return values are: ok,
                   9091: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9092: refused
1.191     harris41 9093: 
                   9094: =item *
                   9095: 
1.243     albertel 9096: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9097: 
                   9098: =item *
                   9099: 
1.243     albertel 9100: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9101: modify user
1.191     harris41 9102: 
                   9103: =item *
                   9104: 
1.286     matthew  9105: modifystudent
                   9106: 
1.957   ! raeburn  9107: modify a student's enrollment and identification information.
1.286     matthew  9108: The course id is resolved based on the current users environment.  
                   9109: This means the envoking user must be a course coordinator or otherwise
                   9110: associated with a course.
                   9111: 
1.297     matthew  9112: This call is essentially a wrapper for lonnet::modifyuser and
                   9113: lonnet::modify_student_enrollment
1.286     matthew  9114: 
                   9115: Inputs: 
                   9116: 
                   9117: =over 4
                   9118: 
1.957   ! raeburn  9119: =item B<$udom> Student's loncapa domain
1.286     matthew  9120: 
1.957   ! raeburn  9121: =item B<$uname> Student's loncapa login name
1.286     matthew  9122: 
1.957   ! raeburn  9123: =item B<$uid> Student's id/student number
1.286     matthew  9124: 
1.957   ! raeburn  9125: =item B<$umode> Student's authentication mode
1.286     matthew  9126: 
1.957   ! raeburn  9127: =item B<$upass> Student's password
1.286     matthew  9128: 
1.957   ! raeburn  9129: =item B<$first> Student's first name
1.286     matthew  9130: 
1.957   ! raeburn  9131: =item B<$middle> Student's middle name
1.286     matthew  9132: 
1.957   ! raeburn  9133: =item B<$last> Student's last name
1.286     matthew  9134: 
1.957   ! raeburn  9135: =item B<$gene> Student's generation
1.286     matthew  9136: 
1.957   ! raeburn  9137: =item B<$usec> Student's section in course
1.286     matthew  9138: 
                   9139: =item B<$end> Unix time of the roles expiration
                   9140: 
                   9141: =item B<$start> Unix time of the roles start date
                   9142: 
                   9143: =item B<$forceid> If defined, allow $uid to be changed
                   9144: 
                   9145: =item B<$desiredhome> server to use as home server for student
                   9146: 
1.957   ! raeburn  9147: =item B<$email> Student's permanent e-mail address
        !          9148: 
        !          9149: =item B<$type> Type of enrollment (auto or manual)
        !          9150: 
        !          9151: =item B<$locktype>
        !          9152: 
        !          9153: =item B<$cid>
        !          9154: 
        !          9155: =item B<$selfenroll>
        !          9156: 
        !          9157: =item B<$context>
        !          9158: 
1.286     matthew  9159: =back
1.297     matthew  9160: 
                   9161: =item *
                   9162: 
                   9163: modify_student_enrollment
                   9164: 
                   9165: Change a students enrollment status in a class.  The environment variable
                   9166: 'role.request.course' must be defined for this function to proceed.
                   9167: 
                   9168: Inputs:
                   9169: 
                   9170: =over 4
                   9171: 
                   9172: =item $udom, students domain
                   9173: 
                   9174: =item $uname, students name
                   9175: 
                   9176: =item $uid, students user id
                   9177: 
                   9178: =item $first, students first name
                   9179: 
                   9180: =item $middle
                   9181: 
                   9182: =item $last
                   9183: 
                   9184: =item $gene
                   9185: 
                   9186: =item $usec
                   9187: 
                   9188: =item $end
                   9189: 
                   9190: =item $start
                   9191: 
1.957   ! raeburn  9192: =item $type
        !          9193: 
        !          9194: =item $locktype
        !          9195: 
        !          9196: =item $cid
        !          9197: 
        !          9198: =item $selfenroll
        !          9199: 
        !          9200: =item $context
        !          9201: 
1.297     matthew  9202: =back
                   9203: 
1.191     harris41 9204: 
                   9205: =item *
                   9206: 
1.243     albertel 9207: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9208: custom role; give a custom role to a user for the level given by URL.  Specify
                   9209: name and domain of role author, and role name
1.191     harris41 9210: 
                   9211: =item *
                   9212: 
1.243     albertel 9213: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9214: 
                   9215: =item *
                   9216: 
1.243     albertel 9217: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9218: 
                   9219: =back
                   9220: 
                   9221: =head2 Course Infomation
                   9222: 
                   9223: =over 4
1.191     harris41 9224: 
                   9225: =item *
                   9226: 
1.631     albertel 9227: coursedescription($courseid) : returns a hash of information about the
                   9228: specified course id, including all environment settings for the
                   9229: course, the description of the course will be in the hash under the
                   9230: key 'description'
1.191     harris41 9231: 
                   9232: =item *
                   9233: 
1.624     albertel 9234: resdata($name,$domain,$type,@which) : request for current parameter
                   9235: setting for a specific $type, where $type is either 'course' or 'user',
                   9236: @what should be a list of parameters to ask about. This routine caches
                   9237: answers for 5 minutes.
1.243     albertel 9238: 
1.877     foxr     9239: =item *
                   9240: 
                   9241: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9242: data base, returning a hash that is keyed by the resource name and has
                   9243: values that are the resource value.  I believe that the timestamps and
                   9244: versions are also returned.
                   9245: 
                   9246: 
1.243     albertel 9247: =back
                   9248: 
                   9249: =head2 Course Modification
                   9250: 
                   9251: =over 4
1.191     harris41 9252: 
                   9253: =item *
                   9254: 
1.243     albertel 9255: writecoursepref($courseid,%prefs) : write preferences (environment
                   9256: database) for a course
1.191     harris41 9257: 
                   9258: =item *
                   9259: 
1.243     albertel 9260: createcourse($udom,$description,$url) : make/modify course
                   9261: 
                   9262: =back
                   9263: 
                   9264: =head2 Resource Subroutines
                   9265: 
                   9266: =over 4
1.191     harris41 9267: 
                   9268: =item *
                   9269: 
1.243     albertel 9270: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9271: 
                   9272: =item *
                   9273: 
1.243     albertel 9274: repcopy($filename) : subscribes to the requested file, and attempts to
                   9275: replicate from the owning library server, Might return
1.607     raeburn  9276: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9277: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9278: resource. Expects the local filesystem pathname
                   9279: (/home/httpd/html/res/....)
                   9280: 
                   9281: =back
                   9282: 
                   9283: =head2 Resource Information
                   9284: 
                   9285: =over 4
1.191     harris41 9286: 
                   9287: =item *
                   9288: 
1.243     albertel 9289: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9290: a vairety of different possible values, $varname should be a request
                   9291: string, and the other parameters can be used to specify who and what
                   9292: one is asking about.
                   9293: 
                   9294: Possible values for $varname are environment.lastname (or other item
                   9295: from the envirnment hash), user.name (or someother aspect about the
                   9296: user), resource.0.maxtries (or some other part and parameter of a
                   9297: resource)
1.204     albertel 9298: 
                   9299: =item *
                   9300: 
1.243     albertel 9301: directcondval($number) : get current value of a condition; reads from a state
                   9302: string
1.204     albertel 9303: 
                   9304: =item *
                   9305: 
1.243     albertel 9306: condval($condidx) : value of condition index based on state
1.204     albertel 9307: 
                   9308: =item *
                   9309: 
1.243     albertel 9310: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9311: resource's metadata, $what should be either a specific key, or either
                   9312: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9313: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9314: 
                   9315: this function automatically caches all requests
1.191     harris41 9316: 
                   9317: =item *
                   9318: 
1.243     albertel 9319: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9320: network of library servers; returns file handle of where SQL and regex results
                   9321: will be stored for query
1.191     harris41 9322: 
                   9323: =item *
                   9324: 
1.243     albertel 9325: symbread($filename) : return symbolic list entry (filename argument optional);
                   9326: returns the data handle
1.191     harris41 9327: 
                   9328: =item *
                   9329: 
1.243     albertel 9330: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9331: a possible symb for the URL in $thisfn, and if is an encryypted
                   9332: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9333: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9334: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9335: 
1.191     harris41 9336: 
                   9337: =item *
                   9338: 
1.243     albertel 9339: symbclean($symb) : removes versions numbers from a symb, returns the
                   9340: cleaned symb
1.191     harris41 9341: 
                   9342: =item *
                   9343: 
1.243     albertel 9344: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9345: course map, user must be in a course for it to work.
1.191     harris41 9346: 
                   9347: =item *
                   9348: 
1.243     albertel 9349: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9350: 
                   9351: =item *
                   9352: 
1.243     albertel 9353: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9354: a random seed, all arguments are optional, if they aren't sent it uses the
                   9355: environment to derive them. Note: if symb isn't sent and it can't get one
                   9356: from &symbread it will use the current time as its return value
1.191     harris41 9357: 
                   9358: =item *
                   9359: 
1.243     albertel 9360: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9361: unfakeable, receipt
1.191     harris41 9362: 
                   9363: =item *
                   9364: 
1.620     albertel 9365: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9366: 
                   9367: =item *
                   9368: 
1.243     albertel 9369: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9370: 
                   9371: =item *
                   9372: 
1.243     albertel 9373: 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 9374: 
                   9375: =item *
                   9376: 
1.243     albertel 9377: 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 9378: 
                   9379: =item *
                   9380: 
1.243     albertel 9381: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9382: 
                   9383: =item *
                   9384: 
1.243     albertel 9385: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9386: forcing spreadsheet to reevaluate the resource scores next time.
                   9387: 
                   9388: =back
                   9389: 
                   9390: =head2 Storing/Retreiving Data
                   9391: 
                   9392: =over 4
1.191     harris41 9393: 
                   9394: =item *
                   9395: 
1.243     albertel 9396: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9397: for this url; hashref needs to be given and should be a \%hashname; the
                   9398: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9399: be derived from the env
1.191     harris41 9400: 
                   9401: =item *
                   9402: 
1.243     albertel 9403: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9404: uses critical subroutine
1.191     harris41 9405: 
                   9406: =item *
                   9407: 
1.243     albertel 9408: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9409: all args are optional
1.191     harris41 9410: 
                   9411: =item *
                   9412: 
1.717     albertel 9413: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9414: dumps the complete (or key matching regexp) namespace into a hash
                   9415: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9416: normally &store()ed into
                   9417: 
                   9418: $range should be either an integer '100' (give me the first 100
                   9419:                                            matching records)
                   9420:               or be  two integers sperated by a - with no spaces
                   9421:                  '30-50' (give me the 30th through the 50th matching
                   9422:                           records)
                   9423: 
                   9424: 
                   9425: =item *
                   9426: 
                   9427: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9428: replaces a &store() version of data with a replacement set of data
                   9429: for a particular resource in a namespace passed in the $storehash hash 
                   9430: reference
                   9431: 
                   9432: =item *
                   9433: 
1.243     albertel 9434: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9435: works very similar to store/cstore, but all data is stored in a
                   9436: temporary location and can be reset using tmpreset, $storehash should
                   9437: be a hash reference, returns nothing on success
1.191     harris41 9438: 
                   9439: =item *
                   9440: 
1.243     albertel 9441: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9442: similar to restore, but all data is stored in a temporary location and
                   9443: can be reset using tmpreset. Returns a hash of values on success,
                   9444: error string otherwise.
1.191     harris41 9445: 
                   9446: =item *
                   9447: 
1.243     albertel 9448: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9449: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9450: 
                   9451: =item *
                   9452: 
1.243     albertel 9453: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9454: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9455: 
                   9456: =item *
                   9457: 
1.243     albertel 9458: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9459: namesp ($udom and $uname are optional)
1.191     harris41 9460: 
                   9461: =item *
                   9462: 
1.702     albertel 9463: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9464: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9465: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9466: 
1.702     albertel 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)
1.449     matthew  9472: =item *
                   9473: 
                   9474: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9475: $store can be a scalar, an array reference, or if the amount to be 
                   9476: incremented is > 1, a hash reference.
                   9477: 
                   9478: ($udom and $uname are optional)
1.191     harris41 9479: 
                   9480: =item *
                   9481: 
1.243     albertel 9482: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9483: ($udom and $uname are optional)
1.191     harris41 9484: 
                   9485: =item *
                   9486: 
1.243     albertel 9487: cput($namespace,$storehash,$udom,$uname) : critical put
                   9488: ($udom and $uname are optional)
1.191     harris41 9489: 
                   9490: =item *
                   9491: 
1.748     albertel 9492: newput($namespace,$storehash,$udom,$uname) :
                   9493: 
                   9494: Attempts to store the items in the $storehash, but only if they don't
                   9495: currently exist, if this succeeds you can be certain that you have 
                   9496: successfully created a new key value pair in the $namespace db.
                   9497: 
                   9498: 
                   9499: Args:
                   9500:  $namespace: name of database to store values to
                   9501:  $storehash: hashref to store to the db
                   9502:  $udom: (optional) domain of user containing the db
                   9503:  $uname: (optional) name of user caontaining the db
                   9504: 
                   9505: Returns:
                   9506:  'ok' -> succeeded in storing all keys of $storehash
                   9507:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9508:                         least <key> already existed in the db (other
                   9509:                         requested keys may also already exist)
                   9510:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9511:  'con_lost' -> unable to contact request server
                   9512:  'refused' -> action was not allowed by remote machine
                   9513: 
                   9514: 
                   9515: =item *
                   9516: 
1.243     albertel 9517: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9518: reference filled in from namesp (encrypts the return communication)
                   9519: ($udom and $uname are optional)
1.191     harris41 9520: 
                   9521: =item *
                   9522: 
1.243     albertel 9523: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9524: critical subroutine
                   9525: 
1.806     raeburn  9526: =item *
                   9527: 
1.860     raeburn  9528: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9529: array reference filled in from namespace found in domain level on either
                   9530: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9531: 
                   9532: =item *
                   9533: 
1.860     raeburn  9534: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9535: domain level either on specified domain server ($uhome) or primary domain 
                   9536: server ($udom and $uhome are optional)
1.806     raeburn  9537: 
1.943     raeburn  9538: =item * 
                   9539: 
                   9540: get_domain_defaults($target_domain) : returns hash with defaults for
                   9541: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9542: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9543: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9544: Values are retrieved from cache (if current), or from domain's configuration.db
                   9545: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9546: or lonTabs/domain.tab. 
                   9547: 
                   9548: %domdefaults = &get_auth_defaults($target_domain);
                   9549: 
1.243     albertel 9550: =back
                   9551: 
                   9552: =head2 Network Status Functions
                   9553: 
                   9554: =over 4
1.191     harris41 9555: 
                   9556: =item *
                   9557: 
                   9558: dirlist($uri) : return directory list based on URI
                   9559: 
                   9560: =item *
                   9561: 
1.243     albertel 9562: spareserver() : find server with least workload from spare.tab
                   9563: 
                   9564: =back
                   9565: 
                   9566: =head2 Apache Request
                   9567: 
                   9568: =over 4
1.191     harris41 9569: 
                   9570: =item *
                   9571: 
1.243     albertel 9572: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9573: localhost, posts hash
                   9574: 
                   9575: =back
                   9576: 
                   9577: =head2 Data to String to Data
                   9578: 
                   9579: =over 4
1.191     harris41 9580: 
                   9581: =item *
                   9582: 
1.243     albertel 9583: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9584: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9585: 
                   9586: =item *
                   9587: 
1.243     albertel 9588: hashref2str($hashref) : convert a hashref into a string complete with
                   9589: escaping and '=' and '&' separators, supports elements that are
                   9590: arrayrefs and hashrefs
1.191     harris41 9591: 
                   9592: =item *
                   9593: 
1.243     albertel 9594: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9595: with escaping and '&' separators, supports elements that are arrayrefs
                   9596: and hashrefs
1.191     harris41 9597: 
                   9598: =item *
                   9599: 
1.243     albertel 9600: str2hash($string) : convert string to hash using unescaping and
                   9601: splitting on '=' and '&', supports elements that are arrayrefs and
                   9602: hashrefs
1.191     harris41 9603: 
                   9604: =item *
                   9605: 
1.243     albertel 9606: str2array($string) : convert string to hash using unescaping and
                   9607: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9608: 
                   9609: =back
                   9610: 
                   9611: =head2 Logging Routines
                   9612: 
                   9613: =over 4
                   9614: 
                   9615: These routines allow one to make log messages in the lonnet.log and
                   9616: lonnet.perm logfiles.
1.191     harris41 9617: 
                   9618: =item *
                   9619: 
1.243     albertel 9620: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9621: 
                   9622: =item *
                   9623: 
1.243     albertel 9624: logthis() : append message to the normal lonnet.log file, it gets
                   9625: preiodically rolled over and deleted.
1.191     harris41 9626: 
                   9627: =item *
                   9628: 
1.243     albertel 9629: logperm() : append a permanent message to lonnet.perm.log, this log
                   9630: file never gets deleted by any automated portion of the system, only
                   9631: messages of critical importance should go in here.
                   9632: 
                   9633: =back
                   9634: 
                   9635: =head2 General File Helper Routines
                   9636: 
                   9637: =over 4
1.191     harris41 9638: 
                   9639: =item *
                   9640: 
1.481     raeburn  9641: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9642: (a) files in /uploaded
                   9643:   (i) If a local copy of the file exists - 
                   9644:       compares modification date of local copy with last-modified date for 
                   9645:       definitive version stored on home server for course. If local copy is 
                   9646:       stale, requests a new version from the home server and stores it. 
                   9647:       If the original has been removed from the home server, then local copy 
                   9648:       is unlinked.
                   9649:   (ii) If local copy does not exist -
                   9650:       requests the file from the home server and stores it. 
                   9651:   
                   9652:   If $caller is 'uploadrep':  
                   9653:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9654:     for request for files originally uploaded via DOCS. 
                   9655:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9656:   
                   9657:   Otherwise:
                   9658:      This indicates a call from the content generation phase of the request.
                   9659:      -  returns the entire contents of the file or -1.
                   9660:      
                   9661: (b) files in /res
                   9662:    - returns the entire contents of a file or -1; 
                   9663:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9664: 
1.712     albertel 9665: 
                   9666: =item *
                   9667: 
                   9668: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9669:                   reference
                   9670: 
                   9671: returns either a stat() list of data about the file or an empty list
                   9672: if the file doesn't exist or couldn't find out about it (connection
                   9673: problems or user unknown)
                   9674: 
1.191     harris41 9675: =item *
                   9676: 
1.243     albertel 9677: filelocation($dir,$file) : returns file system location of a file
                   9678: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9679: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9680: and a file of ../bob will become /a/bob)
1.191     harris41 9681: 
                   9682: =item *
                   9683: 
                   9684: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9685: filelocation except for hrefs
                   9686: 
                   9687: =item *
                   9688: 
                   9689: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9690: 
1.243     albertel 9691: =back
                   9692: 
1.608     albertel 9693: =head2 Usererfile file routines (/uploaded*)
                   9694: 
                   9695: =over 4
                   9696: 
                   9697: =item *
                   9698: 
                   9699: userfileupload(): main rotine for putting a file in a user or course's
                   9700:                   filespace, arguments are,
                   9701: 
1.620     albertel 9702:  formname - required - this is the name of the element in $env where the
1.608     albertel 9703:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9704:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9705:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9706:  coursedoc - if true, store the file in the course of the active role
                   9707:              of the current user
                   9708:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9709:          if undefined, it will be placed in "unknown"
                   9710: 
                   9711:  (This routine calls clean_filename() to remove any dangerous
                   9712:  characters from the filename, and then calls finuserfileupload() to
                   9713:  complete the transaction)
                   9714: 
                   9715:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9716:  and /adm/notfound.html if unsuccessful
                   9717: 
                   9718: =item *
                   9719: 
                   9720: clean_filename(): routine for cleaing a filename up for storage in
                   9721:                  userfile space, argument is:
                   9722: 
                   9723:  filename - proposed filename
                   9724: 
                   9725: returns: the new clean filename
                   9726: 
                   9727: =item *
                   9728: 
                   9729: finishuserfileupload(): routine that creaes and sends the file to
                   9730: userspace, probably shouldn't be called directly
                   9731: 
                   9732:   docuname: username or courseid of destination for the file
                   9733:   docudom: domain of user/course of destination for the file
                   9734:   formname: same as for userfileupload()
                   9735:   fname: filename (inculding subdirectories) for the file
                   9736: 
                   9737:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9738:  and /adm/notfound.html if unsuccessful
                   9739: 
                   9740: =item *
                   9741: 
                   9742: renameuserfile(): renames an existing userfile to a new name
                   9743: 
                   9744:   Args:
                   9745:    docuname: username or courseid of destination for the file
                   9746:    docudom: domain of user/course of destination for the file
                   9747:    old: current file name (including any subdirs under userfiles)
                   9748:    new: desired file name (including any subdirs under userfiles)
                   9749: 
                   9750: =item *
                   9751: 
                   9752: mkdiruserfile(): creates a directory is a userfiles dir
                   9753: 
                   9754:   Args:
                   9755:    docuname: username or courseid of destination for the file
                   9756:    docudom: domain of user/course of destination for the file
                   9757:    dir: dir to create (including any subdirs under userfiles)
                   9758: 
                   9759: =item *
                   9760: 
                   9761: removeuserfile(): removes a file that exists in userfiles
                   9762: 
                   9763:   Args:
                   9764:    docuname: username or courseid of destination for the file
                   9765:    docudom: domain of user/course of destination for the file
                   9766:    fname: filname to delete (including any subdirs under userfiles)
                   9767: 
                   9768: =item *
                   9769: 
                   9770: removeuploadedurl(): convience function for removeuserfile()
                   9771: 
                   9772:   Args:
                   9773:    url:  a full /uploaded/... url to delete
                   9774: 
1.747     albertel 9775: =item * 
                   9776: 
                   9777: get_portfile_permissions():
                   9778:   Args:
                   9779:     domain: domain of user or course contain the portfolio files
                   9780:     user: name of user or num of course contain the portfolio files
                   9781:   Returns:
                   9782:     hashref of a dump of the proper file_permissions.db
                   9783:    
                   9784: 
                   9785: =item * 
                   9786: 
                   9787: get_access_controls():
                   9788: 
                   9789: Args:
                   9790:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9791:   group: (optional) the group you want the files associated with
                   9792:   file: (optional) the file you want access info on
                   9793: 
                   9794: Returns:
1.749     raeburn  9795:     a hash (keys are file names) of hashes containing
                   9796:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9797:         values are XML containing access control settings (see below) 
1.747     albertel 9798: 
                   9799: Internal notes:
                   9800: 
1.749     raeburn  9801:  access controls are stored in file_permissions.db as key=value pairs.
                   9802:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9803:         where scope -> public,guest,course,group,domains or users.
                   9804:               end -> UNIX time for end of access (0 -> no end date)
                   9805:               start -> UNIX time for start of access
                   9806: 
                   9807:     value -> XML description of access control
                   9808:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9809:             <start></start>
                   9810:             <end></end>
                   9811: 
                   9812:             <password></password>  for scope type = guest
                   9813: 
                   9814:             <domain></domain>     for scope type = course or group
                   9815:             <number></number>
                   9816:             <roles id="">
                   9817:              <role></role>
                   9818:              <access></access>
                   9819:              <section></section>
                   9820:              <group></group>
                   9821:             </roles>
                   9822: 
                   9823:             <dom></dom>         for scope type = domains
                   9824: 
                   9825:             <users>             for scope type = users
                   9826:              <user>
                   9827:               <uname></uname>
                   9828:               <udom></udom>
                   9829:              </user>
                   9830:             </users>
                   9831:            </scope> 
                   9832:               
                   9833:  Access data is also aggregated for each file in an additional key=value pair:
                   9834:  key -> path to file/file_name\0accesscontrol 
                   9835:  value -> reference to hash
                   9836:           hash contains key = value pairs
                   9837:           where key = uniqueID:scope_end_start
                   9838:                 value = UNIX time record was last updated
                   9839: 
                   9840:           Used to improve speed of look-ups of access controls for each file.  
                   9841:  
                   9842:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9843: 
                   9844: modify_access_controls():
                   9845: 
                   9846: Modifies access controls for a portfolio file
                   9847: Args
                   9848: 1. file name
                   9849: 2. reference to hash of required changes,
                   9850: 3. domain
                   9851: 4. username
                   9852:   where domain,username are the domain of the portfolio owner 
                   9853:   (either a user or a course) 
                   9854: 
                   9855: Returns:
                   9856: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9857: 2. result of deletions ('ok' or 'error', with error message).
                   9858: 3. reference to hash of any new or updated access controls.
                   9859: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9860:    key = integer (inbound ID)
                   9861:    value = uniqueID  
1.747     albertel 9862: 
1.608     albertel 9863: =back
                   9864: 
1.243     albertel 9865: =head2 HTTP Helper Routines
                   9866: 
                   9867: =over 4
                   9868: 
1.191     harris41 9869: =item *
                   9870: 
                   9871: escape() : unpack non-word characters into CGI-compatible hex codes
                   9872: 
                   9873: =item *
                   9874: 
                   9875: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9876: 
1.243     albertel 9877: =back
                   9878: 
                   9879: =head1 PRIVATE SUBROUTINES
                   9880: 
                   9881: =head2 Underlying communication routines (Shouldn't call)
                   9882: 
                   9883: =over 4
                   9884: 
                   9885: =item *
                   9886: 
                   9887: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9888: 
                   9889: =item *
                   9890: 
                   9891: reply() : uses subreply to send a message to remote machine, logs all failures
                   9892: 
                   9893: =item *
                   9894: 
                   9895: critical() : passes a critical message to another server; if cannot
                   9896: get through then place message in connection buffer directory and
                   9897: returns con_delayed, if incapable of saving message, returns
                   9898: con_failed
                   9899: 
                   9900: =item *
                   9901: 
                   9902: reconlonc() : tries to reconnect lonc client processes.
                   9903: 
                   9904: =back
                   9905: 
                   9906: =head2 Resource Access Logging
                   9907: 
                   9908: =over 4
                   9909: 
                   9910: =item *
                   9911: 
                   9912: flushcourselogs() : flush (save) buffer logs and access logs
                   9913: 
                   9914: =item *
                   9915: 
                   9916: courselog($what) : save message for course in hash
                   9917: 
                   9918: =item *
                   9919: 
                   9920: courseacclog($what) : save message for course using &courselog().  Perform
                   9921: special processing for specific resource types (problems, exams, quizzes, etc).
                   9922: 
1.191     harris41 9923: =item *
                   9924: 
                   9925: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9926: as a PerlChildExitHandler
1.243     albertel 9927: 
                   9928: =back
                   9929: 
                   9930: =head2 Other
                   9931: 
                   9932: =over 4
                   9933: 
                   9934: =item *
                   9935: 
                   9936: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9937: 
                   9938: =back
                   9939: 
                   9940: =cut
1.877     foxr     9941: 

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