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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.963   ! raeburn     4: # $Id: lonnet.pm,v 1.962 2008/06/26 19:54:19 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        42:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
1.957     raeburn    91: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                     92:         if (($cnum eq '') || ($cdom eq '')) {
                     93:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                     94:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                     95:         }
1.729     www        96: 	$logid++;
1.957     raeburn    97:         my $now = time();
                     98: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www        99: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       100: 				    { $id => {
                    101: 					'exe_uname' => $env{'user.name'},
                    102: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   103: 					'exe_time'  => $now,
1.730     www       104: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    105: 					'delflag'   => $delflag,
                    106: 					'logentry'  => $storehash,
                    107: 					'uname'     => $uname,
                    108: 					'udom'      => $udom,
                    109: 				    }
1.957     raeburn   110: 				  },$cdom,$cnum);
1.729     www       111:     }
                    112: }
1.1       albertel  113: 
1.163     harris41  114: sub logtouch {
                    115:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  116:     unless (-e "$execdir/logs/lonnet.log") {	
                    117: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  118: 	close $fh;
                    119:     }
                    120:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    121:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    122: }
                    123: 
1.1       albertel  124: sub logthis {
                    125:     my $message=shift;
                    126:     my $execdir=$perlvar{'lonDaemons'};
                    127:     my $now=time;
                    128:     my $local=localtime($now);
1.448     albertel  129:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    130: 	print $fh "$local ($$): $message\n";
                    131: 	close($fh);
                    132:     }
1.1       albertel  133:     return 1;
                    134: }
                    135: 
                    136: sub logperm {
                    137:     my $message=shift;
                    138:     my $execdir=$perlvar{'lonDaemons'};
                    139:     my $now=time;
                    140:     my $local=localtime($now);
1.448     albertel  141:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    142: 	print $fh "$now:$message:$local\n";
                    143: 	close($fh);
                    144:     }
1.1       albertel  145:     return 1;
                    146: }
                    147: 
1.850     albertel  148: sub create_connection {
1.853     albertel  149:     my ($hostname,$lonid) = @_;
1.851     albertel  150:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  151: 				     Type    => SOCK_STREAM,
                    152: 				     Timeout => 10);
                    153:     return 0 if (!$client);
1.890     albertel  154:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  155:     my $result = <$client>;
                    156:     chomp($result);
                    157:     return 1 if ($result eq 'done');
                    158:     return 0;
                    159: }
                    160: 
                    161: 
1.1       albertel  162: # -------------------------------------------------- Non-critical communication
                    163: sub subreply {
                    164:     my ($cmd,$server)=@_;
1.838     albertel  165:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      166:     #
                    167:     #  With loncnew process trimming, there's a timing hole between lonc server
                    168:     #  process exit and the master server picking up the listen on the AF_UNIX
                    169:     #  socket.  In that time interval, a lock file will exist:
                    170: 
                    171:     my $lockfile=$peerfile.".lock";
                    172:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    173: 	sleep(1);
                    174:     }
                    175:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      176:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      177:     #
1.550     foxr      178:     #   We'll give the connection a few tries before abandoning it.  If
                    179:     #   connection is not possible, we'll con_lost back to the client.
                    180:     #   
                    181:     my $client;
                    182:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    183: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    184: 				      Type    => SOCK_STREAM,
                    185: 				      Timeout => 10);
1.869     albertel  186: 	if ($client) {
1.550     foxr      187: 	    last;		# Connected!
1.850     albertel  188: 	} else {
1.853     albertel  189: 	    &create_connection(&hostname($server),$server);
1.550     foxr      190: 	}
1.850     albertel  191:         sleep(1);		# Try again later if failed connection.
1.550     foxr      192:     }
                    193:     my $answer;
                    194:     if ($client) {
1.704     albertel  195: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      196: 	$answer=<$client>;
                    197: 	if (!$answer) { $answer="con_lost"; }
                    198: 	chomp($answer);
                    199:     } else {
                    200: 	$answer = 'con_lost';	# Failed connection.
                    201:     }
1.1       albertel  202:     return $answer;
                    203: }
                    204: 
                    205: sub reply {
                    206:     my ($cmd,$server)=@_;
1.838     albertel  207:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  208:     my $answer=subreply($cmd,$server);
1.65      www       209:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  210:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       211:                 " $cmd to $server returned $answer</font>");
                    212:     }
1.1       albertel  213:     return $answer;
                    214: }
                    215: 
                    216: # ----------------------------------------------------------- Send USR1 to lonc
                    217: 
                    218: sub reconlonc {
1.891     albertel  219:     my ($lonid) = @_;
                    220:     my $hostname = &hostname($lonid);
                    221:     if ($lonid) {
                    222: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    223: 	if ($hostname && -e $peerfile) {
                    224: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    225: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    226: 					     Type    => SOCK_STREAM,
                    227: 					     Timeout => 10);
                    228: 	    if ($client) {
                    229: 		print $client ("reset_retries\n");
                    230: 		my $answer=<$client>;
                    231: 		#reset just this one.
                    232: 	    }
                    233: 	}
                    234: 	return;
                    235:     }
                    236: 
1.836     www       237:     &logthis("Trying to reconnect lonc");
1.1       albertel  238:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  239:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  240: 	my $loncpid=<$fh>;
                    241:         chomp($loncpid);
                    242:         if (kill 0 => $loncpid) {
                    243: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    244:             kill USR1 => $loncpid;
                    245:             sleep 1;
1.836     www       246:          } else {
1.12      www       247: 	    &logthis(
1.672     albertel  248:                "<font color=\"blue\">WARNING:".
1.12      www       249:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  250:         }
                    251:     } else {
1.836     www       252: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  253:     }
                    254: }
                    255: 
                    256: # ------------------------------------------------------ Critical communication
1.12      www       257: 
1.1       albertel  258: sub critical {
                    259:     my ($cmd,$server)=@_;
1.838     albertel  260:     unless (&hostname($server)) {
1.672     albertel  261:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       262:                " Critical message to unknown server ($server)</font>");
                    263:         return 'no_such_host';
                    264:     }
1.1       albertel  265:     my $answer=reply($cmd,$server);
                    266:     if ($answer eq 'con_lost') {
                    267: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  268: 	my $answer=reply($cmd,$server);
1.1       albertel  269:         if ($answer eq 'con_lost') {
                    270:             my $now=time;
                    271:             my $middlename=$cmd;
1.5       www       272:             $middlename=substr($middlename,0,16);
1.1       albertel  273:             $middlename=~s/\W//g;
                    274:             my $dfilename=
1.305     www       275:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    276:             $dumpcount++;
1.1       albertel  277:             {
1.448     albertel  278: 		my $dfh;
                    279: 		if (open($dfh,">$dfilename")) {
                    280: 		    print $dfh "$cmd\n"; 
                    281: 		    close($dfh);
                    282: 		}
1.1       albertel  283:             }
                    284:             sleep 2;
                    285:             my $wcmd='';
                    286:             {
1.448     albertel  287: 		my $dfh;
                    288: 		if (open($dfh,"<$dfilename")) {
                    289: 		    $wcmd=<$dfh>; 
                    290: 		    close($dfh);
                    291: 		}
1.1       albertel  292:             }
                    293:             chomp($wcmd);
1.7       www       294:             if ($wcmd eq $cmd) {
1.672     albertel  295: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       296:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  297:                 &logperm("D:$server:$cmd");
                    298: 	        return 'con_delayed';
                    299:             } else {
1.672     albertel  300:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       301:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  302:                 &logperm("F:$server:$cmd");
                    303:                 return 'con_failed';
                    304:             }
                    305:         }
                    306:     }
                    307:     return $answer;
1.405     albertel  308: }
                    309: 
1.755     albertel  310: # ------------------------------------------- check if return value is an error
                    311: 
                    312: sub error {
                    313:     my ($result) = @_;
1.756     albertel  314:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  315: 	if ($2 == 2) { return undef; }
                    316: 	return $1;
                    317:     }
                    318:     return undef;
                    319: }
                    320: 
1.783     albertel  321: sub convert_and_load_session_env {
                    322:     my ($lonidsdir,$handle)=@_;
                    323:     my @profile;
                    324:     {
1.917     albertel  325: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    326: 	if (!$opened) {
1.915     albertel  327: 	    return 0;
                    328: 	}
1.783     albertel  329: 	flock($idf,LOCK_SH);
                    330: 	@profile=<$idf>;
                    331: 	close($idf);
                    332:     }
                    333:     my %temp_env;
                    334:     foreach my $line (@profile) {
1.786     albertel  335: 	if ($line !~ m/=/) {
                    336: 	    return 0;
                    337: 	}
1.783     albertel  338: 	chomp($line);
                    339: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    340: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    341:     }
                    342:     unlink("$lonidsdir/$handle.id");
                    343:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    344: 	    0640)) {
                    345: 	%disk_env = %temp_env;
                    346: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    347: 	untie(%disk_env);
                    348:     }
1.786     albertel  349:     return 1;
1.783     albertel  350: }
                    351: 
1.374     www       352: # ------------------------------------------- Transfer profile into environment
1.780     albertel  353: my $env_loaded;
                    354: sub transfer_profile_to_env {
1.788     albertel  355:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    356:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       357: 
1.720     albertel  358:     if (!defined($lonidsdir)) {
                    359: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    360:     }
                    361:     if (!defined($handle)) {
                    362:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    363:     }
                    364: 
1.786     albertel  365:     my $convert;
                    366:     {
1.917     albertel  367:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    368: 	if (!$opened) {
1.915     albertel  369: 	    return;
                    370: 	}
1.786     albertel  371: 	flock($idf,LOCK_SH);
                    372: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    373: 		&GDBM_READER(),0640)) {
                    374: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    375: 	    untie(%disk_env);
                    376: 	} else {
                    377: 	    $convert = 1;
                    378: 	}
                    379:     }
                    380:     if ($convert) {
                    381: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    382: 	    &logthis("Failed to load session, or convert session.");
                    383: 	}
1.374     www       384:     }
1.783     albertel  385: 
1.786     albertel  386:     my %remove;
1.783     albertel  387:     while ( my $envname = each(%env) ) {
1.433     matthew   388:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    389:             if ($time < time-300) {
1.783     albertel  390:                 $remove{$key}++;
1.433     matthew   391:             }
                    392:         }
                    393:     }
1.783     albertel  394: 
1.619     albertel  395:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  396:     $env_loaded=1;
1.783     albertel  397:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   398:         &delenv($expired_key);
1.374     www       399:     }
1.1       albertel  400: }
                    401: 
1.916     albertel  402: # ---------------------------------------------------- Check for valid session 
                    403: sub check_for_valid_session {
                    404:     my ($r) = @_;
                    405:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    406:     my $lonid=$cookies{'lonID'};
                    407:     return undef if (!$lonid);
                    408: 
                    409:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    410:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    411:     return undef if (!-e "$lonidsdir/$handle.id");
                    412: 
1.917     albertel  413:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    414:     return undef if (!$opened);
1.916     albertel  415: 
                    416:     flock($idf,LOCK_SH);
                    417:     my %disk_env;
                    418:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    419: 	    &GDBM_READER(),0640)) {
                    420: 	return undef;	
                    421:     }
                    422: 
                    423:     if (!defined($disk_env{'user.name'})
                    424: 	|| !defined($disk_env{'user.domain'})) {
                    425: 	return undef;
                    426:     }
                    427:     return $handle;
                    428: }
                    429: 
1.830     albertel  430: sub timed_flock {
                    431:     my ($file,$lock_type) = @_;
                    432:     my $failed=0;
                    433:     eval {
                    434: 	local $SIG{__DIE__}='DEFAULT';
                    435: 	local $SIG{ALRM}=sub {
                    436: 	    $failed=1;
                    437: 	    die("failed lock");
                    438: 	};
                    439: 	alarm(13);
                    440: 	flock($file,$lock_type);
                    441: 	alarm(0);
                    442:     };
                    443:     if ($failed) {
                    444: 	return undef;
                    445:     } else {
                    446: 	return 1;
                    447:     }
                    448: }
                    449: 
1.5       www       450: # ---------------------------------------------------------- Append Environment
                    451: 
                    452: sub appenv {
1.949     raeburn   453:     my ($newenv,$roles) = @_;
                    454:     if (ref($newenv) eq 'HASH') {
                    455:         foreach my $key (keys(%{$newenv})) {
                    456:             my $refused = 0;
                    457: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    458:                 $refused = 1;
                    459:                 if (ref($roles) eq 'ARRAY') {
                    460:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    461:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    462:                         $refused = 0;
                    463:                     }
                    464:                 }
                    465:             }
                    466:             if ($refused) {
                    467:                 &logthis("<font color=\"blue\">WARNING: ".
                    468:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    469:                          .'</font>');
                    470: 	        delete($newenv->{$key});
                    471:             } else {
                    472:                 $env{$key}=$newenv->{$key};
                    473:             }
                    474:         }
                    475:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    476:         if ($opened
                    477: 	    && &timed_flock($env_file,LOCK_EX)
                    478: 	    &&
                    479: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    480: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    481: 	    while (my ($key,$value) = each(%{$newenv})) {
                    482: 	        $disk_env{$key} = $value;
                    483: 	    }
                    484: 	    untie(%disk_env);
1.35      www       485:         }
1.191     harris41  486:     }
1.56      www       487:     return 'ok';
                    488: }
                    489: # ----------------------------------------------------- Delete from Environment
                    490: 
                    491: sub delenv {
                    492:     my $delthis=shift;
                    493:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  494:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       495:                 "Attempt to delete from environment ".$delthis);
                    496:         return 'error';
                    497:     }
1.917     albertel  498:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    499:     if ($opened
1.915     albertel  500: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  501: 	&&
                    502: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    503: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  504: 	foreach my $key (keys(%disk_env)) {
                    505: 	    if ($key=~/^$delthis/) { 
1.915     albertel  506: 		delete($env{$key});
                    507: 		delete($disk_env{$key});
                    508: 	    }
1.448     albertel  509: 	}
1.783     albertel  510: 	untie(%disk_env);
1.5       www       511:     }
                    512:     return 'ok';
1.369     albertel  513: }
                    514: 
1.790     albertel  515: sub get_env_multiple {
                    516:     my ($name) = @_;
                    517:     my @values;
                    518:     if (defined($env{$name})) {
                    519:         # exists is it an array
                    520:         if (ref($env{$name})) {
                    521:             @values=@{ $env{$name} };
                    522:         } else {
                    523:             $values[0]=$env{$name};
                    524:         }
                    525:     }
                    526:     return(@values);
                    527: }
                    528: 
1.958     www       529: # ------------------------------------------------------------------- Locking
                    530: 
                    531: sub set_lock {
                    532:     my ($text)=@_;
                    533:     $locknum++;
                    534:     my $id=$$.'-'.$locknum;
                    535:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    536:              'session.lock.'.$id => $text});
                    537:     return $id;
                    538: }
                    539: 
                    540: sub get_locks {
                    541:     my $num=0;
                    542:     my %texts=();
                    543:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    544:        if ($lock=~/\w/) {
                    545:           $num++;
                    546:           $texts{$lock}=$env{'session.lock.'.$lock};
                    547:        }
                    548:    }
                    549:    return ($num,%texts);
                    550: }
                    551: 
                    552: sub remove_lock {
                    553:     my ($id)=@_;
                    554:     my $newlocks='';
                    555:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    556:        if (($lock=~/\w/) && ($lock ne $id)) {
                    557:           $newlocks.=','.$lock;
                    558:        }
                    559:     }
                    560:     &appenv({'session.locks' => $newlocks});
                    561:     &delenv('session.lock.'.$id);
                    562: }
                    563: 
                    564: sub remove_all_locks {
                    565:     my $activelocks=$env{'session.locks'};
                    566:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    567:        if ($lock=~/\w/) {
                    568:           &remove_lock($lock);
                    569:        }
                    570:     }
                    571: }
                    572: 
                    573: 
1.369     albertel  574: # ------------------------------------------ Find out current server userload
                    575: sub userload {
                    576:     my $numusers=0;
                    577:     {
                    578: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    579: 	my $filename;
                    580: 	my $curtime=time;
                    581: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  582: 	    next if ($filename eq '.' || $filename eq '..');
                    583: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  584: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  585: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  586: 	}
                    587: 	closedir(LONIDS);
                    588:     }
                    589:     my $userloadpercent=0;
                    590:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    591:     if ($maxuserload) {
1.371     albertel  592: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  593:     }
1.372     albertel  594:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  595:     return $userloadpercent;
1.283     www       596: }
                    597: 
                    598: # ------------------------------------------ Fight off request when overloaded
                    599: 
                    600: sub overloaderror {
                    601:     my ($r,$checkserver)=@_;
                    602:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    603:     my $loadavg;
                    604:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  605:        open(my $loadfile,'/proc/loadavg');
1.283     www       606:        $loadavg=<$loadfile>;
                    607:        $loadavg =~ s/\s.*//g;
1.285     matthew   608:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  609:        close($loadfile);
1.283     www       610:     } else {
                    611:        $loadavg=&reply('load',$checkserver);
                    612:     }
1.285     matthew   613:     my $overload=$loadavg-100;
1.283     www       614:     if ($overload>0) {
1.285     matthew   615: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       616:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       617:         return 413;
1.283     www       618:     }    
                    619:     return '';
1.5       www       620: }
1.1       albertel  621: 
                    622: # ------------------------------ Find server with least workload from spare.tab
1.11      www       623: 
1.1       albertel  624: sub spareserver {
1.670     albertel  625:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  626:     my $spare_server;
1.370     albertel  627:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  628:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    629:                                                      :  $userloadpercent;
                    630:     
                    631:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    632: 	($spare_server, $lowest_load) =
                    633: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    634:     }
                    635: 
                    636:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    637: 
                    638:     if (!$found_server) {
                    639: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    640: 	    ($spare_server, $lowest_load) =
                    641: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    642: 	}
                    643:     }
                    644: 
                    645:     if (!$want_server_name) {
1.838     albertel  646: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  647:     }
                    648:     return $spare_server;
                    649: }
                    650: 
                    651: sub compare_server_load {
                    652:     my ($try_server, $spare_server, $lowest_load) = @_;
                    653: 
                    654:     my $loadans     = &reply('load',    $try_server);
                    655:     my $userloadans = &reply('userload',$try_server);
                    656: 
                    657:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    658: 	next; #didn't get a number from the server
                    659:     }
                    660: 
                    661:     my $load;
                    662:     if ($loadans =~ /\d/) {
                    663: 	if ($userloadans =~ /\d/) {
                    664: 	    #both are numbers, pick the bigger one
                    665: 	    $load = ($loadans > $userloadans) ? $loadans 
                    666: 		                              : $userloadans;
1.411     albertel  667: 	} else {
1.784     albertel  668: 	    $load = $loadans;
1.411     albertel  669: 	}
1.784     albertel  670:     } else {
                    671: 	$load = $userloadans;
                    672:     }
                    673: 
                    674:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    675: 	$spare_server = $try_server;
                    676: 	$lowest_load  = $load;
1.370     albertel  677:     }
1.784     albertel  678:     return ($spare_server,$lowest_load);
1.202     matthew   679: }
1.914     albertel  680: 
                    681: # --------------------------- ask offload servers if user already has a session
                    682: sub find_existing_session {
                    683:     my ($udom,$uname) = @_;
                    684:     foreach my $try_server (@{ $spareid{'primary'} },
                    685: 			    @{ $spareid{'default'} }) {
                    686: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    687:     }
                    688:     return;
                    689: }
                    690: 
                    691: # -------------------------------- ask if server already has a session for user
                    692: sub has_user_session {
                    693:     my ($lonid,$udom,$uname) = @_;
                    694:     my $result = &reply(join(':','userhassession',
                    695: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    696:     return 1 if ($result eq 'ok');
                    697: 
                    698:     return 0;
                    699: }
                    700: 
1.202     matthew   701: # --------------------------------------------- Try to change a user's password
                    702: 
                    703: sub changepass {
1.799     raeburn   704:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   705:     $currentpass = &escape($currentpass);
                    706:     $newpass     = &escape($newpass);
1.799     raeburn   707:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   708: 		       $server);
                    709:     if (! $answer) {
                    710: 	&logthis("No reply on password change request to $server ".
                    711: 		 "by $uname in domain $udom.");
                    712:     } elsif ($answer =~ "^ok") {
                    713:         &logthis("$uname in $udom successfully changed their password ".
                    714: 		 "on $server.");
                    715:     } elsif ($answer =~ "^pwchange_failure") {
                    716: 	&logthis("$uname in $udom was unable to change their password ".
                    717: 		 "on $server.  The action was blocked by either lcpasswd ".
                    718: 		 "or pwchange");
                    719:     } elsif ($answer =~ "^non_authorized") {
                    720:         &logthis("$uname in $udom did not get their password correct when ".
                    721: 		 "attempting to change it on $server.");
                    722:     } elsif ($answer =~ "^auth_mode_error") {
                    723:         &logthis("$uname in $udom attempted to change their password despite ".
                    724: 		 "not being locally or internally authenticated on $server.");
                    725:     } elsif ($answer =~ "^unknown_user") {
                    726:         &logthis("$uname in $udom attempted to change their password ".
                    727: 		 "on $server but were unable to because $server is not ".
                    728: 		 "their home server.");
                    729:     } elsif ($answer =~ "^refused") {
                    730: 	&logthis("$server refused to change $uname in $udom password because ".
                    731: 		 "it was sent an unencrypted request to change the password.");
                    732:     }
                    733:     return $answer;
1.1       albertel  734: }
                    735: 
1.169     harris41  736: # ----------------------- Try to determine user's current authentication scheme
                    737: 
                    738: sub queryauthenticate {
                    739:     my ($uname,$udom)=@_;
1.456     albertel  740:     my $uhome=&homeserver($uname,$udom);
                    741:     if (!$uhome) {
                    742: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    743: 	return 'no_host';
                    744:     }
                    745:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    746:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    747: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  748:     }
1.456     albertel  749:     return $answer;
1.169     harris41  750: }
                    751: 
1.1       albertel  752: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       753: 
1.1       albertel  754: sub authenticate {
1.952     raeburn   755:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  756:     $upass=&escape($upass);
                    757:     $uname= &LONCAPA::clean_username($uname);
1.836     www       758:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   759:     my $newhome;
1.836     www       760:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    761: # Maybe the machine was offline and only re-appeared again recently?
                    762:         &reconlonc();
                    763: # One more
1.952     raeburn   764: 	$uhome=&homeserver($uname,$udom,1);
                    765:         if (($uhome eq 'no_host') && $checkdefauth) {
                    766:             if (defined(&domain($udom,'primary'))) {
                    767:                 $newhome=&domain($udom,'primary');
                    768:             }
                    769:             if ($newhome ne '') {
                    770:                 $uhome = $newhome;
                    771:             }
                    772:         }
1.836     www       773: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    774: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   775: 	    return 'no_host';
                    776:         }
1.1       albertel  777:     }
1.952     raeburn   778:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  779:     if ($answer eq 'authorized') {
1.952     raeburn   780:         if ($newhome) {
                    781:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    782:             return 'no_account_on_host'; 
                    783:         } else {
                    784:             &logthis("User $uname at $udom authorized by $uhome");
                    785:             return $uhome;
                    786:         }
1.471     albertel  787:     }
                    788:     if ($answer eq 'non_authorized') {
                    789: 	&logthis("User $uname at $udom rejected by $uhome");
                    790: 	return 'no_host'; 
1.9       www       791:     }
1.471     albertel  792:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  793:     return 'no_host';
                    794: }
                    795: 
                    796: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       797: 
1.599     albertel  798: my %homecache;
1.1       albertel  799: sub homeserver {
1.230     stredwic  800:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  801:     my $index="$uname:$udom";
1.426     albertel  802: 
1.599     albertel  803:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  804: 
                    805:     my %servers = &get_servers($udom,'library');
                    806:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  807:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  808: 		 exists($badServerCache{$tryserver}));
1.841     albertel  809: 
                    810: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    811: 	if ($answer eq 'found') {
                    812: 	    delete($badServerCache{$tryserver}); 
                    813: 	    return $homecache{$index}=$tryserver;
                    814: 	} elsif ($answer eq 'no_host') {
                    815: 	    $badServerCache{$tryserver}=1;
                    816: 	}
1.1       albertel  817:     }    
                    818:     return 'no_host';
1.70      www       819: }
                    820: 
                    821: # ------------------------------------- Find the usernames behind a list of IDs
                    822: 
                    823: sub idget {
                    824:     my ($udom,@ids)=@_;
                    825:     my %returnhash=();
                    826:     
1.841     albertel  827:     my %servers = &get_servers($udom,'library');
                    828:     foreach my $tryserver (keys(%servers)) {
                    829: 	my $idlist=join('&',@ids);
                    830: 	$idlist=~tr/A-Z/a-z/; 
                    831: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    832: 	my @answer=();
                    833: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    834: 	    @answer=split(/\&/,$reply);
                    835: 	}                    ;
                    836: 	my $i;
                    837: 	for ($i=0;$i<=$#ids;$i++) {
                    838: 	    if ($answer[$i]) {
                    839: 		$returnhash{$ids[$i]}=$answer[$i];
                    840: 	    } 
                    841: 	}
                    842:     } 
1.70      www       843:     return %returnhash;
                    844: }
                    845: 
                    846: # ------------------------------------- Find the IDs behind a list of usernames
                    847: 
                    848: sub idrget {
                    849:     my ($udom,@unames)=@_;
                    850:     my %returnhash=();
1.800     albertel  851:     foreach my $uname (@unames) {
                    852:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  853:     }
1.70      www       854:     return %returnhash;
                    855: }
                    856: 
                    857: # ------------------------------- Store away a list of names and associated IDs
                    858: 
                    859: sub idput {
                    860:     my ($udom,%ids)=@_;
                    861:     my %servers=();
1.800     albertel  862:     foreach my $uname (keys(%ids)) {
                    863: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    864:         my $uhom=&homeserver($uname,$udom);
1.70      www       865:         if ($uhom ne 'no_host') {
1.800     albertel  866:             my $id=&escape($ids{$uname});
1.70      www       867:             $id=~tr/A-Z/a-z/;
1.800     albertel  868:             my $esc_unam=&escape($uname);
1.70      www       869: 	    if ($servers{$uhom}) {
1.800     albertel  870: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       871:             } else {
1.800     albertel  872:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       873:             }
                    874:         }
1.191     harris41  875:     }
1.800     albertel  876:     foreach my $server (keys(%servers)) {
                    877:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  878:     }
1.344     www       879: }
                    880: 
1.806     raeburn   881: # ------------------------------------------- get items from domain db files   
                    882: 
                    883: sub get_dom {
1.860     raeburn   884:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   885:     my $items='';
                    886:     foreach my $item (@$storearr) {
                    887:         $items.=&escape($item).'&';
                    888:     }
                    889:     $items=~s/\&$//;
1.860     raeburn   890:     if (!$udom) {
                    891:         $udom=$env{'user.domain'};
                    892:         if (defined(&domain($udom,'primary'))) {
                    893:             $uhome=&domain($udom,'primary');
                    894:         } else {
1.874     albertel  895:             undef($uhome);
1.860     raeburn   896:         }
                    897:     } else {
                    898:         if (!$uhome) {
                    899:             if (defined(&domain($udom,'primary'))) {
                    900:                 $uhome=&domain($udom,'primary');
                    901:             }
                    902:         }
                    903:     }
                    904:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   905:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   906:         my %returnhash;
1.875     albertel  907:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   908:             return %returnhash;
                    909:         }
1.806     raeburn   910:         my @pairs=split(/\&/,$rep);
                    911:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    912:             return @pairs;
                    913:         }
                    914:         my $i=0;
                    915:         foreach my $item (@$storearr) {
                    916:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    917:             $i++;
                    918:         }
                    919:         return %returnhash;
                    920:     } else {
1.880     banghart  921:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   922:     }
                    923: }
                    924: 
                    925: # -------------------------------------------- put items in domain db files 
                    926: 
                    927: sub put_dom {
1.860     raeburn   928:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    929:     if (!$udom) {
                    930:         $udom=$env{'user.domain'};
                    931:         if (defined(&domain($udom,'primary'))) {
                    932:             $uhome=&domain($udom,'primary');
                    933:         } else {
1.874     albertel  934:             undef($uhome);
1.860     raeburn   935:         }
                    936:     } else {
                    937:         if (!$uhome) {
                    938:             if (defined(&domain($udom,'primary'))) {
                    939:                 $uhome=&domain($udom,'primary');
                    940:             }
                    941:         }
                    942:     } 
                    943:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   944:         my $items='';
                    945:         foreach my $item (keys(%$storehash)) {
                    946:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    947:         }
                    948:         $items=~s/\&$//;
                    949:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    950:     } else {
1.860     raeburn   951:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   952:     }
                    953: }
                    954: 
1.837     raeburn   955: sub retrieve_inst_usertypes {
                    956:     my ($udom) = @_;
                    957:     my (%returnhash,@order);
1.846     albertel  958:     if (defined(&domain($udom,'primary'))) {
                    959:         my $uhome=&domain($udom,'primary');
1.837     raeburn   960:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn   961:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                    962:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                    963:             return (\%returnhash,\@order);
                    964:         }
1.837     raeburn   965:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    966:         my @pairs=split(/\&/,$hashitems);
                    967:         foreach my $item (@pairs) {
                    968:             my ($key,$value)=split(/=/,$item,2);
                    969:             $key = &unescape($key);
                    970:             next if ($key =~ /^error: 2 /);
                    971:             $returnhash{$key}=&thaw_unescape($value);
                    972:         }
                    973:         my @esc_order = split(/\&/,$orderitems);
                    974:         foreach my $item (@esc_order) {
                    975:             push(@order,&unescape($item));
                    976:         }
                    977:     } else {
                    978:         &logthis("get_dom failed - no primary domain server for $udom");
                    979:     }
                    980:     return (\%returnhash,\@order);
                    981: }
                    982: 
1.868     raeburn   983: sub is_domainimage {
                    984:     my ($url) = @_;
                    985:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    986:         if (&domain($1) ne '') {
                    987:             return '1';
                    988:         }
                    989:     }
                    990:     return;
                    991: }
                    992: 
1.899     raeburn   993: sub inst_directory_query {
                    994:     my ($srch) = @_;
                    995:     my $udom = $srch->{'srchdomain'};
                    996:     my %results;
                    997:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   998:     my $outcome;
1.899     raeburn   999:     if ($homeserver ne '') {
1.904     albertel 1000: 	my $queryid=&reply("querysend:instdirsearch:".
                   1001: 			   &escape($srch->{'srchby'}).':'.
                   1002: 			   &escape($srch->{'srchterm'}).':'.
                   1003: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1004: 	my $host=&hostname($homeserver);
                   1005: 	if ($queryid !~/^\Q$host\E\_/) {
                   1006: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1007: 	    return;
                   1008: 	}
                   1009: 	my $response = &get_query_reply($queryid);
                   1010: 	my $maxtries = 5;
                   1011: 	my $tries = 1;
                   1012: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1013: 	    $response = &get_query_reply($queryid);
                   1014: 	    $tries ++;
                   1015: 	}
                   1016: 
                   1017:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1018:             if ($response eq 'unavailable') {
                   1019:                 $outcome = $response;
                   1020:             } else {
                   1021:                 $outcome = 'ok';
                   1022:                 my @matches = split(/\n/,$response);
                   1023:                 foreach my $match (@matches) {
                   1024:                     my ($key,$value) = split(/=/,$match);
                   1025:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1026:                 }
1.899     raeburn  1027:             }
                   1028:         }
                   1029:     }
1.909     raeburn  1030:     return ($outcome,%results);
1.899     raeburn  1031: }
                   1032: 
                   1033: sub usersearch {
                   1034:     my ($srch) = @_;
                   1035:     my $dom = $srch->{'srchdomain'};
                   1036:     my %results;
                   1037:     my %libserv = &all_library();
                   1038:     my $query = 'usersearch';
                   1039:     foreach my $tryserver (keys(%libserv)) {
                   1040:         if (&host_domain($tryserver) eq $dom) {
                   1041:             my $host=&hostname($tryserver);
                   1042:             my $queryid=
1.911     raeburn  1043:                 &reply("querysend:".&escape($query).':'.
                   1044:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1045:                        &escape($srch->{'srchtype'}).':'.
                   1046:                        &escape($srch->{'srchterm'}),$tryserver);
                   1047:             if ($queryid !~/^\Q$host\E\_/) {
                   1048:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1049:                 next;
1.899     raeburn  1050:             }
                   1051:             my $reply = &get_query_reply($queryid);
                   1052:             my $maxtries = 1;
                   1053:             my $tries = 1;
                   1054:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1055:                 $reply = &get_query_reply($queryid);
                   1056:                 $tries ++;
                   1057:             }
                   1058:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1059:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1060:             } else {
1.911     raeburn  1061:                 my @matches;
                   1062:                 if ($reply =~ /\n/) {
                   1063:                     @matches = split(/\n/,$reply);
                   1064:                 } else {
                   1065:                     @matches = split(/\&/,$reply);
                   1066:                 }
1.899     raeburn  1067:                 foreach my $match (@matches) {
                   1068:                     my ($uname,$udom,%userhash);
1.911     raeburn  1069:                     foreach my $entry (split(/:/,$match)) {
                   1070:                         my ($key,$value) =
                   1071:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1072:                         $userhash{$key} = $value;
                   1073:                         if ($key eq 'username') {
                   1074:                             $uname = $value;
                   1075:                         } elsif ($key eq 'domain') {
                   1076:                             $udom = $value;
1.911     raeburn  1077:                         }
1.899     raeburn  1078:                     }
                   1079:                     $results{$uname.':'.$udom} = \%userhash;
                   1080:                 }
                   1081:             }
                   1082:         }
                   1083:     }
                   1084:     return %results;
                   1085: }
                   1086: 
1.912     raeburn  1087: sub get_instuser {
                   1088:     my ($udom,$uname,$id) = @_;
                   1089:     my $homeserver = &domain($udom,'primary');
                   1090:     my ($outcome,%results);
                   1091:     if ($homeserver ne '') {
                   1092:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1093:                            &escape($id).':'.&escape($udom),$homeserver);
                   1094:         my $host=&hostname($homeserver);
                   1095:         if ($queryid !~/^\Q$host\E\_/) {
                   1096:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1097:             return;
                   1098:         }
                   1099:         my $response = &get_query_reply($queryid);
                   1100:         my $maxtries = 5;
                   1101:         my $tries = 1;
                   1102:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1103:             $response = &get_query_reply($queryid);
                   1104:             $tries ++;
                   1105:         }
                   1106:         if (!&error($response) && $response ne 'refused') {
                   1107:             if ($response eq 'unavailable') {
                   1108:                 $outcome = $response;
                   1109:             } else {
                   1110:                 $outcome = 'ok';
                   1111:                 my @matches = split(/\n/,$response);
                   1112:                 foreach my $match (@matches) {
                   1113:                     my ($key,$value) = split(/=/,$match);
                   1114:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1115:                 }
                   1116:             }
                   1117:         }
                   1118:     }
                   1119:     my %userinfo;
                   1120:     if (ref($results{$uname}) eq 'HASH') {
                   1121:         %userinfo = %{$results{$uname}};
                   1122:     } 
                   1123:     return ($outcome,%userinfo);
                   1124: }
                   1125: 
                   1126: sub inst_rulecheck {
1.923     raeburn  1127:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1128:     my %returnhash;
                   1129:     if ($udom ne '') {
                   1130:         if (ref($rules) eq 'ARRAY') {
                   1131:             @{$rules} = map {&escape($_);} (@{$rules});
                   1132:             my $rulestr = join(':',@{$rules});
                   1133:             my $homeserver=&domain($udom,'primary');
                   1134:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1135:                 my $response;
                   1136:                 if ($item eq 'username') {                
                   1137:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1138:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1139:                                               $homeserver));
1.923     raeburn  1140:                 } elsif ($item eq 'id') {
                   1141:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1142:                                               ':'.&escape($id).':'.$rulestr,
                   1143:                                               $homeserver));
1.945     raeburn  1144:                 } elsif ($item eq 'selfcreate') {
                   1145:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1146:                                                &escape($udom).':'.&escape($uname).
                   1147:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1148:                 }
1.912     raeburn  1149:                 if ($response ne 'refused') {
                   1150:                     my @pairs=split(/\&/,$response);
                   1151:                     foreach my $item (@pairs) {
                   1152:                         my ($key,$value)=split(/=/,$item,2);
                   1153:                         $key = &unescape($key);
                   1154:                         next if ($key =~ /^error: 2 /);
                   1155:                         $returnhash{$key}=&thaw_unescape($value);
                   1156:                     }
                   1157:                 }
                   1158:             }
                   1159:         }
                   1160:     }
                   1161:     return %returnhash;
                   1162: }
                   1163: 
                   1164: sub inst_userrules {
1.923     raeburn  1165:     my ($udom,$check) = @_;
1.912     raeburn  1166:     my (%ruleshash,@ruleorder);
                   1167:     if ($udom ne '') {
                   1168:         my $homeserver=&domain($udom,'primary');
                   1169:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1170:             my $response;
                   1171:             if ($check eq 'id') {
                   1172:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1173:                                  $homeserver);
1.943     raeburn  1174:             } elsif ($check eq 'email') {
                   1175:                 $response=&reply('instemailrules:'.&escape($udom),
                   1176:                                  $homeserver);
1.923     raeburn  1177:             } else {
                   1178:                 $response=&reply('instuserrules:'.&escape($udom),
                   1179:                                  $homeserver);
                   1180:             }
1.912     raeburn  1181:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1182:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1183:                 ($response ne 'no_such_host')) {
                   1184:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1185:                 my @pairs=split(/\&/,$hashitems);
                   1186:                 foreach my $item (@pairs) {
                   1187:                     my ($key,$value)=split(/=/,$item,2);
                   1188:                     $key = &unescape($key);
                   1189:                     next if ($key =~ /^error: 2 /);
                   1190:                     $ruleshash{$key}=&thaw_unescape($value);
                   1191:                 }
                   1192:                 my @esc_order = split(/\&/,$orderitems);
                   1193:                 foreach my $item (@esc_order) {
                   1194:                     push(@ruleorder,&unescape($item));
                   1195:                 }
                   1196:             }
                   1197:         }
                   1198:     }
                   1199:     return (\%ruleshash,\@ruleorder);
                   1200: }
                   1201: 
1.943     raeburn  1202: # ------------------------- Get Authentication and Language Defaults for Domain
                   1203: 
                   1204: sub get_domain_defaults {
                   1205:     my ($domain) = @_;
                   1206:     my $cachetime = 60*60*24;
                   1207:     my ($defauthtype,$defautharg,$deflang);
                   1208:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1209:     if (defined($cached)) {
                   1210:         if (ref($result) eq 'HASH') {
                   1211:             return %{$result};
                   1212:         }
                   1213:     }
                   1214:     my %domdefaults;
                   1215:     my %domconfig =
                   1216:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1217:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1218:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1219:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1220:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1221:     } else {
                   1222:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1223:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1224:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1225:     }
                   1226:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1227:                                   $cachetime);
                   1228:     return %domdefaults;
                   1229: }
                   1230: 
1.344     www      1231: # --------------------------------------------------- Assign a key to a student
                   1232: 
                   1233: sub assign_access_key {
1.364     www      1234: #
                   1235: # a valid key looks like uname:udom#comments
                   1236: # comments are being appended
                   1237: #
1.498     www      1238:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1239:     $kdom=
1.620     albertel 1240:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1241:     $knum=
1.620     albertel 1242:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1243:     $cdom=
1.620     albertel 1244:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1245:     $cnum=
1.620     albertel 1246:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1247:     $udom=$env{'user.name'} unless (defined($udom));
                   1248:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1249:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1250:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1251:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1252:                                                   # assigned to this person
                   1253:                                                   # - this should not happen,
1.345     www      1254:                                                   # unless something went wrong
                   1255:                                                   # the first time around
                   1256: # ready to assign
1.364     www      1257:         $logentry=$1.'; '.$logentry;
1.496     www      1258:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1259:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1260: # key now belongs to user
1.346     www      1261: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1262:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1263:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1264:                 return 'ok';
                   1265:             } else {
                   1266:                 return 
                   1267:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1268: 	    }
                   1269:         } else {
                   1270:             return 'error: Could not assign key, try again later.';
                   1271:         }
1.364     www      1272:     } elsif (!$existing{$ckey}) {
1.345     www      1273: # the key does not exist
                   1274: 	return 'error: The key does not exist';
                   1275:     } else {
                   1276: # the key is somebody else's
                   1277: 	return 'error: The key is already in use';
                   1278:     }
1.344     www      1279: }
                   1280: 
1.364     www      1281: # ------------------------------------------ put an additional comment on a key
                   1282: 
                   1283: sub comment_access_key {
                   1284: #
                   1285: # a valid key looks like uname:udom#comments
                   1286: # comments are being appended
                   1287: #
                   1288:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1289:     $cdom=
1.620     albertel 1290:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1291:     $cnum=
1.620     albertel 1292:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1293:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1294:     if ($existing{$ckey}) {
                   1295:         $existing{$ckey}.='; '.$logentry;
                   1296: # ready to assign
1.367     www      1297:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1298:                                                  $cdom,$cnum) eq 'ok') {
                   1299: 	    return 'ok';
                   1300:         } else {
                   1301: 	    return 'error: Count not store comment.';
                   1302:         }
                   1303:     } else {
                   1304: # the key does not exist
                   1305: 	return 'error: The key does not exist';
                   1306:     }
                   1307: }
                   1308: 
1.344     www      1309: # ------------------------------------------------------ Generate a set of keys
                   1310: 
                   1311: sub generate_access_keys {
1.364     www      1312:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1313:     $cdom=
1.620     albertel 1314:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1315:     $cnum=
1.620     albertel 1316:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1317:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1318:     unless (($cdom) && ($cnum)) { return 0; }
                   1319:     if ($number>10000) { return 0; }
                   1320:     sleep(2); # make sure don't get same seed twice
                   1321:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1322:     my $total=0;
                   1323:     for (my $i=1;$i<=$number;$i++) {
                   1324:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1325:                   sprintf("%lx",int(100000*rand)).'-'.
                   1326:                   sprintf("%lx",int(100000*rand));
                   1327:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1328:        $newkey=~s/0/h/g; # and also 0 and O
                   1329:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1330:        if ($existing{$newkey}) {
                   1331:            $i--;
                   1332:        } else {
1.364     www      1333: 	  if (&put('accesskeys',
                   1334:               { $newkey => '# generated '.localtime().
1.620     albertel 1335:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1336:                            '; '.$logentry },
                   1337: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1338:               $total++;
                   1339: 	  }
                   1340:        }
                   1341:     }
1.620     albertel 1342:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1343:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1344:     return $total;
                   1345: }
                   1346: 
                   1347: # ------------------------------------------------------- Validate an accesskey
                   1348: 
                   1349: sub validate_access_key {
                   1350:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1351:     $cdom=
1.620     albertel 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1353:     $cnum=
1.620     albertel 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1355:     $udom=$env{'user.domain'} unless (defined($udom));
                   1356:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1357:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1358:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1359: }
                   1360: 
                   1361: # ------------------------------------- Find the section of student in a course
1.652     albertel 1362: sub devalidate_getsection_cache {
                   1363:     my ($udom,$unam,$courseid)=@_;
                   1364:     my $hashid="$udom:$unam:$courseid";
                   1365:     &devalidate_cache_new('getsection',$hashid);
                   1366: }
1.298     matthew  1367: 
1.815     albertel 1368: sub courseid_to_courseurl {
                   1369:     my ($courseid) = @_;
                   1370:     #already url style courseid
                   1371:     return $courseid if ($courseid =~ m{^/});
                   1372: 
                   1373:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1374: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1375: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1376: 	return "/$cdom/$cnum";
                   1377:     }
                   1378: 
                   1379:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1380:     if (exists($courseinfo{'num'})) {
                   1381: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1382:     }
                   1383: 
                   1384:     return undef;
                   1385: }
                   1386: 
1.298     matthew  1387: sub getsection {
                   1388:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1389:     my $cachetime=1800;
1.551     albertel 1390: 
                   1391:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1392:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1393:     if (defined($cached)) { return $result; }
                   1394: 
1.298     matthew  1395:     my %Pending; 
                   1396:     my %Expired;
                   1397:     #
                   1398:     # Each role can either have not started yet (pending), be active, 
                   1399:     #    or have expired.
                   1400:     #
                   1401:     # If there is an active role, we are done.
                   1402:     #
                   1403:     # If there is more than one role which has not started yet, 
                   1404:     #     choose the one which will start sooner
                   1405:     # If there is one role which has not started yet, return it.
                   1406:     #
                   1407:     # If there is more than one expired role, choose the one which ended last.
                   1408:     # If there is a role which has expired, return it.
                   1409:     #
1.815     albertel 1410:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1411:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1412:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1413:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1414:         my $section=$1;
                   1415:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1416:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1417:         my $now=time;
1.548     albertel 1418:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1419:             $Expired{$end}=$section;
                   1420:             next;
                   1421:         }
1.548     albertel 1422:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1423:             $Pending{$start}=$section;
                   1424:             next;
                   1425:         }
1.599     albertel 1426:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1427:     }
                   1428:     #
                   1429:     # Presumedly there will be few matching roles from the above
                   1430:     # loop and the sorting time will be negligible.
                   1431:     if (scalar(keys(%Pending))) {
                   1432:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1433:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1434:     } 
                   1435:     if (scalar(keys(%Expired))) {
                   1436:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1437:         my $time = pop(@sorted);
1.599     albertel 1438:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1439:     }
1.599     albertel 1440:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1441: }
1.70      www      1442: 
1.599     albertel 1443: sub save_cache {
                   1444:     &purge_remembered();
1.722     albertel 1445:     #&Apache::loncommon::validate_page();
1.620     albertel 1446:     undef(%env);
1.780     albertel 1447:     undef($env_loaded);
1.599     albertel 1448: }
1.452     albertel 1449: 
1.599     albertel 1450: my $to_remember=-1;
                   1451: my %remembered;
                   1452: my %accessed;
                   1453: my $kicks=0;
                   1454: my $hits=0;
1.849     albertel 1455: sub make_key {
                   1456:     my ($name,$id) = @_;
1.872     albertel 1457:     if (length($id) > 65 
                   1458: 	&& length(&escape($id)) > 200) {
                   1459: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1460:     }
1.849     albertel 1461:     return &escape($name.':'.$id);
                   1462: }
                   1463: 
1.599     albertel 1464: sub devalidate_cache_new {
                   1465:     my ($name,$id,$debug) = @_;
                   1466:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1467:     $id=&make_key($name,$id);
1.599     albertel 1468:     $memcache->delete($id);
                   1469:     delete($remembered{$id});
                   1470:     delete($accessed{$id});
                   1471: }
                   1472: 
                   1473: sub is_cached_new {
                   1474:     my ($name,$id,$debug) = @_;
1.849     albertel 1475:     $id=&make_key($name,$id);
1.599     albertel 1476:     if (exists($remembered{$id})) {
                   1477: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1478: 	$accessed{$id}=[&gettimeofday()];
                   1479: 	$hits++;
                   1480: 	return ($remembered{$id},1);
                   1481:     }
                   1482:     my $value = $memcache->get($id);
                   1483:     if (!(defined($value))) {
                   1484: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1485: 	return (undef,undef);
1.416     albertel 1486:     }
1.599     albertel 1487:     if ($value eq '__undef__') {
                   1488: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1489: 	$value=undef;
                   1490:     }
                   1491:     &make_room($id,$value,$debug);
                   1492:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1493:     return ($value,1);
                   1494: }
                   1495: 
                   1496: sub do_cache_new {
                   1497:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1498:     $id=&make_key($name,$id);
1.599     albertel 1499:     my $setvalue=$value;
                   1500:     if (!defined($setvalue)) {
                   1501: 	$setvalue='__undef__';
                   1502:     }
1.623     albertel 1503:     if (!defined($time) ) {
                   1504: 	$time=600;
                   1505:     }
1.599     albertel 1506:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1507:     my $result = $memcache->set($id,$setvalue,$time);
                   1508:     if (! $result) {
1.872     albertel 1509: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1510: 	$memcache->disconnect_all();
1.872     albertel 1511:     }
1.600     albertel 1512:     # need to make a copy of $value
1.919     albertel 1513:     &make_room($id,$value,$debug);
1.599     albertel 1514:     return $value;
                   1515: }
                   1516: 
                   1517: sub make_room {
                   1518:     my ($id,$value,$debug)=@_;
1.919     albertel 1519: 
                   1520:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1521:                                     : $value;
1.599     albertel 1522:     if ($to_remember<0) { return; }
                   1523:     $accessed{$id}=[&gettimeofday()];
                   1524:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1525:     my $to_kick;
                   1526:     my $max_time=0;
                   1527:     foreach my $other (keys(%accessed)) {
                   1528: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1529: 	    $to_kick=$other;
                   1530: 	    $max_time=&tv_interval($accessed{$other});
                   1531: 	}
                   1532:     }
                   1533:     delete($remembered{$to_kick});
                   1534:     delete($accessed{$to_kick});
                   1535:     $kicks++;
                   1536:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1537:     return;
                   1538: }
                   1539: 
1.599     albertel 1540: sub purge_remembered {
1.604     albertel 1541:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1542:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1543:     undef(%remembered);
                   1544:     undef(%accessed);
1.428     albertel 1545: }
1.70      www      1546: # ------------------------------------- Read an entry from a user's environment
                   1547: 
                   1548: sub userenvironment {
                   1549:     my ($udom,$unam,@what)=@_;
                   1550:     my %returnhash=();
                   1551:     my @answer=split(/\&/,
                   1552:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1553:                       &homeserver($unam,$udom)));
                   1554:     my $i;
                   1555:     for ($i=0;$i<=$#what;$i++) {
                   1556: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1557:     }
                   1558:     return %returnhash;
1.1       albertel 1559: }
                   1560: 
1.617     albertel 1561: # ---------------------------------------------------------- Get a studentphoto
                   1562: sub studentphoto {
                   1563:     my ($udom,$unam,$ext) = @_;
                   1564:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1565:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1566:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1567:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1568:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1569:             } else {
                   1570:                 my ($result,$perm_reqd)=
1.707     albertel 1571: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1572:                 if ($result eq 'ok') {
                   1573:                     if (!($perm_reqd eq 'yes')) {
                   1574:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1575:                     }
                   1576:                 }
                   1577:             }
                   1578:         }
                   1579:     } else {
                   1580:         my ($result,$perm_reqd) = 
1.707     albertel 1581: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1582:         if ($result eq 'ok') {
                   1583:             if (!($perm_reqd eq 'yes')) {
                   1584:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1585:             }
                   1586:         }
                   1587:     }
                   1588:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1589: }
                   1590: 
                   1591: sub retrievestudentphoto {
                   1592:     my ($udom,$unam,$ext,$type) = @_;
                   1593:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1594:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1595:     if ($ret eq 'ok') {
                   1596:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1597:         if ($type eq 'thumbnail') {
                   1598:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1599:         }
                   1600:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1601:         return $tokenurl;
                   1602:     } else {
                   1603:         if ($type eq 'thumbnail') {
                   1604:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1605:         } else { 
                   1606:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1607:         }
1.617     albertel 1608:     }
                   1609: }
                   1610: 
1.263     www      1611: # -------------------------------------------------------------------- New chat
                   1612: 
                   1613: sub chatsend {
1.724     raeburn  1614:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1615:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1616:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1617:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1618:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1619: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1620: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1621: }
                   1622: 
                   1623: # ------------------------------------------ Find current version of a resource
                   1624: 
                   1625: sub getversion {
                   1626:     my $fname=&clutter(shift);
                   1627:     unless ($fname=~/^\/res\//) { return -1; }
                   1628:     return &currentversion(&filelocation('',$fname));
                   1629: }
                   1630: 
                   1631: sub currentversion {
                   1632:     my $fname=shift;
1.599     albertel 1633:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1634:     if (defined($cached)) { return $result; }
1.292     www      1635:     my $author=$fname;
                   1636:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1637:     my ($udom,$uname)=split(/\//,$author);
                   1638:     my $home=homeserver($uname,$udom);
                   1639:     if ($home eq 'no_host') { 
                   1640:         return -1; 
                   1641:     }
                   1642:     my $answer=reply("currentversion:$fname",$home);
                   1643:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1644: 	return -1;
                   1645:     }
1.599     albertel 1646:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1647: }
                   1648: 
1.1       albertel 1649: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1650: 
1.1       albertel 1651: sub subscribe {
                   1652:     my $fname=shift;
1.761     raeburn  1653:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1654:     $fname=~s/[\n\r]//g;
1.1       albertel 1655:     my $author=$fname;
                   1656:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1657:     my ($udom,$uname)=split(/\//,$author);
                   1658:     my $home=homeserver($uname,$udom);
1.335     albertel 1659:     if ($home eq 'no_host') {
                   1660:         return 'not_found';
1.1       albertel 1661:     }
                   1662:     my $answer=reply("sub:$fname",$home);
1.64      www      1663:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1664: 	$answer.=' by '.$home;
                   1665:     }
1.1       albertel 1666:     return $answer;
                   1667: }
                   1668:     
1.8       www      1669: # -------------------------------------------------------------- Replicate file
                   1670: 
                   1671: sub repcopy {
                   1672:     my $filename=shift;
1.23      www      1673:     $filename=~s/\/+/\//g;
1.607     raeburn  1674:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1675:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1676:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1677: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1678: 	return &repcopy_userfile($filename);
                   1679:     }
1.532     albertel 1680:     $filename=~s/[\n\r]//g;
1.8       www      1681:     my $transname="$filename.in.transfer";
1.828     www      1682: # FIXME: this should flock
1.607     raeburn  1683:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1684:     my $remoteurl=subscribe($filename);
1.64      www      1685:     if ($remoteurl =~ /^con_lost by/) {
                   1686: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1687:            return 'unavailable';
1.8       www      1688:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1689: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1690: 	   return 'not_found';
1.64      www      1691:     } elsif ($remoteurl =~ /^rejected by/) {
                   1692: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1693:            return 'forbidden';
1.20      www      1694:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1695:            return 'ok';
1.8       www      1696:     } else {
1.290     www      1697:         my $author=$filename;
                   1698:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1699:         my ($udom,$uname)=split(/\//,$author);
                   1700:         my $home=homeserver($uname,$udom);
                   1701:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1702:            my @parts=split(/\//,$filename);
                   1703:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1704:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1705:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1706: 	       return 'bad_request';
1.8       www      1707:            }
                   1708:            my $count;
                   1709:            for ($count=5;$count<$#parts;$count++) {
                   1710:                $path.="/$parts[$count]";
                   1711:                if ((-e $path)!=1) {
                   1712: 		   mkdir($path,0777);
                   1713:                }
                   1714:            }
                   1715:            my $ua=new LWP::UserAgent;
                   1716:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1717:            my $response=$ua->request($request,$transname);
                   1718:            if ($response->is_error()) {
                   1719: 	       unlink($transname);
                   1720:                my $message=$response->status_line;
1.672     albertel 1721:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1722:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1723:                return 'unavailable';
1.8       www      1724:            } else {
1.16      www      1725: 	       if ($remoteurl!~/\.meta$/) {
                   1726:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1727:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1728:                   if ($mresponse->is_error()) {
                   1729: 		      unlink($filename.'.meta');
                   1730:                       &logthis(
1.672     albertel 1731:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1732:                   }
                   1733: 	       }
1.8       www      1734:                rename($transname,$filename);
1.607     raeburn  1735:                return 'ok';
1.8       www      1736:            }
1.290     www      1737:        }
1.8       www      1738:     }
1.330     www      1739: }
                   1740: 
                   1741: # ------------------------------------------------ Get server side include body
                   1742: sub ssi_body {
1.381     albertel 1743:     my ($filelink,%form)=@_;
1.606     matthew  1744:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1745:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1746:     }
1.953     www      1747:     my $output='';
                   1748:     my $response;
                   1749:     if ($filelink=~/^http\:/) {
1.954     raeburn  1750:        ($output,$response)=&externalssi($filelink);
1.953     www      1751:     } else {
                   1752:        ($output,$response)=&ssi($filelink,%form);
                   1753:     }
1.778     albertel 1754:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1755:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1756:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1757:     if (wantarray) {
                   1758:         return ($output, $response);
                   1759:     } else {
                   1760:         return $output;
                   1761:     }
1.8       www      1762: }
                   1763: 
1.15      www      1764: # --------------------------------------------------------- Server Side Include
                   1765: 
1.782     albertel 1766: sub absolute_url {
                   1767:     my ($host_name) = @_;
                   1768:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1769:     if ($host_name eq '') {
                   1770: 	$host_name = $ENV{'SERVER_NAME'};
                   1771:     }
                   1772:     return $protocol.$host_name;
                   1773: }
                   1774: 
1.942     foxr     1775: #
                   1776: #   Server side include.
                   1777: # Parameters:
                   1778: #  fn     Possibly encrypted resource name/id.
                   1779: #  form   Hash that describes how the rendering should be done
                   1780: #         and other things.
1.944     foxr     1781: # Returns:
1.950     raeburn  1782: #   Scalar context: The content of the response.
                   1783: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1784: #     
1.15      www      1785: sub ssi {
                   1786: 
1.944     foxr     1787:     my ($fn,%form)=@_;
1.15      www      1788:     my $ua=new LWP::UserAgent;
1.23      www      1789:     my $request;
1.711     albertel 1790: 
                   1791:     $form{'no_update_last_known'}=1;
1.895     albertel 1792:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1793:     if (%form) {
1.782     albertel 1794:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1795:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1796:     } else {
1.782     albertel 1797:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1798:     }
                   1799: 
1.15      www      1800:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1801:     my $response=$ua->request($request);
                   1802: 
1.944     foxr     1803:     if (wantarray) {
                   1804: 	return ($response->content, $response);
                   1805:     } else {
                   1806: 	return $response->content;
1.942     foxr     1807:     }
1.324     www      1808: }
                   1809: 
                   1810: sub externalssi {
                   1811:     my ($url)=@_;
                   1812:     my $ua=new LWP::UserAgent;
                   1813:     my $request=new HTTP::Request('GET',$url);
                   1814:     my $response=$ua->request($request);
1.954     raeburn  1815:     if (wantarray) {
                   1816:         return ($response->content, $response);
                   1817:     } else {
                   1818:         return $response->content;
                   1819:     }
1.15      www      1820: }
1.254     www      1821: 
1.492     albertel 1822: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1823: 
                   1824: sub allowuploaded {
                   1825:     my ($srcurl,$url)=@_;
                   1826:     $url=&clutter(&declutter($url));
                   1827:     my $dir=$url;
                   1828:     $dir=~s/\/[^\/]+$//;
                   1829:     my %httpref=();
                   1830:     my $httpurl=&hreflocation('',$url);
                   1831:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1832:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1833: }
1.477     raeburn  1834: 
1.478     albertel 1835: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1836: # input: action, courseID, current domain, intended
1.637     raeburn  1837: #        path to file, source of file, instruction to parse file for objects,
                   1838: #        ref to hash for embedded objects,
                   1839: #        ref to hash for codebase of java objects.
                   1840: #
1.485     raeburn  1841: # output: url to file (if action was uploaddoc), 
                   1842: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1843: #
1.478     albertel 1844: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1845: # course.
1.477     raeburn  1846: #
1.478     albertel 1847: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1848: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1849: #          course's home server.
1.477     raeburn  1850: #
1.478     albertel 1851: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1852: #          be copied from $source (current location) to 
                   1853: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1854: #         and will then be copied to
                   1855: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1856: #         course's home server.
1.485     raeburn  1857: #
1.481     raeburn  1858: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1859: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1860: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1861: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1862: #         in course's home server.
1.637     raeburn  1863: #
1.477     raeburn  1864: 
                   1865: sub process_coursefile {
1.638     albertel 1866:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1867:     my $fetchresult;
1.638     albertel 1868:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1869:     if ($action eq 'propagate') {
1.638     albertel 1870:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1871: 			     $home);
1.481     raeburn  1872:     } else {
1.477     raeburn  1873:         my $fpath = '';
                   1874:         my $fname = $file;
1.478     albertel 1875:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1876:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1877:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1878:         if ($action eq 'copy') {
                   1879:             if ($source eq '') {
                   1880:                 $fetchresult = 'no source file';
                   1881:                 return $fetchresult;
                   1882:             } else {
                   1883:                 my $destination = $filepath.'/'.$fname;
                   1884:                 rename($source,$destination);
                   1885:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1886:                                  $home);
1.481     raeburn  1887:             }
                   1888:         } elsif ($action eq 'uploaddoc') {
                   1889:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1890:             print $fh $env{'form.'.$source};
1.481     raeburn  1891:             close($fh);
1.637     raeburn  1892:             if ($parser eq 'parse') {
1.961     raeburn  1893:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1894:                 unless ($parse_result eq 'ok') {
                   1895:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1896:                 }
                   1897:             }
1.477     raeburn  1898:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1899:                                  $home);
1.481     raeburn  1900:             if ($fetchresult eq 'ok') {
                   1901:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1902:             } else {
                   1903:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1904:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1905:                 return '/adm/notfound.html';
                   1906:             }
1.477     raeburn  1907:         }
                   1908:     }
1.485     raeburn  1909:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1910:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1911:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1912:     }
                   1913:     return $fetchresult;
                   1914: }
                   1915: 
1.637     raeburn  1916: sub build_filepath {
                   1917:     my ($fpath) = @_;
                   1918:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1919:     unless ($fpath eq '') {
                   1920:         my @parts=split('/',$fpath);
                   1921:         foreach my $part (@parts) {
                   1922:             $filepath.= '/'.$part;
                   1923:             if ((-e $filepath)!=1) {
                   1924:                 mkdir($filepath,0777);
                   1925:             }
                   1926:         }
                   1927:     }
                   1928:     return $filepath;
                   1929: }
                   1930: 
                   1931: sub store_edited_file {
1.638     albertel 1932:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1933:     my $file = $primary_url;
                   1934:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1935:     my $fpath = '';
                   1936:     my $fname = $file;
                   1937:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1938:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1939:     my $filepath = &build_filepath($fpath);
                   1940:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1941:     print $fh $content;
                   1942:     close($fh);
1.638     albertel 1943:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1944:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1945: 			  $home);
1.637     raeburn  1946:     if ($$fetchresult eq 'ok') {
                   1947:         return '/uploaded/'.$fpath.'/'.$fname;
                   1948:     } else {
1.638     albertel 1949:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1950: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1951:         return '/adm/notfound.html';
                   1952:     }
                   1953: }
                   1954: 
1.531     albertel 1955: sub clean_filename {
1.831     albertel 1956:     my ($fname,$args)=@_;
1.315     www      1957: # Replace Windows backslashes by forward slashes
1.257     www      1958:     $fname=~s/\\/\//g;
1.831     albertel 1959:     if (!$args->{'keep_path'}) {
                   1960:         # Get rid of everything but the actual filename
                   1961: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1962:     }
1.315     www      1963: # Replace spaces by underscores
                   1964:     $fname=~s/\s+/\_/g;
                   1965: # Replace all other weird characters by nothing
1.831     albertel 1966:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1967: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1968: # numbers
                   1969:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1970:     return $fname;
                   1971: }
                   1972: 
1.608     albertel 1973: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1974: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1975: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1976: #        $coursedoc - if true up to the current course
                   1977: #                     if false
                   1978: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1979: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1980: #        $allfiles - reference to hash for embedded objects
                   1981: #        $codebase - reference to hash for codebase of java objects
                   1982: #        $desuname - username for permanent storage of uploaded file
                   1983: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1984: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1985: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1986: # 
1.686     albertel 1987: # output: url of file in userspace, or error: <message> 
                   1988: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1989: 
                   1990: 
1.531     albertel 1991: sub userfileupload {
1.860     raeburn  1992:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1993:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1994:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1995:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1996:     $fname=&clean_filename($fname);
1.315     www      1997: # See if there is anything left
1.257     www      1998:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1999:     chop($env{'form.'.$formname});
1.523     raeburn  2000:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2001:         my $now = time;
                   2002:         my $filepath = 'tmp/helprequests/'.$now;
                   2003:         my @parts=split(/\//,$filepath);
                   2004:         my $fullpath = $perlvar{'lonDaemons'};
                   2005:         for (my $i=0;$i<@parts;$i++) {
                   2006:             $fullpath .= '/'.$parts[$i];
                   2007:             if ((-e $fullpath)!=1) {
                   2008:                 mkdir($fullpath,0777);
                   2009:             }
                   2010:         }
                   2011:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2012:         print $fh $env{'form.'.$formname};
1.523     raeburn  2013:         close($fh);
1.741     raeburn  2014:         return $fullpath.'/'.$fname;
                   2015:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2016:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2017:                        '_'.$env{'user.domain'}.'/pending';
                   2018:         my @parts=split(/\//,$filepath);
                   2019:         my $fullpath = $perlvar{'lonDaemons'};
                   2020:         for (my $i=0;$i<@parts;$i++) {
                   2021:             $fullpath .= '/'.$parts[$i];
                   2022:             if ((-e $fullpath)!=1) {
                   2023:                 mkdir($fullpath,0777);
                   2024:             }
                   2025:         }
                   2026:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2027:         print $fh $env{'form.'.$formname};
                   2028:         close($fh);
                   2029:         return $fullpath.'/'.$fname;
1.523     raeburn  2030:     }
1.719     banghart 2031:     
1.258     www      2032: # Create the directory if not present
1.493     albertel 2033:     $fname="$subdir/$fname";
1.259     www      2034:     if ($coursedoc) {
1.638     albertel 2035: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2036: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2037:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2038:             return &finishuserfileupload($docuname,$docudom,
                   2039: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2040: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2041:         } else {
1.620     albertel 2042:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2043:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2044: 				       $fname,$formname,$parser,
                   2045: 				       $allfiles,$codebase);
1.481     raeburn  2046:         }
1.719     banghart 2047:     } elsif (defined($destuname)) {
                   2048:         my $docuname=$destuname;
                   2049:         my $docudom=$destudom;
1.860     raeburn  2050: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2051: 				     $parser,$allfiles,$codebase,
                   2052:                                      $thumbwidth,$thumbheight);
1.719     banghart 2053:         
1.259     www      2054:     } else {
1.638     albertel 2055:         my $docuname=$env{'user.name'};
                   2056:         my $docudom=$env{'user.domain'};
1.714     raeburn  2057:         if (exists($env{'form.group'})) {
                   2058:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2059:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2060:         }
1.860     raeburn  2061: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2062: 				     $parser,$allfiles,$codebase,
                   2063:                                      $thumbwidth,$thumbheight);
1.259     www      2064:     }
1.271     www      2065: }
                   2066: 
                   2067: sub finishuserfileupload {
1.860     raeburn  2068:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2069:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2070:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2071:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2072:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2073:     $file=$fname;
                   2074:     if ($fname=~m|/|) {
                   2075:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2076: 	$path.=$fnamepath.'/';
                   2077:     }
1.259     www      2078:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2079:     my $count;
                   2080:     for ($count=4;$count<=$#parts;$count++) {
                   2081:         $filepath.="/$parts[$count]";
                   2082:         if ((-e $filepath)!=1) {
                   2083: 	    mkdir($filepath,0777);
                   2084:         }
                   2085:     }
                   2086: # Save the file
                   2087:     {
1.701     albertel 2088: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2089: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2090: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2091: 	    return '/adm/notfound.html';
                   2092: 	}
                   2093: 	if (!print FH ($env{'form.'.$formname})) {
                   2094: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2095: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2096: 	    return '/adm/notfound.html';
                   2097: 	}
1.570     albertel 2098: 	close(FH);
1.258     www      2099:     }
1.637     raeburn  2100:     if ($parser eq 'parse') {
1.961     raeburn  2101:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2102: 						   $codebase);
1.637     raeburn  2103:         unless ($parse_result eq 'ok') {
1.638     albertel 2104:             &logthis('Failed to parse '.$filepath.$file.
                   2105: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2106:         }
                   2107:     }
1.860     raeburn  2108:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2109:         my $input = $filepath.'/'.$file;
                   2110:         my $output = $filepath.'/'.'tn-'.$file;
                   2111:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2112:         system("convert -sample $thumbsize $input $output");
                   2113:         if (-e $filepath.'/'.'tn-'.$file) {
                   2114:             $fetchthumb  = 1; 
                   2115:         }
                   2116:     }
1.858     raeburn  2117:  
1.259     www      2118: # Notify homeserver to grep it
                   2119: #
1.638     albertel 2120:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2121:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2122:     if ($fetchresult eq 'ok') {
1.860     raeburn  2123:         if ($fetchthumb) {
                   2124:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2125:             if ($thumbresult ne 'ok') {
                   2126:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2127:                          $docuhome.': '.$thumbresult);
                   2128:             }
                   2129:         }
1.259     www      2130: #
1.258     www      2131: # Return the URL to it
1.494     albertel 2132:         return '/uploaded/'.$path.$file;
1.263     www      2133:     } else {
1.494     albertel 2134:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2135: 		 ': '.$fetchresult);
1.263     www      2136:         return '/adm/notfound.html';
1.858     raeburn  2137:     }
1.493     albertel 2138: }
                   2139: 
1.637     raeburn  2140: sub extract_embedded_items {
1.961     raeburn  2141:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2142:     my @state = ();
                   2143:     my %javafiles = (
                   2144:                       codebase => '',
                   2145:                       code => '',
                   2146:                       archive => ''
                   2147:                     );
                   2148:     my %mediafiles = (
                   2149:                       src => '',
                   2150:                       movie => '',
                   2151:                      );
1.648     raeburn  2152:     my $p;
                   2153:     if ($content) {
                   2154:         $p = HTML::LCParser->new($content);
                   2155:     } else {
1.961     raeburn  2156:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2157:     }
1.641     albertel 2158:     while (my $t=$p->get_token()) {
1.640     albertel 2159: 	if ($t->[0] eq 'S') {
                   2160: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2161: 	    push(@state, $tagname);
1.648     raeburn  2162:             if (lc($tagname) eq 'allow') {
                   2163:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2164:             }
1.640     albertel 2165: 	    if (lc($tagname) eq 'img') {
                   2166: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2167: 	    }
1.886     albertel 2168: 	    if (lc($tagname) eq 'a') {
                   2169: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2170: 	    }
1.645     raeburn  2171:             if (lc($tagname) eq 'script') {
                   2172:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2173:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2174:                 } else {
                   2175:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2176:                 }
                   2177:             }
                   2178:             if (lc($tagname) eq 'link') {
                   2179:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2180:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2181:                 }
                   2182:             }
1.640     albertel 2183: 	    if (lc($tagname) eq 'object' ||
                   2184: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2185: 		foreach my $item (keys(%javafiles)) {
                   2186: 		    $javafiles{$item} = '';
                   2187: 		}
                   2188: 	    }
                   2189: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2190: 		my $name = lc($attr->{'name'});
                   2191: 		foreach my $item (keys(%javafiles)) {
                   2192: 		    if ($name eq $item) {
                   2193: 			$javafiles{$item} = $attr->{'value'};
                   2194: 			last;
                   2195: 		    }
                   2196: 		}
                   2197: 		foreach my $item (keys(%mediafiles)) {
                   2198: 		    if ($name eq $item) {
                   2199: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2200: 			last;
                   2201: 		    }
                   2202: 		}
                   2203: 	    }
                   2204: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2205: 		foreach my $item (keys(%javafiles)) {
                   2206: 		    if ($attr->{$item}) {
                   2207: 			$javafiles{$item} = $attr->{$item};
                   2208: 			last;
                   2209: 		    }
                   2210: 		}
                   2211: 		foreach my $item (keys(%mediafiles)) {
                   2212: 		    if ($attr->{$item}) {
                   2213: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2214: 			last;
                   2215: 		    }
                   2216: 		}
                   2217: 	    }
                   2218: 	} elsif ($t->[0] eq 'E') {
                   2219: 	    my ($tagname) = ($t->[1]);
                   2220: 	    if ($javafiles{'codebase'} ne '') {
                   2221: 		$javafiles{'codebase'} .= '/';
                   2222: 	    }  
                   2223: 	    if (lc($tagname) eq 'applet' ||
                   2224: 		lc($tagname) eq 'object' ||
                   2225: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2226: 		) {
                   2227: 		foreach my $item (keys(%javafiles)) {
                   2228: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2229: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2230: 			&add_filetype($allfiles,$file,$item);
                   2231: 		    }
                   2232: 		}
                   2233: 	    } 
                   2234: 	    pop @state;
                   2235: 	}
                   2236:     }
1.637     raeburn  2237:     return 'ok';
                   2238: }
                   2239: 
1.639     albertel 2240: sub add_filetype {
                   2241:     my ($allfiles,$file,$type)=@_;
                   2242:     if (exists($allfiles->{$file})) {
                   2243: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2244: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2245: 	}
                   2246:     } else {
                   2247: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2248:     }
                   2249: }
                   2250: 
1.493     albertel 2251: sub removeuploadedurl {
                   2252:     my ($url)=@_;
                   2253:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2254:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2255: }
                   2256: 
                   2257: sub removeuserfile {
                   2258:     my ($docuname,$docudom,$fname)=@_;
                   2259:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2260:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2261:     if ($result eq 'ok') {
                   2262:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2263:             my $metafile = $fname.'.meta';
                   2264:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2265: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2266:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2267:             my $sqlresult = 
1.823     albertel 2268:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2269:                                         'portfolio_metadata',$group,
                   2270:                                         'delete');
1.798     raeburn  2271:         }
                   2272:     }
                   2273:     return $result;
1.257     www      2274: }
1.15      www      2275: 
1.530     albertel 2276: sub mkdiruserfile {
                   2277:     my ($docuname,$docudom,$dir)=@_;
                   2278:     my $home=&homeserver($docuname,$docudom);
                   2279:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2280: }
                   2281: 
1.531     albertel 2282: sub renameuserfile {
                   2283:     my ($docuname,$docudom,$old,$new)=@_;
                   2284:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2285:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2286:                         &escape("$old").':'.&escape("$new"),$home);
                   2287:     if ($result eq 'ok') {
                   2288:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2289:             my $oldmeta = $old.'.meta';
                   2290:             my $newmeta = $new.'.meta';
                   2291:             my $metaresult = 
                   2292:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2293: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2294:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2295:             my $sqlresult = 
1.823     albertel 2296:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2297:                                         'portfolio_metadata',$group,
                   2298:                                         'delete');
1.798     raeburn  2299:         }
                   2300:     }
                   2301:     return $result;
1.531     albertel 2302: }
                   2303: 
1.14      www      2304: # ------------------------------------------------------------------------- Log
                   2305: 
                   2306: sub log {
                   2307:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2308:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2309: }
                   2310: 
                   2311: # ------------------------------------------------------------------ Course Log
1.352     www      2312: #
                   2313: # This routine flushes several buffers of non-mission-critical nature
                   2314: #
1.157     www      2315: 
                   2316: sub flushcourselogs {
1.352     www      2317:     &logthis('Flushing log buffers');
                   2318: #
                   2319: # course logs
                   2320: # This is a log of all transactions in a course, which can be used
                   2321: # for data mining purposes
                   2322: #
                   2323: # It also collects the courseid database, which lists last transaction
                   2324: # times and course titles for all courseids
                   2325: #
                   2326:     my %courseidbuffer=();
1.921     raeburn  2327:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2328:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2329: 		          &escape($courselogs{$crsid}),
                   2330: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2331: 	    delete $courselogs{$crsid};
                   2332:         } else {
                   2333:             &logthis('Failed to flush log buffer for '.$crsid);
                   2334:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2335:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2336:                         " exceeded maximum size, deleting.</font>");
                   2337:                delete $courselogs{$crsid};
                   2338:             }
1.352     www      2339:         }
1.920     raeburn  2340:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2341:             'description' => $coursedescrbuf{$crsid},
                   2342:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2343:             'type'        => $coursetypebuf{$crsid},
                   2344:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2345:         };
1.191     harris41 2346:     }
1.352     www      2347: #
                   2348: # Write course id database (reverse lookup) to homeserver of courses 
                   2349: # Is used in pickcourse
                   2350: #
1.840     albertel 2351:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2352:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2353:                                     $courseidbuffer{$crs_home},
                   2354:                                     $crs_home,'timeonly');
1.352     www      2355:     }
                   2356: #
                   2357: # File accesses
                   2358: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2359: #
1.449     matthew  2360:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2361:         if ($entry =~ /___count$/) {
                   2362:             my ($dom,$name);
1.807     albertel 2363:             ($dom,$name,undef)=
1.811     albertel 2364: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2365:             if (! defined($dom) || $dom eq '' || 
                   2366:                 ! defined($name) || $name eq '') {
1.620     albertel 2367:                 my $cid = $env{'request.course.id'};
                   2368:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2369:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2370:             }
1.450     matthew  2371:             my $value = $accesshash{$entry};
                   2372:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2373:             my %temphash=($url => $value);
1.449     matthew  2374:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2375:             if ($result eq 'ok') {
                   2376:                 delete $accesshash{$entry};
                   2377:             } elsif ($result eq 'unknown_cmd') {
                   2378:                 # Target server has old code running on it.
1.450     matthew  2379:                 my %temphash=($entry => $value);
1.449     matthew  2380:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2381:                     delete $accesshash{$entry};
                   2382:                 }
                   2383:             }
                   2384:         } else {
1.811     albertel 2385:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2386:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2387:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2388:                 delete $accesshash{$entry};
                   2389:             }
1.185     www      2390:         }
1.191     harris41 2391:     }
1.352     www      2392: #
                   2393: # Roles
                   2394: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2395: #
1.800     albertel 2396:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2397:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2398: 	    split(/\:/,$entry);
                   2399:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2400:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2401:                 $rudom,$runame) eq 'ok') {
                   2402: 	    delete $userrolehash{$entry};
                   2403:         }
                   2404:     }
1.662     raeburn  2405: #
                   2406: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2407: #
                   2408:     my %domrolebuffer = ();
                   2409:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2410:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2411:         if ($domrolebuffer{$rudom}) {
                   2412:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2413:                       '='.&escape($domainrolehash{$entry});
                   2414:         } else {
                   2415:             $domrolebuffer{$rudom}.=&escape($entry).
                   2416:                       '='.&escape($domainrolehash{$entry});
                   2417:         }
                   2418:         delete $domainrolehash{$entry};
                   2419:     }
                   2420:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2421: 	my %servers = &get_servers($dom,'library');
                   2422: 	foreach my $tryserver (keys(%servers)) {
                   2423: 	    unless (&reply('domroleput:'.$dom.':'.
                   2424: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2425: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2426: 	    }
1.662     raeburn  2427:         }
                   2428:     }
1.186     www      2429:     $dumpcount++;
1.157     www      2430: }
                   2431: 
                   2432: sub courselog {
                   2433:     my $what=shift;
1.158     www      2434:     $what=time.':'.$what;
1.620     albertel 2435:     unless ($env{'request.course.id'}) { return ''; }
                   2436:     $coursedombuf{$env{'request.course.id'}}=
                   2437:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2438:     $coursenumbuf{$env{'request.course.id'}}=
                   2439:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2440:     $coursehombuf{$env{'request.course.id'}}=
                   2441:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2442:     $coursedescrbuf{$env{'request.course.id'}}=
                   2443:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2444:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2445:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2446:     $courseownerbuf{$env{'request.course.id'}}=
                   2447:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2448:     $coursetypebuf{$env{'request.course.id'}}=
                   2449:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2450:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2451: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2452:     } else {
1.620     albertel 2453: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2454:     }
1.620     albertel 2455:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2456: 	&flushcourselogs();
                   2457:     }
1.158     www      2458: }
                   2459: 
                   2460: sub courseacclog {
                   2461:     my $fnsymb=shift;
1.620     albertel 2462:     unless ($env{'request.course.id'}) { return ''; }
                   2463:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2464:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2465:         $what.=':POST';
1.583     matthew  2466:         # FIXME: Probably ought to escape things....
1.800     albertel 2467: 	foreach my $key (keys(%env)) {
                   2468:             if ($key=~/^form\.(.*)/) {
                   2469: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2470:             }
1.191     harris41 2471:         }
1.583     matthew  2472:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2473:         # FIXME: We should not be depending on a form parameter that someone
                   2474:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2475:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2476:             $what.= ':POST';
                   2477:             # FIXME: Probably ought to escape things....
                   2478:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2479:                                  'crsdiscuss') {
1.620     albertel 2480:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2481:             }
                   2482:         }
1.158     www      2483:     }
                   2484:     &courselog($what);
1.149     www      2485: }
                   2486: 
1.185     www      2487: sub countacc {
                   2488:     my $url=&declutter(shift);
1.458     matthew  2489:     return if (! defined($url) || $url eq '');
1.620     albertel 2490:     unless ($env{'request.course.id'}) { return ''; }
                   2491:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2492:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2493:     $accesshash{$key}++;
1.185     www      2494: }
1.349     www      2495: 
1.361     www      2496: sub linklog {
                   2497:     my ($from,$to)=@_;
                   2498:     $from=&declutter($from);
                   2499:     $to=&declutter($to);
                   2500:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2501:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2502: }
                   2503:   
1.349     www      2504: sub userrolelog {
                   2505:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2506:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2507:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2508:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2509:         ($trole=~/^ta/)) {
1.350     www      2510:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2511:        $userrolehash
                   2512:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2513:                     =$tend.':'.$tstart;
1.662     raeburn  2514:     }
1.898     albertel 2515:     if (($env{'request.role'} =~ /dc\./) &&
                   2516: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2517: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2518: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2519:        $userrolehash
                   2520:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2521:                     =$tend.':'.$tstart;
                   2522:     }
1.662     raeburn  2523:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2524:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2525:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2526:         ($trole=~/^sc/)) {
                   2527:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2528:        $domainrolehash
                   2529:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2530:                     = $tend.':'.$tstart;
                   2531:     }
1.351     www      2532: }
                   2533: 
1.957     raeburn  2534: sub courserolelog {
                   2535:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2536:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2537:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2538:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2539:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2540:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2541:             my $cdom = $1;
                   2542:             my $cnum = $2;
                   2543:             my $sec = $3;
                   2544:             my $namespace = 'rolelog';
                   2545:             my %storehash = (
                   2546:                                role    => $trole,
                   2547:                                start   => $tstart,
                   2548:                                end     => $tend,
                   2549:                                selfenroll => $selfenroll,
                   2550:                                context    => $context,
                   2551:                             );
                   2552:             if ($trole eq 'gr') {
                   2553:                 $namespace = 'groupslog';
                   2554:                 $storehash{'group'} = $sec;
                   2555:             } else {
                   2556:                 $storehash{'section'} = $sec;
                   2557:             }
                   2558:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2559:         }
                   2560:     }
                   2561:     return;
                   2562: }
                   2563: 
1.351     www      2564: sub get_course_adv_roles {
1.948     raeburn  2565:     my ($cid,$codes) = @_;
1.620     albertel 2566:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2567:     my %coursehash=&coursedescription($cid);
1.470     www      2568:     my %nothide=();
1.800     albertel 2569:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2570:         if ($user !~ /:/) {
                   2571: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2572:         } else {
                   2573:             $nothide{$user}=1;
                   2574:         }
1.470     www      2575:     }
1.351     www      2576:     my %returnhash=();
                   2577:     my %dumphash=
                   2578:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2579:     my $now=time;
1.800     albertel 2580:     foreach my $entry (keys %dumphash) {
                   2581: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2582:         if (($tstart) && ($tstart<0)) { next; }
                   2583:         if (($tend) && ($tend<$now)) { next; }
                   2584:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2585:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2586: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2587: 	if ((&privileged($username,$domain)) && 
                   2588: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2589: 	if ($role eq 'cr') { next; }
1.948     raeburn  2590:         if ($codes) {
                   2591:             if ($section) { $role .= ':'.$section; }
                   2592:             if ($returnhash{$role}) {
                   2593:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2594:             } else {
                   2595:                 $returnhash{$role}=$username.':'.$domain;
                   2596:             }
1.351     www      2597:         } else {
1.948     raeburn  2598:             my $key=&plaintext($role);
                   2599:             if ($section) { $key.=' (Section '.$section.')'; }
                   2600:             if ($returnhash{$key}) {
                   2601: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2602:             } else {
                   2603:                 $returnhash{$key}=$username.':'.$domain;
                   2604:             }
1.351     www      2605:         }
1.948     raeburn  2606:     }
1.400     www      2607:     return %returnhash;
                   2608: }
                   2609: 
                   2610: sub get_my_roles {
1.937     raeburn  2611:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2612:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2613:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2614:     my (%dumphash,%nothide);
1.858     raeburn  2615:     if ($context eq 'userroles') { 
                   2616:         %dumphash = &dump('roles',$udom,$uname);
                   2617:     } else {
                   2618:         %dumphash=
1.400     www      2619:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2620:         if ($hidepriv) {
                   2621:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2622:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2623:                 if ($user !~ /:/) {
                   2624:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2625:                 } else {
                   2626:                     $nothide{$user} = 1;
                   2627:                 }
                   2628:             }
                   2629:         }
1.858     raeburn  2630:     }
1.400     www      2631:     my %returnhash=();
                   2632:     my $now=time;
1.800     albertel 2633:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2634:         my ($role,$tend,$tstart);
                   2635:         if ($context eq 'userroles') {
                   2636: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2637:         } else {
                   2638:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2639:         }
1.400     www      2640:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2641:         my $status = 'active';
1.939     raeburn  2642:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2643:             $status = 'previous';
                   2644:         } 
                   2645:         if (($tstart) && ($now<$tstart)) {
                   2646:             $status = 'future';
                   2647:         }
                   2648:         if (ref($types) eq 'ARRAY') {
                   2649:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2650:                 next;
                   2651:             } 
                   2652:         } else {
                   2653:             if ($status ne 'active') {
                   2654:                 next;
                   2655:             }
                   2656:         }
1.867     raeburn  2657:         my ($rolecode,$username,$domain,$section,$area);
                   2658:         if ($context eq 'userroles') {
                   2659:             ($area,$rolecode) = split(/_/,$entry);
                   2660:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2661:         } else {
                   2662:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2663:         }
1.832     raeburn  2664:         if (ref($roledoms) eq 'ARRAY') {
                   2665:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2666:                 next;
                   2667:             }
                   2668:         }
                   2669:         if (ref($roles) eq 'ARRAY') {
                   2670:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2671:                 if ($role =~ /^cr\//) {
                   2672:                     if (!grep(/^cr$/,@{$roles})) {
                   2673:                         next;
                   2674:                     }
                   2675:                 } else {
                   2676:                     next;
                   2677:                 }
1.832     raeburn  2678:             }
1.867     raeburn  2679:         }
1.937     raeburn  2680:         if ($hidepriv) {
                   2681:             if ((&privileged($username,$domain)) &&
                   2682:                 (!$nothide{$username.':'.$domain})) { 
                   2683:                 next;
                   2684:             }
                   2685:         }
1.933     raeburn  2686:         if ($withsec) {
                   2687:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2688:                 $tstart.':'.$tend;
                   2689:         } else {
                   2690:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2691:         }
1.832     raeburn  2692:     }
1.373     www      2693:     return %returnhash;
1.399     www      2694: }
                   2695: 
                   2696: # ----------------------------------------------------- Frontpage Announcements
                   2697: #
                   2698: #
                   2699: 
                   2700: sub postannounce {
                   2701:     my ($server,$text)=@_;
1.844     albertel 2702:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2703:     unless ($text=~/\w/) { $text=''; }
                   2704:     return &reply('setannounce:'.&escape($text),$server);
                   2705: }
                   2706: 
                   2707: sub getannounce {
1.448     albertel 2708: 
                   2709:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2710: 	my $announcement='';
1.800     albertel 2711: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2712: 	close($fh);
1.399     www      2713: 	if ($announcement=~/\w/) { 
                   2714: 	    return 
                   2715:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2716:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2717: 	} else {
                   2718: 	    return '';
                   2719: 	}
                   2720:     } else {
                   2721: 	return '';
                   2722:     }
1.351     www      2723: }
1.353     www      2724: 
                   2725: # ---------------------------------------------------------- Course ID routines
                   2726: # Deal with domain's nohist_courseid.db files
                   2727: #
                   2728: 
                   2729: sub courseidput {
1.921     raeburn  2730:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2731:     my $outcome;
                   2732:     if ($caller eq 'timeonly') {
                   2733:         my $cids = '';
                   2734:         foreach my $item (keys(%$storehash)) {
                   2735:             $cids.=&escape($item).'&';
                   2736:         }
                   2737:         $cids=~s/\&$//;
                   2738:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2739:                           $coursehome);       
                   2740:     } else {
                   2741:         my $items = '';
                   2742:         foreach my $item (keys(%$storehash)) {
                   2743:             $items.= &escape($item).'='.
                   2744:                      &freeze_escape($$storehash{$item}).'&';
                   2745:         }
                   2746:         $items=~s/\&$//;
                   2747:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2748:                           $coursehome);
1.918     raeburn  2749:     }
                   2750:     if ($outcome eq 'unknown_cmd') {
                   2751:         my $what;
                   2752:         foreach my $cid (keys(%$storehash)) {
                   2753:             $what .= &escape($cid).'=';
1.921     raeburn  2754:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2755:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2756:             }
                   2757:             $what =~ s/\:$/&/;
                   2758:         }
                   2759:         $what =~ s/\&$//;  
                   2760:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2761:     } else {
                   2762:         return $outcome;
                   2763:     }
1.353     www      2764: }
                   2765: 
                   2766: sub courseiddump {
1.921     raeburn  2767:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2768:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2769:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2770:     my $as_hash = 1;
                   2771:     my %returnhash;
                   2772:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2773:     my %libserv = &all_library();
                   2774:     foreach my $tryserver (keys(%libserv)) {
                   2775:         if ( (  $hostidflag == 1 
                   2776: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2777: 	     || (!defined($hostidflag)) ) {
                   2778: 
1.918     raeburn  2779: 	    if (($domfilter eq '') ||
                   2780: 		(&host_domain($tryserver) eq $domfilter)) {
                   2781:                 my $rep = 
                   2782:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2783:                          $sincefilter.':'.&escape($descfilter).':'.
                   2784:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2785:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2786:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2787:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2788:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2789:                 my @pairs=split(/\&/,$rep);
                   2790:                 foreach my $item (@pairs) {
                   2791:                     my ($key,$value)=split(/\=/,$item,2);
                   2792:                     $key = &unescape($key);
                   2793:                     next if ($key =~ /^error: 2 /);
                   2794:                     my $result = &thaw_unescape($value);
                   2795:                     if (ref($result) eq 'HASH') {
                   2796:                         $returnhash{$key}=$result;
                   2797:                     } else {
1.921     raeburn  2798:                         my @responses = split(/:/,$value);
                   2799:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2800:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2801:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2802:                         }
                   2803:                     } 
1.353     www      2804:                 }
                   2805:             }
                   2806:         }
                   2807:     }
                   2808:     return %returnhash;
                   2809: }
                   2810: 
1.658     raeburn  2811: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2812: 
                   2813: sub dcmailput {
1.685     raeburn  2814:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2815:     my $status = &Apache::lonnet::critical(
1.740     www      2816:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2817:        &escape($message),$server);
1.662     raeburn  2818:     return $status;
                   2819: }
                   2820: 
1.658     raeburn  2821: sub dcmaildump {
                   2822:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2823:     my %returnhash=();
1.846     albertel 2824: 
                   2825:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2826:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2827:                                                          &escape($enddate).':';
                   2828: 	my @esc_senders=map { &escape($_)} @$senders;
                   2829: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2830: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2831:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2832:             if (($key) && ($value)) {
                   2833:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2834:             }
                   2835:         }
                   2836:     }
                   2837:     return %returnhash;
                   2838: }
1.662     raeburn  2839: # ---------------------------------------------------------- Domain roles
                   2840: 
                   2841: sub get_domain_roles {
                   2842:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2843:     if (undef($startdate) || $startdate eq '') {
                   2844:         $startdate = '.';
                   2845:     }
                   2846:     if (undef($enddate) || $enddate eq '') {
                   2847:         $enddate = '.';
                   2848:     }
1.922     raeburn  2849:     my $rolelist;
                   2850:     if (ref($roles) eq 'ARRAY') {
                   2851:         $rolelist = join(':',@{$roles});
                   2852:     }
1.662     raeburn  2853:     my %personnel = ();
1.841     albertel 2854: 
                   2855:     my %servers = &get_servers($dom,'library');
                   2856:     foreach my $tryserver (keys(%servers)) {
                   2857: 	%{$personnel{$tryserver}}=();
                   2858: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2859: 					    &escape($startdate).':'.
                   2860: 					    &escape($enddate).':'.
                   2861: 					    &escape($rolelist), $tryserver))) {
                   2862: 	    my ($key,$value) = split(/\=/,$line,2);
                   2863: 	    if (($key) && ($value)) {
                   2864: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2865: 	    }
                   2866: 	}
1.662     raeburn  2867:     }
                   2868:     return %personnel;
                   2869: }
1.658     raeburn  2870: 
1.149     www      2871: # ----------------------------------------------------------- Check out an item
                   2872: 
1.504     albertel 2873: sub get_first_access {
                   2874:     my ($type,$argsymb)=@_;
1.790     albertel 2875:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2876:     if ($argsymb) { $symb=$argsymb; }
                   2877:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2878:     if ($type eq 'course') {
                   2879: 	$res='course';
                   2880:     } elsif ($type eq 'map') {
1.588     albertel 2881: 	$res=&symbread($map);
                   2882:     } else {
                   2883: 	$res=$symb;
                   2884:     }
                   2885:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2886:     return $times{"$courseid\0$res"};
1.504     albertel 2887: }
                   2888: 
                   2889: sub set_first_access {
                   2890:     my ($type)=@_;
1.790     albertel 2891:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2892:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2893:     if ($type eq 'course') {
                   2894: 	$res='course';
                   2895:     } elsif ($type eq 'map') {
1.588     albertel 2896: 	$res=&symbread($map);
                   2897:     } else {
                   2898: 	$res=$symb;
                   2899:     }
                   2900:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2901:     if (!$firstaccess) {
1.588     albertel 2902: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2903:     }
                   2904:     return 'already_set';
1.504     albertel 2905: }
                   2906: 
1.149     www      2907: sub checkout {
                   2908:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2909:     my $now=time;
                   2910:     my $lonhost=$perlvar{'lonHostID'};
                   2911:     my $infostr=&escape(
1.234     www      2912:                  'CHECKOUTTOKEN&'.
1.149     www      2913:                  $tuname.'&'.
                   2914:                  $tudom.'&'.
                   2915:                  $tcrsid.'&'.
                   2916:                  $symb.'&'.
                   2917: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2918:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2919:     if ($token=~/^error\:/) { 
1.672     albertel 2920:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2921:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2922:                  "</font>");
                   2923:         return ''; 
                   2924:     }
                   2925: 
1.149     www      2926:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2927:     $token=~tr/a-z/A-Z/;
                   2928: 
1.153     www      2929:     my %infohash=('resource.0.outtoken' => $token,
                   2930:                   'resource.0.checkouttime' => $now,
                   2931:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2932: 
                   2933:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2934:        return '';
1.151     www      2935:     } else {
1.672     albertel 2936:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2937:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2938:                  "</font>");
1.149     www      2939:     }    
                   2940: 
                   2941:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2942:                          &escape('Checkout '.$infostr.' - '.
                   2943:                                                  $token)) ne 'ok') {
                   2944: 	return '';
1.151     www      2945:     } else {
1.672     albertel 2946:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2947:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2948:                  "</font>");
1.149     www      2949:     }
1.151     www      2950:     return $token;
1.149     www      2951: }
                   2952: 
                   2953: # ------------------------------------------------------------ Check in an item
                   2954: 
                   2955: sub checkin {
                   2956:     my $token=shift;
1.150     www      2957:     my $now=time;
                   2958:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2959:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2960:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2961:     $dtoken=~s/\W/\_/g;
1.234     www      2962:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2963:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2964: 
1.154     www      2965:     unless (($tuname) && ($tudom)) {
                   2966:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2967:         return '';
                   2968:     }
                   2969:     
                   2970:     unless (&allowed('mgr',$tcrsid)) {
                   2971:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2972:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2973:         return '';
                   2974:     }
                   2975: 
1.153     www      2976:     my %infohash=('resource.0.intoken' => $token,
                   2977:                   'resource.0.checkintime' => $now,
                   2978:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2979: 
                   2980:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2981:        return '';
                   2982:     }    
                   2983: 
                   2984:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2985:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2986: 	return '';
                   2987:     }
                   2988: 
                   2989:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2990: }
                   2991: 
                   2992: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2993: 
                   2994: sub expirespread {
                   2995:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2996:     my $cid=$env{'request.course.id'}; 
1.110     www      2997:     if ($cid) {
                   2998:        my $now=time;
                   2999:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3000:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3001:                             $env{'course.'.$cid.'.num'}.
1.110     www      3002: 	        	    ':nohist_expirationdates:'.
                   3003:                             &escape($key).'='.$now,
1.620     albertel 3004:                             $env{'course.'.$cid.'.home'})
1.110     www      3005:     }
                   3006:     return 'ok';
1.14      www      3007: }
                   3008: 
1.109     www      3009: # ----------------------------------------------------- Devalidate Spreadsheets
                   3010: 
                   3011: sub devalidate {
1.325     www      3012:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3013:     my $cid=$env{'request.course.id'}; 
1.109     www      3014:     if ($cid) {
1.391     matthew  3015:         # delete the stored spreadsheets for
                   3016:         # - the student level sheet of this user in course's homespace
                   3017:         # - the assessment level sheet for this resource 
                   3018:         #   for this user in user's homespace
1.553     albertel 3019: 	# - current conditional state info
1.325     www      3020: 	my $key=$uname.':'.$udom.':';
1.109     www      3021:         my $status=
1.299     matthew  3022: 	    &del('nohist_calculatedsheets',
1.391     matthew  3023: 		 [$key.'studentcalc:'],
1.620     albertel 3024: 		 $env{'course.'.$cid.'.domain'},
                   3025: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3026: 		.' '.
                   3027: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3028: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3029:         unless ($status eq 'ok ok') {
                   3030:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3031:                     $uname.' at '.$udom.' for '.
1.109     www      3032: 		    $symb.': '.$status);
1.133     albertel 3033:         }
1.553     albertel 3034: 	&delenv('user.state.'.$cid);
1.109     www      3035:     }
                   3036: }
                   3037: 
1.265     albertel 3038: sub get_scalar {
                   3039:     my ($string,$end) = @_;
                   3040:     my $value;
                   3041:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3042: 	$value = $1;
                   3043:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3044: 	$value = $1;
                   3045:     }
                   3046:     return &unescape($value);
                   3047: }
                   3048: 
                   3049: sub array2str {
                   3050:   my (@array) = @_;
                   3051:   my $result=&arrayref2str(\@array);
                   3052:   $result=~s/^__ARRAY_REF__//;
                   3053:   $result=~s/__END_ARRAY_REF__$//;
                   3054:   return $result;
                   3055: }
                   3056: 
1.204     albertel 3057: sub arrayref2str {
                   3058:   my ($arrayref) = @_;
1.265     albertel 3059:   my $result='__ARRAY_REF__';
1.204     albertel 3060:   foreach my $elem (@$arrayref) {
1.265     albertel 3061:     if(ref($elem) eq 'ARRAY') {
                   3062:       $result.=&arrayref2str($elem).'&';
                   3063:     } elsif(ref($elem) eq 'HASH') {
                   3064:       $result.=&hashref2str($elem).'&';
                   3065:     } elsif(ref($elem)) {
                   3066:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3067:     } else {
                   3068:       $result.=&escape($elem).'&';
                   3069:     }
                   3070:   }
                   3071:   $result=~s/\&$//;
1.265     albertel 3072:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3073:   return $result;
                   3074: }
                   3075: 
1.168     albertel 3076: sub hash2str {
1.204     albertel 3077:   my (%hash) = @_;
                   3078:   my $result=&hashref2str(\%hash);
1.265     albertel 3079:   $result=~s/^__HASH_REF__//;
                   3080:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3081:   return $result;
                   3082: }
                   3083: 
                   3084: sub hashref2str {
                   3085:   my ($hashref)=@_;
1.265     albertel 3086:   my $result='__HASH_REF__';
1.800     albertel 3087:   foreach my $key (sort(keys(%$hashref))) {
                   3088:     if (ref($key) eq 'ARRAY') {
                   3089:       $result.=&arrayref2str($key).'=';
                   3090:     } elsif (ref($key) eq 'HASH') {
                   3091:       $result.=&hashref2str($key).'=';
                   3092:     } elsif (ref($key)) {
1.265     albertel 3093:       $result.='=';
1.800     albertel 3094:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3095:     } else {
1.800     albertel 3096: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3097:     }
                   3098: 
1.800     albertel 3099:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3100:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3101:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3102:       $result.=&hashref2str($hashref->{$key}).'&';
                   3103:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3104:        $result.='&';
1.800     albertel 3105:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3106:     } else {
1.800     albertel 3107:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3108:     }
                   3109:   }
1.168     albertel 3110:   $result=~s/\&$//;
1.265     albertel 3111:   $result .= '__END_HASH_REF__';
1.168     albertel 3112:   return $result;
                   3113: }
                   3114: 
                   3115: sub str2hash {
1.265     albertel 3116:     my ($string)=@_;
                   3117:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3118:     return %$hash;
                   3119: }
                   3120: 
                   3121: sub str2hashref {
1.168     albertel 3122:   my ($string) = @_;
1.265     albertel 3123: 
                   3124:   my %hash;
                   3125: 
                   3126:   if($string !~ /^__HASH_REF__/) {
                   3127:       if (! ($string eq '' || !defined($string))) {
                   3128: 	  $hash{'error'}='Not hash reference';
                   3129:       }
                   3130:       return (\%hash, $string);
                   3131:   }
                   3132: 
                   3133:   $string =~ s/^__HASH_REF__//;
                   3134: 
                   3135:   while($string !~ /^__END_HASH_REF__/) {
                   3136:       #key
                   3137:       my $key='';
                   3138:       if($string =~ /^__HASH_REF__/) {
                   3139:           ($key, $string)=&str2hashref($string);
                   3140:           if(defined($key->{'error'})) {
                   3141:               $hash{'error'}='Bad data';
                   3142:               return (\%hash, $string);
                   3143:           }
                   3144:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3145:           ($key, $string)=&str2arrayref($string);
                   3146:           if($key->[0] eq 'Array reference error') {
                   3147:               $hash{'error'}='Bad data';
                   3148:               return (\%hash, $string);
                   3149:           }
                   3150:       } else {
                   3151:           $string =~ s/^(.*?)=//;
1.267     albertel 3152: 	  $key=&unescape($1);
1.265     albertel 3153:       }
                   3154:       $string =~ s/^=//;
                   3155: 
                   3156:       #value
                   3157:       my $value='';
                   3158:       if($string =~ /^__HASH_REF__/) {
                   3159:           ($value, $string)=&str2hashref($string);
                   3160:           if(defined($value->{'error'})) {
                   3161:               $hash{'error'}='Bad data';
                   3162:               return (\%hash, $string);
                   3163:           }
                   3164:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3165:           ($value, $string)=&str2arrayref($string);
                   3166:           if($value->[0] eq 'Array reference error') {
                   3167:               $hash{'error'}='Bad data';
                   3168:               return (\%hash, $string);
                   3169:           }
                   3170:       } else {
                   3171: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3172:       }
                   3173:       $string =~ s/^&//;
                   3174: 
                   3175:       $hash{$key}=$value;
1.204     albertel 3176:   }
1.265     albertel 3177: 
                   3178:   $string =~ s/^__END_HASH_REF__//;
                   3179: 
                   3180:   return (\%hash, $string);
1.204     albertel 3181: }
                   3182: 
                   3183: sub str2array {
1.265     albertel 3184:     my ($string)=@_;
                   3185:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3186:     return @$array;
                   3187: }
                   3188: 
                   3189: sub str2arrayref {
1.204     albertel 3190:   my ($string) = @_;
1.265     albertel 3191:   my @array;
                   3192: 
                   3193:   if($string !~ /^__ARRAY_REF__/) {
                   3194:       if (! ($string eq '' || !defined($string))) {
                   3195: 	  $array[0]='Array reference error';
                   3196:       }
                   3197:       return (\@array, $string);
                   3198:   }
                   3199: 
                   3200:   $string =~ s/^__ARRAY_REF__//;
                   3201: 
                   3202:   while($string !~ /^__END_ARRAY_REF__/) {
                   3203:       my $value='';
                   3204:       if($string =~ /^__HASH_REF__/) {
                   3205:           ($value, $string)=&str2hashref($string);
                   3206:           if(defined($value->{'error'})) {
                   3207:               $array[0] ='Array reference error';
                   3208:               return (\@array, $string);
                   3209:           }
                   3210:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3211:           ($value, $string)=&str2arrayref($string);
                   3212:           if($value->[0] eq 'Array reference error') {
                   3213:               $array[0] ='Array reference error';
                   3214:               return (\@array, $string);
                   3215:           }
                   3216:       } else {
                   3217: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3218:       }
                   3219:       $string =~ s/^&//;
                   3220: 
                   3221:       push(@array, $value);
1.191     harris41 3222:   }
1.265     albertel 3223: 
                   3224:   $string =~ s/^__END_ARRAY_REF__//;
                   3225: 
                   3226:   return (\@array, $string);
1.168     albertel 3227: }
                   3228: 
1.167     albertel 3229: # -------------------------------------------------------------------Temp Store
                   3230: 
1.168     albertel 3231: sub tmpreset {
                   3232:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3233:   if (!$symb) {
                   3234:     $symb=&symbread();
1.620     albertel 3235:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3236:   }
                   3237:   $symb=escape($symb);
                   3238: 
1.620     albertel 3239:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3240:   $namespace=~s/\//\_/g;
                   3241:   $namespace=~s/\W//g;
                   3242: 
1.620     albertel 3243:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3244:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3245:   if ($domain eq 'public' && $stuname eq 'public') {
                   3246:       $stuname=$ENV{'REMOTE_ADDR'};
                   3247:   }
1.168     albertel 3248:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3249:   my %hash;
                   3250:   if (tie(%hash,'GDBM_File',
                   3251: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3252: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3253:     foreach my $key (keys %hash) {
1.180     albertel 3254:       if ($key=~ /:$symb/) {
1.168     albertel 3255: 	delete($hash{$key});
                   3256:       }
                   3257:     }
                   3258:   }
                   3259: }
                   3260: 
1.167     albertel 3261: sub tmpstore {
1.168     albertel 3262:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3263: 
                   3264:   if (!$symb) {
                   3265:     $symb=&symbread();
1.620     albertel 3266:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3267:   }
                   3268:   $symb=escape($symb);
                   3269: 
                   3270:   if (!$namespace) {
                   3271:     # I don't think we would ever want to store this for a course.
                   3272:     # it seems this will only be used if we don't have a course.
1.620     albertel 3273:     #$namespace=$env{'request.course.id'};
1.168     albertel 3274:     #if (!$namespace) {
1.620     albertel 3275:       $namespace=$env{'request.state'};
1.168     albertel 3276:     #}
                   3277:   }
                   3278:   $namespace=~s/\//\_/g;
                   3279:   $namespace=~s/\W//g;
1.620     albertel 3280:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3281:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3282:   if ($domain eq 'public' && $stuname eq 'public') {
                   3283:       $stuname=$ENV{'REMOTE_ADDR'};
                   3284:   }
1.168     albertel 3285:   my $now=time;
                   3286:   my %hash;
                   3287:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3288:   if (tie(%hash,'GDBM_File',
                   3289: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3290: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3291:     $hash{"version:$symb"}++;
                   3292:     my $version=$hash{"version:$symb"};
                   3293:     my $allkeys=''; 
                   3294:     foreach my $key (keys(%$storehash)) {
                   3295:       $allkeys.=$key.':';
1.591     albertel 3296:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3297:     }
                   3298:     $hash{"$version:$symb:timestamp"}=$now;
                   3299:     $allkeys.='timestamp';
                   3300:     $hash{"$version:keys:$symb"}=$allkeys;
                   3301:     if (untie(%hash)) {
                   3302:       return 'ok';
                   3303:     } else {
                   3304:       return "error:$!";
                   3305:     }
                   3306:   } else {
                   3307:     return "error:$!";
                   3308:   }
                   3309: }
1.167     albertel 3310: 
1.168     albertel 3311: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3312: 
1.168     albertel 3313: sub tmprestore {
                   3314:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3315: 
1.168     albertel 3316:   if (!$symb) {
                   3317:     $symb=&symbread();
1.620     albertel 3318:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3319:   }
                   3320:   $symb=escape($symb);
                   3321: 
1.620     albertel 3322:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3323: 
1.620     albertel 3324:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3325:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3326:   if ($domain eq 'public' && $stuname eq 'public') {
                   3327:       $stuname=$ENV{'REMOTE_ADDR'};
                   3328:   }
1.168     albertel 3329:   my %returnhash;
                   3330:   $namespace=~s/\//\_/g;
                   3331:   $namespace=~s/\W//g;
                   3332:   my %hash;
                   3333:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3334:   if (tie(%hash,'GDBM_File',
                   3335: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3336: 	  &GDBM_READER(),0640)) {
1.168     albertel 3337:     my $version=$hash{"version:$symb"};
                   3338:     $returnhash{'version'}=$version;
                   3339:     my $scope;
                   3340:     for ($scope=1;$scope<=$version;$scope++) {
                   3341:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3342:       my @keys=split(/:/,$vkeys);
                   3343:       my $key;
                   3344:       $returnhash{"$scope:keys"}=$vkeys;
                   3345:       foreach $key (@keys) {
1.591     albertel 3346: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3347: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3348:       }
                   3349:     }
1.168     albertel 3350:     if (!(untie(%hash))) {
                   3351:       return "error:$!";
                   3352:     }
                   3353:   } else {
                   3354:     return "error:$!";
                   3355:   }
                   3356:   return %returnhash;
1.167     albertel 3357: }
                   3358: 
1.9       www      3359: # ----------------------------------------------------------------------- Store
                   3360: 
                   3361: sub store {
1.124     www      3362:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3363:     my $home='';
                   3364: 
1.168     albertel 3365:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3366: 
1.213     www      3367:     $symb=&symbclean($symb);
1.122     albertel 3368:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3369: 
1.620     albertel 3370:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3371:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3372: 
                   3373:     &devalidate($symb,$stuname,$domain);
1.109     www      3374: 
                   3375:     $symb=escape($symb);
1.187     www      3376:     if (!$namespace) { 
1.620     albertel 3377:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3378:           return ''; 
                   3379:        } 
                   3380:     }
1.620     albertel 3381:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3382: 
                   3383:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3384:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3385: 
1.12      www      3386:     my $namevalue='';
1.800     albertel 3387:     foreach my $key (keys(%$storehash)) {
                   3388:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3389:     }
1.12      www      3390:     $namevalue=~s/\&$//;
1.187     www      3391:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3392:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3393: }
                   3394: 
1.47      www      3395: # -------------------------------------------------------------- Critical Store
                   3396: 
                   3397: sub cstore {
1.124     www      3398:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3399:     my $home='';
                   3400: 
1.168     albertel 3401:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3402: 
1.213     www      3403:     $symb=&symbclean($symb);
1.122     albertel 3404:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3405: 
1.620     albertel 3406:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3407:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3408: 
                   3409:     &devalidate($symb,$stuname,$domain);
1.109     www      3410: 
                   3411:     $symb=escape($symb);
1.187     www      3412:     if (!$namespace) { 
1.620     albertel 3413:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3414:           return ''; 
                   3415:        } 
                   3416:     }
1.620     albertel 3417:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3418: 
                   3419:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3420:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3421: 
1.47      www      3422:     my $namevalue='';
1.800     albertel 3423:     foreach my $key (keys(%$storehash)) {
                   3424:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3425:     }
1.47      www      3426:     $namevalue=~s/\&$//;
1.187     www      3427:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3428:     return critical
                   3429:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3430: }
                   3431: 
1.9       www      3432: # --------------------------------------------------------------------- Restore
                   3433: 
                   3434: sub restore {
1.124     www      3435:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3436:     my $home='';
                   3437: 
1.168     albertel 3438:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3439: 
1.122     albertel 3440:     if (!$symb) {
                   3441:       unless ($symb=escape(&symbread())) { return ''; }
                   3442:     } else {
1.213     www      3443:       $symb=&escape(&symbclean($symb));
1.122     albertel 3444:     }
1.188     www      3445:     if (!$namespace) { 
1.620     albertel 3446:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3447:           return ''; 
                   3448:        } 
                   3449:     }
1.620     albertel 3450:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3451:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3452:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3453:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3454: 
1.12      www      3455:     my %returnhash=();
1.800     albertel 3456:     foreach my $line (split(/\&/,$answer)) {
                   3457: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3458:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3459:     }
1.75      www      3460:     my $version;
                   3461:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3462:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3463:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3464:        }
1.75      www      3465:     }
1.13      www      3466:     return %returnhash;
1.34      www      3467: }
                   3468: 
                   3469: # ---------------------------------------------------------- Course Description
                   3470: 
                   3471: sub coursedescription {
1.731     albertel 3472:     my ($courseid,$args)=@_;
1.34      www      3473:     $courseid=~s/^\///;
1.49      www      3474:     $courseid=~s/\_/\//g;
1.34      www      3475:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3476:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3477:     my $normalid=$cdomain.'_'.$cnum;
                   3478:     # need to always cache even if we get errors otherwise we keep 
                   3479:     # trying and trying and trying to get the course description.
                   3480:     my %envhash=();
                   3481:     my %returnhash=();
1.731     albertel 3482:     
                   3483:     my $expiretime=600;
                   3484:     if ($env{'request.course.id'} eq $normalid) {
                   3485: 	$expiretime=120;
                   3486:     }
                   3487: 
                   3488:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3489:     if (!$args->{'freshen_cache'}
                   3490: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3491: 	foreach my $key (keys(%env)) {
                   3492: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3493: 	    my ($setting) = $1;
                   3494: 	    $returnhash{$setting} = $env{$key};
                   3495: 	}
                   3496: 	return %returnhash;
                   3497:     }
                   3498: 
                   3499:     # get the data agin
                   3500:     if (!$args->{'one_time'}) {
                   3501: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3502:     }
1.811     albertel 3503: 
1.34      www      3504:     if ($chome ne 'no_host') {
1.302     albertel 3505:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3506:        if (!exists($returnhash{'con_lost'})) {
                   3507:            $returnhash{'home'}= $chome;
                   3508: 	   $returnhash{'domain'} = $cdomain;
                   3509: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3510:            if (!defined($returnhash{'type'})) {
                   3511:                $returnhash{'type'} = 'Course';
                   3512:            }
1.130     albertel 3513:            while (my ($name,$value) = each %returnhash) {
1.53      www      3514:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3515:            }
1.270     www      3516:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3517:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3518: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3519:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3520:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3521:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3522:        }
                   3523:     }
1.731     albertel 3524:     if (!$args->{'one_time'}) {
1.949     raeburn  3525: 	&appenv(\%envhash);
1.731     albertel 3526:     }
1.302     albertel 3527:     return %returnhash;
1.461     www      3528: }
                   3529: 
                   3530: # -------------------------------------------------See if a user is privileged
                   3531: 
                   3532: sub privileged {
                   3533:     my ($username,$domain)=@_;
                   3534:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3535: 			&homeserver($username,$domain));
                   3536:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3537:     my $now=time;
                   3538:     if ($rolesdump ne '') {
1.800     albertel 3539:         foreach my $entry (split(/&/,$rolesdump)) {
                   3540: 	    if ($entry!~/^rolesdef_/) {
                   3541: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3542: 		$area=~s/\_\w\w$//;
                   3543: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3544: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3545: 		    my $active=1;
                   3546: 		    if ($tend) {
                   3547: 			if ($tend<$now) { $active=0; }
                   3548: 		    }
                   3549: 		    if ($tstart) {
                   3550: 			if ($tstart>$now) { $active=0; }
                   3551: 		    }
                   3552: 		    if ($active) { return 1; }
                   3553: 		}
                   3554: 	    }
                   3555: 	}
                   3556:     }
                   3557:     return 0;
1.9       www      3558: }
1.1       albertel 3559: 
1.103     harris41 3560: # -------------------------------------------------------- Get user privileges
1.11      www      3561: 
                   3562: sub rolesinit {
                   3563:     my ($domain,$username,$authhost)=@_;
                   3564:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3565:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3566:     my %allroles=();
1.678     raeburn  3567:     my %allgroups=();   
1.11      www      3568:     my $now=time;
1.743     albertel 3569:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3570:     my $group_privs;
1.11      www      3571: 
                   3572:     if ($rolesdump ne '') {
1.800     albertel 3573:         foreach my $entry (split(/&/,$rolesdump)) {
                   3574: 	  if ($entry!~/^rolesdef_/) {
                   3575:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3576: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3577:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3578: 	    if ($role=~/^cr/) { 
1.807     albertel 3579: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3580: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3581: 		    ($tend,$tstart)=split('_',$trest);
                   3582: 		} else {
                   3583: 		    $trole=$role;
                   3584: 		}
1.678     raeburn  3585:             } elsif ($role =~ m|^gr/|) {
                   3586:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3587:                 ($trole,$group_privs) = split(/\//,$trole);
                   3588:                 $group_privs = &unescape($group_privs);
1.587     albertel 3589: 	    } else {
                   3590: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3591: 	    }
1.743     albertel 3592: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3593: 					 $username);
                   3594: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3595:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3596:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3597:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3598: 		my $spec=$trole.'.'.$area;
                   3599: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3600: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3601:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3602:                 } elsif ($trole eq 'gr') {
                   3603:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3604: 		} else {
1.567     raeburn  3605:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3606: 		}
1.12      www      3607:             }
1.662     raeburn  3608:           }
1.191     harris41 3609:         }
1.743     albertel 3610:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3611:         $userroles{'user.adv'}    = $adv;
                   3612: 	$userroles{'user.author'} = $author;
1.620     albertel 3613:         $env{'user.adv'}=$adv;
1.11      www      3614:     }
1.743     albertel 3615:     return \%userroles;  
1.11      www      3616: }
                   3617: 
1.567     raeburn  3618: sub set_arearole {
                   3619:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3620: # log the associated role with the area
                   3621:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3622:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3623: }
                   3624: 
                   3625: sub custom_roleprivs {
                   3626:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3627:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3628:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3629:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3630:         my ($rdummy,$roledef)=
                   3631:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3632:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3633:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3634:             if (defined($syspriv)) {
                   3635:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3636:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3637:             }
                   3638:             if ($tdomain ne '') {
                   3639:                 if (defined($dompriv)) {
                   3640:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3641:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3642:                 }
                   3643:                 if (($trest ne '') && (defined($coursepriv))) {
                   3644:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3645:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3646:                 }
                   3647:             }
                   3648:         }
                   3649:     }
                   3650: }
                   3651: 
1.678     raeburn  3652: sub group_roleprivs {
                   3653:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3654:     my $access = 1;
                   3655:     my $now = time;
                   3656:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3657:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3658:     if ($access) {
1.811     albertel 3659:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3660:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3661:     }
                   3662: }
1.567     raeburn  3663: 
                   3664: sub standard_roleprivs {
                   3665:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3666:     if (defined($pr{$trole.':s'})) {
                   3667:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3668:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3669:     }
                   3670:     if ($tdomain ne '') {
                   3671:         if (defined($pr{$trole.':d'})) {
                   3672:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3673:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3674:         }
                   3675:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3676:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3677:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3678:         }
                   3679:     }
                   3680: }
                   3681: 
                   3682: sub set_userprivs {
1.678     raeburn  3683:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3684:     my $author=0;
                   3685:     my $adv=0;
1.678     raeburn  3686:     my %grouproles = ();
                   3687:     if (keys(%{$allgroups}) > 0) {
                   3688:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3689:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3690:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3691:                 $trole = $1;
                   3692:                 $area = $2;
1.681     raeburn  3693:                 $sec = $3;
                   3694:                 $extendedarea = $area.$sec;
                   3695:                 if (exists($$allgroups{$area})) {
                   3696:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3697:                         my $spec = $trole.'.'.$extendedarea;
                   3698:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3699:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3700:                     }
                   3701:                 }
                   3702:             }
                   3703:         }
                   3704:     }
1.800     albertel 3705:     foreach my $group (keys(%grouproles)) {
                   3706:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3707:     }
1.800     albertel 3708:     foreach my $role (keys(%{$allroles})) {
                   3709:         my %thesepriv;
1.941     raeburn  3710:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3711:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3712:             if ($item ne '') {
                   3713:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3714:                 if ($restrictions eq '') {
                   3715:                     $thesepriv{$privilege}='F';
                   3716:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3717:                     $thesepriv{$privilege}.=$restrictions;
                   3718:                 }
                   3719:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3720:             }
                   3721:         }
                   3722:         my $thesestr='';
1.800     albertel 3723:         foreach my $priv (keys(%thesepriv)) {
                   3724: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3725: 	}
                   3726:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3727:     }
                   3728:     return ($author,$adv);
                   3729: }
                   3730: 
1.12      www      3731: # --------------------------------------------------------------- get interface
                   3732: 
                   3733: sub get {
1.131     albertel 3734:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3735:    my $items='';
1.800     albertel 3736:    foreach my $item (@$storearr) {
                   3737:        $items.=&escape($item).'&';
1.191     harris41 3738:    }
1.12      www      3739:    $items=~s/\&$//;
1.620     albertel 3740:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3741:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3742:    my $uhome=&homeserver($uname,$udomain);
                   3743: 
1.133     albertel 3744:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3745:    my @pairs=split(/\&/,$rep);
1.273     albertel 3746:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3747:      return @pairs;
                   3748:    }
1.15      www      3749:    my %returnhash=();
1.42      www      3750:    my $i=0;
1.800     albertel 3751:    foreach my $item (@$storearr) {
                   3752:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3753:       $i++;
1.191     harris41 3754:    }
1.15      www      3755:    return %returnhash;
1.27      www      3756: }
                   3757: 
                   3758: # --------------------------------------------------------------- del interface
                   3759: 
                   3760: sub del {
1.133     albertel 3761:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3762:    my $items='';
1.800     albertel 3763:    foreach my $item (@$storearr) {
                   3764:        $items.=&escape($item).'&';
1.191     harris41 3765:    }
1.27      www      3766:    $items=~s/\&$//;
1.620     albertel 3767:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3768:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3769:    my $uhome=&homeserver($uname,$udomain);
                   3770: 
                   3771:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3772: }
                   3773: 
                   3774: # -------------------------------------------------------------- dump interface
                   3775: 
                   3776: sub dump {
1.755     albertel 3777:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3778:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3779:     if (!$uname) { $uname=$env{'user.name'}; }
                   3780:     my $uhome=&homeserver($uname,$udomain);
                   3781:     if ($regexp) {
                   3782: 	$regexp=&escape($regexp);
                   3783:     } else {
                   3784: 	$regexp='.';
                   3785:     }
                   3786:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3787:     my @pairs=split(/\&/,$rep);
                   3788:     my %returnhash=();
                   3789:     foreach my $item (@pairs) {
                   3790: 	my ($key,$value)=split(/=/,$item,2);
                   3791: 	$key = &unescape($key);
                   3792: 	next if ($key =~ /^error: 2 /);
                   3793: 	$returnhash{$key}=&thaw_unescape($value);
                   3794:     }
                   3795:     return %returnhash;
1.407     www      3796: }
                   3797: 
1.717     albertel 3798: # --------------------------------------------------------- dumpstore interface
                   3799: 
                   3800: sub dumpstore {
                   3801:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3802:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3803:    if (!$uname) { $uname=$env{'user.name'}; }
                   3804:    my $uhome=&homeserver($uname,$udomain);
                   3805:    if ($regexp) {
                   3806:        $regexp=&escape($regexp);
                   3807:    } else {
                   3808:        $regexp='.';
                   3809:    }
                   3810:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3811:    my @pairs=split(/\&/,$rep);
                   3812:    my %returnhash=();
                   3813:    foreach my $item (@pairs) {
                   3814:        my ($key,$value)=split(/=/,$item,2);
                   3815:        next if ($key =~ /^error: 2 /);
                   3816:        $returnhash{$key}=&thaw_unescape($value);
                   3817:    }
                   3818:    return %returnhash;
1.717     albertel 3819: }
                   3820: 
1.407     www      3821: # -------------------------------------------------------------- keys interface
                   3822: 
                   3823: sub getkeys {
                   3824:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3825:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3826:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3827:    my $uhome=&homeserver($uname,$udomain);
                   3828:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3829:    my @keyarray=();
1.800     albertel 3830:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3831:       next if ($key =~ /^error: 2 /);
1.800     albertel 3832:       push(@keyarray,&unescape($key));
1.407     www      3833:    }
                   3834:    return @keyarray;
1.318     matthew  3835: }
                   3836: 
1.319     matthew  3837: # --------------------------------------------------------------- currentdump
                   3838: sub currentdump {
1.328     matthew  3839:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3840:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3841:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3842:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3843:    my $uhome = &homeserver($sname,$sdom);
                   3844:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3845:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3846:    #
1.318     matthew  3847:    my %returnhash=();
1.319     matthew  3848:    #
                   3849:    if ($rep eq "unknown_cmd") { 
                   3850:        # an old lond will not know currentdump
                   3851:        # Do a dump and make it look like a currentdump
1.822     albertel 3852:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3853:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3854:        my %hash = @tmp;
                   3855:        @tmp=();
1.424     matthew  3856:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3857:    } else {
                   3858:        my @pairs=split(/\&/,$rep);
1.800     albertel 3859:        foreach my $pair (@pairs) {
                   3860:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3861:            my ($symb,$param) = split(/:/,$key);
                   3862:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3863:                                                         &thaw_unescape($value);
1.319     matthew  3864:        }
1.191     harris41 3865:    }
1.12      www      3866:    return %returnhash;
1.424     matthew  3867: }
                   3868: 
                   3869: sub convert_dump_to_currentdump{
                   3870:     my %hash = %{shift()};
                   3871:     my %returnhash;
                   3872:     # Code ripped from lond, essentially.  The only difference
                   3873:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3874:     # we might run in to problems with parameter names =~ /^v\./
                   3875:     while (my ($key,$value) = each(%hash)) {
                   3876:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3877: 	$symb  = &unescape($symb);
                   3878: 	$param = &unescape($param);
1.424     matthew  3879:         next if ($v eq 'version' || $symb eq 'keys');
                   3880:         next if (exists($returnhash{$symb}) &&
                   3881:                  exists($returnhash{$symb}->{$param}) &&
                   3882:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3883:         $returnhash{$symb}->{$param}=$value;
                   3884:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3885:     }
                   3886:     #
                   3887:     # Remove all of the keys in the hashes which keep track of
                   3888:     # the version of the parameter.
                   3889:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3890:         # use a foreach because we are going to delete from the hash.
                   3891:         foreach my $key (keys(%$param_hash)) {
                   3892:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3893:         }
                   3894:     }
                   3895:     return \%returnhash;
1.12      www      3896: }
                   3897: 
1.627     albertel 3898: # ------------------------------------------------------ critical inc interface
                   3899: 
                   3900: sub cinc {
                   3901:     return &inc(@_,'critical');
                   3902: }
                   3903: 
1.449     matthew  3904: # --------------------------------------------------------------- inc interface
                   3905: 
                   3906: sub inc {
1.627     albertel 3907:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3908:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3909:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3910:     my $uhome=&homeserver($uname,$udomain);
                   3911:     my $items='';
                   3912:     if (! ref($store)) {
                   3913:         # got a single value, so use that instead
                   3914:         $items = &escape($store).'=&';
                   3915:     } elsif (ref($store) eq 'SCALAR') {
                   3916:         $items = &escape($$store).'=&';        
                   3917:     } elsif (ref($store) eq 'ARRAY') {
                   3918:         $items = join('=&',map {&escape($_);} @{$store});
                   3919:     } elsif (ref($store) eq 'HASH') {
                   3920:         while (my($key,$value) = each(%{$store})) {
                   3921:             $items.= &escape($key).'='.&escape($value).'&';
                   3922:         }
                   3923:     }
                   3924:     $items=~s/\&$//;
1.627     albertel 3925:     if ($critical) {
                   3926: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3927:     } else {
                   3928: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3929:     }
1.449     matthew  3930: }
                   3931: 
1.12      www      3932: # --------------------------------------------------------------- put interface
                   3933: 
                   3934: sub put {
1.134     albertel 3935:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3936:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3937:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3938:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3939:    my $items='';
1.800     albertel 3940:    foreach my $item (keys(%$storehash)) {
                   3941:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3942:    }
1.12      www      3943:    $items=~s/\&$//;
1.134     albertel 3944:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3945: }
                   3946: 
1.631     albertel 3947: # ------------------------------------------------------------ newput interface
                   3948: 
                   3949: sub newput {
                   3950:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3951:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3952:    if (!$uname) { $uname=$env{'user.name'}; }
                   3953:    my $uhome=&homeserver($uname,$udomain);
                   3954:    my $items='';
                   3955:    foreach my $key (keys(%$storehash)) {
                   3956:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3957:    }
                   3958:    $items=~s/\&$//;
                   3959:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3960: }
                   3961: 
                   3962: # ---------------------------------------------------------  putstore interface
                   3963: 
1.524     raeburn  3964: sub putstore {
1.715     albertel 3965:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3966:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3967:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3968:    my $uhome=&homeserver($uname,$udomain);
                   3969:    my $items='';
1.715     albertel 3970:    foreach my $key (keys(%$storehash)) {
                   3971:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3972:    }
1.715     albertel 3973:    $items=~s/\&$//;
1.716     albertel 3974:    my $esc_symb=&escape($symb);
                   3975:    my $esc_v=&escape($version);
1.715     albertel 3976:    my $reply =
1.716     albertel 3977:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3978: 	      $uhome);
                   3979:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3980:        # gfall back to way things use to be done
1.715     albertel 3981:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3982: 			    $uname);
1.524     raeburn  3983:    }
1.715     albertel 3984:    return $reply;
                   3985: }
                   3986: 
                   3987: sub old_putstore {
1.716     albertel 3988:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3989:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3990:     if (!$uname) { $uname=$env{'user.name'}; }
                   3991:     my $uhome=&homeserver($uname,$udomain);
                   3992:     my %newstorehash;
1.800     albertel 3993:     foreach my $item (keys(%$storehash)) {
                   3994: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3995: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3996:     }
                   3997:     my $items='';
                   3998:     my %allitems = ();
1.800     albertel 3999:     foreach my $item (keys(%newstorehash)) {
                   4000: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4001: 	    my $key = $1.':keys:'.$2;
                   4002: 	    $allitems{$key} .= $3.':';
                   4003: 	}
1.800     albertel 4004: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4005:     }
1.800     albertel 4006:     foreach my $item (keys(%allitems)) {
                   4007: 	$allitems{$item} =~ s/\:$//;
                   4008: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4009:     }
                   4010:     $items=~s/\&$//;
                   4011:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4012: }
                   4013: 
1.47      www      4014: # ------------------------------------------------------ critical put interface
                   4015: 
                   4016: sub cput {
1.134     albertel 4017:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4019:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4020:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4021:    my $items='';
1.800     albertel 4022:    foreach my $item (keys(%$storehash)) {
                   4023:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4024:    }
1.47      www      4025:    $items=~s/\&$//;
1.134     albertel 4026:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4027: }
                   4028: 
                   4029: # -------------------------------------------------------------- eget interface
                   4030: 
                   4031: sub eget {
1.133     albertel 4032:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4033:    my $items='';
1.800     albertel 4034:    foreach my $item (@$storearr) {
                   4035:        $items.=&escape($item).'&';
1.191     harris41 4036:    }
1.12      www      4037:    $items=~s/\&$//;
1.620     albertel 4038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4039:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4040:    my $uhome=&homeserver($uname,$udomain);
                   4041:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4042:    my @pairs=split(/\&/,$rep);
                   4043:    my %returnhash=();
1.42      www      4044:    my $i=0;
1.800     albertel 4045:    foreach my $item (@$storearr) {
                   4046:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4047:       $i++;
1.191     harris41 4048:    }
1.12      www      4049:    return %returnhash;
                   4050: }
                   4051: 
1.667     albertel 4052: # ------------------------------------------------------------ tmpput interface
                   4053: sub tmpput {
1.802     raeburn  4054:     my ($storehash,$server,$context)=@_;
1.667     albertel 4055:     my $items='';
1.800     albertel 4056:     foreach my $item (keys(%$storehash)) {
                   4057: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4058:     }
                   4059:     $items=~s/\&$//;
1.802     raeburn  4060:     if (defined($context)) {
                   4061:         $items .= ':'.&escape($context);
                   4062:     }
1.667     albertel 4063:     return &reply("tmpput:$items",$server);
                   4064: }
                   4065: 
                   4066: # ------------------------------------------------------------ tmpget interface
                   4067: sub tmpget {
1.688     albertel 4068:     my ($token,$server)=@_;
                   4069:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4070:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4071:     my %returnhash;
                   4072:     foreach my $item (split(/\&/,$rep)) {
                   4073: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4074:         next if ($key =~ /^error: 2 /);
1.667     albertel 4075: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4076:     }
                   4077:     return %returnhash;
                   4078: }
                   4079: 
1.688     albertel 4080: # ------------------------------------------------------------ tmpget interface
                   4081: sub tmpdel {
                   4082:     my ($token,$server)=@_;
                   4083:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4084:     return &reply("tmpdel:$token",$server);
                   4085: }
                   4086: 
1.765     albertel 4087: # -------------------------------------------------- portfolio access checking
                   4088: 
                   4089: sub portfolio_access {
1.766     albertel 4090:     my ($requrl) = @_;
1.765     albertel 4091:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4092:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4093:     if ($result) {
                   4094:         my %setters;
                   4095:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4096:             my ($startblock,$endblock) =
                   4097:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4098:             if ($startblock && $endblock) {
                   4099:                 return 'B';
                   4100:             }
                   4101:         } else {
                   4102:             my ($startblock,$endblock) =
                   4103:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4104:             if ($startblock && $endblock) {
                   4105:                 return 'B';
                   4106:             }
                   4107:         }
                   4108:     }
1.765     albertel 4109:     if ($result eq 'ok') {
1.766     albertel 4110:        return 'F';
1.765     albertel 4111:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4112:        return 'A';
1.765     albertel 4113:     }
1.766     albertel 4114:     return '';
1.765     albertel 4115: }
                   4116: 
                   4117: sub get_portfolio_access {
1.767     albertel 4118:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4119: 
                   4120:     if (!ref($access_hash)) {
                   4121: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4122: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4123: 						   $file_name);
                   4124: 	$access_hash = $access_controls{$file_name};
                   4125:     }
                   4126: 
1.765     albertel 4127:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4128:     my $now = time;
                   4129:     if (ref($access_hash) eq 'HASH') {
                   4130:         foreach my $key (keys(%{$access_hash})) {
                   4131:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4132:             if ($start > $now) {
                   4133:                 next;
                   4134:             }
                   4135:             if ($end && $end<$now) {
                   4136:                 next;
                   4137:             }
                   4138:             if ($scope eq 'public') {
                   4139:                 $public = $key;
                   4140:                 last;
                   4141:             } elsif ($scope eq 'guest') {
                   4142:                 $guest = $key;
                   4143:             } elsif ($scope eq 'domains') {
                   4144:                 push(@domains,$key);
                   4145:             } elsif ($scope eq 'users') {
                   4146:                 push(@users,$key);
                   4147:             } elsif ($scope eq 'course') {
                   4148:                 push(@courses,$key);
                   4149:             } elsif ($scope eq 'group') {
                   4150:                 push(@groups,$key);
                   4151:             }
                   4152:         }
                   4153:         if ($public) {
                   4154:             return 'ok';
                   4155:         }
                   4156:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4157:             if ($guest) {
                   4158:                 return $guest;
                   4159:             }
                   4160:         } else {
                   4161:             if (@domains > 0) {
                   4162:                 foreach my $domkey (@domains) {
                   4163:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4164:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4165:                             return 'ok';
                   4166:                         }
                   4167:                     }
                   4168:                 }
                   4169:             }
                   4170:             if (@users > 0) {
                   4171:                 foreach my $userkey (@users) {
1.865     raeburn  4172:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4173:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4174:                             if (ref($item) eq 'HASH') {
                   4175:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4176:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4177:                                     return 'ok';
                   4178:                                 }
                   4179:                             }
                   4180:                         }
                   4181:                     } 
1.765     albertel 4182:                 }
                   4183:             }
                   4184:             my %roleshash;
                   4185:             my @courses_and_groups = @courses;
                   4186:             push(@courses_and_groups,@groups); 
                   4187:             if (@courses_and_groups > 0) {
                   4188:                 my (%allgroups,%allroles); 
                   4189:                 my ($start,$end,$role,$sec,$group);
                   4190:                 foreach my $envkey (%env) {
1.811     albertel 4191:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4192:                         my $cid = $2.'_'.$3; 
                   4193:                         if ($1 eq 'gr') {
                   4194:                             $group = $4;
                   4195:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4196:                         } else {
                   4197:                             if ($4 eq '') {
                   4198:                                 $sec = 'none';
                   4199:                             } else {
                   4200:                                 $sec = $4;
                   4201:                             }
                   4202:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4203:                         }
1.811     albertel 4204:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4205:                         my $cid = $2.'_'.$3;
                   4206:                         if ($4 eq '') {
                   4207:                             $sec = 'none';
                   4208:                         } else {
                   4209:                             $sec = $4;
                   4210:                         }
                   4211:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4212:                     }
                   4213:                 }
                   4214:                 if (keys(%allroles) == 0) {
                   4215:                     return;
                   4216:                 }
                   4217:                 foreach my $key (@courses_and_groups) {
                   4218:                     my %content = %{$$access_hash{$key}};
                   4219:                     my $cnum = $content{'number'};
                   4220:                     my $cdom = $content{'domain'};
                   4221:                     my $cid = $cdom.'_'.$cnum;
                   4222:                     if (!exists($allroles{$cid})) {
                   4223:                         next;
                   4224:                     }    
                   4225:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4226:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4227:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4228:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4229:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4230:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4231:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4232:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4233:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4234:                                         if (grep/^all$/,@sections) {
                   4235:                                             return 'ok';
                   4236:                                         } else {
                   4237:                                             if (grep/^$sec$/,@sections) {
                   4238:                                                 return 'ok';
                   4239:                                             }
                   4240:                                         }
                   4241:                                     }
                   4242:                                 }
                   4243:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4244:                                     if (grep/^none$/,@groups) {
                   4245:                                         return 'ok';
                   4246:                                     }
                   4247:                                 } else {
                   4248:                                     if (grep/^all$/,@groups) {
                   4249:                                         return 'ok';
                   4250:                                     } 
                   4251:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4252:                                         if (grep/^$group$/,@groups) {
                   4253:                                             return 'ok';
                   4254:                                         }
                   4255:                                     }
                   4256:                                 } 
                   4257:                             }
                   4258:                         }
                   4259:                     }
                   4260:                 }
                   4261:             }
                   4262:             if ($guest) {
                   4263:                 return $guest;
                   4264:             }
                   4265:         }
                   4266:     }
                   4267:     return;
                   4268: }
                   4269: 
                   4270: sub course_group_datechecker {
                   4271:     my ($dates,$now,$status) = @_;
                   4272:     my ($start,$end) = split(/\./,$dates);
                   4273:     if (!$start && !$end) {
                   4274:         return 'ok';
                   4275:     }
                   4276:     if (grep/^active$/,@{$status}) {
                   4277:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4278:             return 'ok';
                   4279:         }
                   4280:     }
                   4281:     if (grep/^previous$/,@{$status}) {
                   4282:         if ($end > $now ) {
                   4283:             return 'ok';
                   4284:         }
                   4285:     }
                   4286:     if (grep/^future$/,@{$status}) {
                   4287:         if ($start > $now) {
                   4288:             return 'ok';
                   4289:         }
                   4290:     }
                   4291:     return; 
                   4292: }
                   4293: 
                   4294: sub parse_portfolio_url {
                   4295:     my ($url) = @_;
                   4296: 
                   4297:     my ($type,$udom,$unum,$group,$file_name);
                   4298:     
1.823     albertel 4299:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4300: 	$type = 1;
                   4301:         $udom = $1;
                   4302:         $unum = $2;
                   4303:         $file_name = $3;
1.823     albertel 4304:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4305: 	$type = 2;
                   4306:         $udom = $1;
                   4307:         $unum = $2;
                   4308:         $group = $3;
                   4309:         $file_name = $3.'/'.$4;
                   4310:     }
                   4311:     if (wantarray) {
                   4312: 	return ($type,$udom,$unum,$file_name,$group);
                   4313:     }
                   4314:     return $type;
                   4315: }
                   4316: 
                   4317: sub is_portfolio_url {
                   4318:     my ($url) = @_;
                   4319:     return scalar(&parse_portfolio_url($url));
                   4320: }
                   4321: 
1.798     raeburn  4322: sub is_portfolio_file {
                   4323:     my ($file) = @_;
1.820     raeburn  4324:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4325:         return 1;
                   4326:     }
                   4327:     return;
                   4328: }
                   4329: 
                   4330: 
1.341     www      4331: # ---------------------------------------------- Custom access rule evaluation
                   4332: 
                   4333: sub customaccess {
                   4334:     my ($priv,$uri)=@_;
1.807     albertel 4335:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4336:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4337:     $udom = &LONCAPA::clean_domain($udom);
                   4338:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4339:     my $access=0;
1.800     albertel 4340:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4341: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4342: 	if ($type eq 'user') {
                   4343: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4344: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4345: 		if ($tdom) {
                   4346: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4347: 		}
1.896     albertel 4348: 		if ($tuname) {
                   4349: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4350: 		}
                   4351: 		$access=($effect eq 'allow');
                   4352: 		last;
                   4353: 	    }
                   4354: 	} else {
                   4355: 	    if ($role) {
                   4356: 		if ($role ne $urole) { next; }
                   4357: 	    }
                   4358: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4359: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4360: 		if ($tdom) {
                   4361: 		    if ($tdom ne $udom) { next; }
                   4362: 		}
                   4363: 		if ($tcrs) {
                   4364: 		    if ($tcrs ne $ucrs) { next; }
                   4365: 		}
                   4366: 		if ($tsec) {
                   4367: 		    if ($tsec ne $usec) { next; }
                   4368: 		}
                   4369: 		$access=($effect eq 'allow');
                   4370: 		last;
                   4371: 	    }
                   4372: 	    if ($realm eq '' && $role eq '') {
                   4373: 		$access=($effect eq 'allow');
                   4374: 	    }
1.402     bowersj2 4375: 	}
1.341     www      4376:     }
                   4377:     return $access;
                   4378: }
                   4379: 
1.103     harris41 4380: # ------------------------------------------------- Check for a user privilege
1.12      www      4381: 
                   4382: sub allowed {
1.810     raeburn  4383:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4384:     my $ver_orguri=$uri;
1.439     www      4385:     $uri=&deversion($uri);
1.152     www      4386:     my $orguri=$uri;
1.52      www      4387:     $uri=&declutter($uri);
1.809     raeburn  4388: 
1.810     raeburn  4389:     if ($priv eq 'evb') {
                   4390: # Evade communication block restrictions for specified role in a course
                   4391:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4392:             return $1;
                   4393:         } else {
                   4394:             return;
                   4395:         }
                   4396:     }
                   4397: 
1.620     albertel 4398:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4399: # Free bre access to adm and meta resources
1.775     albertel 4400:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4401: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4402: 	&& ($priv eq 'bre')) {
1.14      www      4403: 	return 'F';
1.159     www      4404:     }
                   4405: 
1.545     banghart 4406: # Free bre access to user's own portfolio contents
1.714     raeburn  4407:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4408:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4409: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4410:         my %setters;
                   4411:         my ($startblock,$endblock) = 
                   4412:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4413:         if ($startblock && $endblock) {
                   4414:             return 'B';
                   4415:         } else {
                   4416:             return 'F';
                   4417:         }
1.545     banghart 4418:     }
                   4419: 
1.762     raeburn  4420: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4421:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4422:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4423:         if (exists($env{'request.course.id'})) {
                   4424:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4425:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4426:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4427:                 my $courseprivid=$env{'request.course.id'};
                   4428:                 $courseprivid=~s/\_/\//;
                   4429:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4430:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4431:                     return $1; 
1.762     raeburn  4432:                 } else {
                   4433:                     if ($env{'request.course.sec'}) {
                   4434:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4435:                     }
                   4436:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4437:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4438:                         return $2;
                   4439:                     }
1.714     raeburn  4440:                 }
                   4441:             }
                   4442:         }
                   4443:     }
                   4444: 
1.159     www      4445: # Free bre to public access
                   4446: 
                   4447:     if ($priv eq 'bre') {
1.238     www      4448:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4449: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4450:            return 'F'; 
                   4451:         }
1.238     www      4452:         if ($copyright eq 'priv') {
                   4453:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4454: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4455: 		return '';
                   4456:             }
                   4457:         }
                   4458:         if ($copyright eq 'domain') {
                   4459:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4460: 	    unless (($env{'user.domain'} eq $1) ||
                   4461:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4462: 		return '';
                   4463:             }
1.262     matthew  4464:         }
1.620     albertel 4465:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4466:             # Library role, so allow browsing of resources in this domain.
                   4467:             return 'F';
1.238     www      4468:         }
1.341     www      4469:         if ($copyright eq 'custom') {
                   4470: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4471:         }
1.14      www      4472:     }
1.264     matthew  4473:     # Domain coordinator is trying to create a course
1.620     albertel 4474:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4475:         # uri is the requested domain in this case.
                   4476:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4477:         # a role of dc for the domain in question.
1.620     albertel 4478:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4479:     }
1.29      www      4480: 
1.52      www      4481:     my $thisallowed='';
                   4482:     my $statecond=0;
                   4483:     my $courseprivid='';
                   4484: 
                   4485: # Course
                   4486: 
1.620     albertel 4487:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4488:        $thisallowed.=$1;
                   4489:     }
1.29      www      4490: 
1.52      www      4491: # Domain
                   4492: 
1.620     albertel 4493:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4494:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4495:        $thisallowed.=$1;
                   4496:     }
1.52      www      4497: 
                   4498: # Course: uri itself is a course
1.66      www      4499:     my $courseuri=$uri;
                   4500:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4501:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4502: 
1.620     albertel 4503:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4504:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4505:        $thisallowed.=$1;
                   4506:     }
1.29      www      4507: 
1.665     albertel 4508: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4509: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4510:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4511: 	$thisallowed='';
1.671     raeburn  4512:         my ($match)=&is_on_map($uri);
                   4513:         if ($match) {
                   4514:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4515:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4516:                 $thisallowed.=$1;
                   4517:             }
                   4518:         } else {
1.705     albertel 4519:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4520:             if ($refuri) {
                   4521:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4522:                     $thisallowed='F';
1.671     raeburn  4523:                 } else {
                   4524:                     $refuri=&declutter($refuri);
                   4525:                     my ($match) = &is_on_map($refuri);
                   4526:                     if ($match) {
                   4527:                         $thisallowed='F';
                   4528:                     }
1.669     raeburn  4529:                 }
1.671     raeburn  4530:             }
                   4531:         }
1.314     www      4532:     }
1.492     albertel 4533: 
1.766     albertel 4534:     if ($priv eq 'bre'
                   4535: 	&& $thisallowed ne 'F' 
                   4536: 	&& $thisallowed ne '2'
                   4537: 	&& &is_portfolio_url($uri)) {
                   4538: 	$thisallowed = &portfolio_access($uri);
                   4539:     }
                   4540:     
1.52      www      4541: # Full access at system, domain or course-wide level? Exit.
1.29      www      4542:     if ($thisallowed=~/F/) {
                   4543: 	return 'F';
                   4544:     }
                   4545: 
1.52      www      4546: # If this is generating or modifying users, exit with special codes
1.29      www      4547: 
1.643     www      4548:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4549: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4550: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4551: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4552: 	    unless ($auname) { return $thisallowed; }
                   4553: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4554: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4555: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4556: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4557: 	}
1.52      www      4558: 	return $thisallowed;
                   4559:     }
                   4560: #
1.103     harris41 4561: # Gathered so far: system, domain and course wide privileges
1.52      www      4562: #
                   4563: # Course: See if uri or referer is an individual resource that is part of 
                   4564: # the course
                   4565: 
1.620     albertel 4566:     if ($env{'request.course.id'}) {
1.232     www      4567: 
1.620     albertel 4568:        $courseprivid=$env{'request.course.id'};
                   4569:        if ($env{'request.course.sec'}) {
                   4570:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4571:        }
                   4572:        $courseprivid=~s/\_/\//;
                   4573:        my $checkreferer=1;
1.232     www      4574:        my ($match,$cond)=&is_on_map($uri);
                   4575:        if ($match) {
                   4576:            $statecond=$cond;
1.620     albertel 4577:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4578:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4579:                $thisallowed.=$1;
                   4580:                $checkreferer=0;
                   4581:            }
1.29      www      4582:        }
1.83      www      4583:        
1.148     www      4584:        if ($checkreferer) {
1.620     albertel 4585: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4586:             unless ($refuri) {
1.800     albertel 4587:                 foreach my $key (keys(%env)) {
                   4588: 		    if ($key=~/^httpref\..*\*/) {
                   4589: 			my $pattern=$key;
1.156     www      4590:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4591:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4592:                         $pattern=~s/\//\\\//g;
1.152     www      4593:                         if ($orguri=~/$pattern/) {
1.800     albertel 4594: 			    $refuri=$env{$key};
1.148     www      4595:                         }
                   4596:                     }
1.191     harris41 4597:                 }
1.148     www      4598:             }
1.232     www      4599: 
1.148     www      4600:          if ($refuri) { 
1.152     www      4601: 	  $refuri=&declutter($refuri);
1.232     www      4602:           my ($match,$cond)=&is_on_map($refuri);
                   4603:             if ($match) {
                   4604:               my $refstatecond=$cond;
1.620     albertel 4605:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4606:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4607:                   $thisallowed.=$1;
1.53      www      4608:                   $uri=$refuri;
                   4609:                   $statecond=$refstatecond;
1.52      www      4610:               }
                   4611:           }
1.148     www      4612:         }
1.29      www      4613:        }
1.52      www      4614:    }
1.29      www      4615: 
1.52      www      4616: #
1.103     harris41 4617: # Gathered now: all privileges that could apply, and condition number
1.52      www      4618: # 
                   4619: #
                   4620: # Full or no access?
                   4621: #
1.29      www      4622: 
1.52      www      4623:     if ($thisallowed=~/F/) {
                   4624: 	return 'F';
                   4625:     }
1.29      www      4626: 
1.52      www      4627:     unless ($thisallowed) {
                   4628:         return '';
                   4629:     }
1.29      www      4630: 
1.52      www      4631: # Restrictions exist, deal with them
                   4632: #
                   4633: #   C:according to course preferences
                   4634: #   R:according to resource settings
                   4635: #   L:unless locked
                   4636: #   X:according to user session state
                   4637: #
                   4638: 
                   4639: # Possibly locked functionality, check all courses
1.54      www      4640: # Locks might take effect only after 10 minutes cache expiration for other
                   4641: # courses, and 2 minutes for current course
1.52      www      4642: 
                   4643:     my $envkey;
                   4644:     if ($thisallowed=~/L/) {
1.620     albertel 4645:         foreach $envkey (keys %env) {
1.54      www      4646:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4647:                my $courseid=$2;
                   4648:                my $roleid=$1.'.'.$2;
1.92      www      4649:                $courseid=~s/^\///;
1.54      www      4650:                my $expiretime=600;
1.620     albertel 4651:                if ($env{'request.role'} eq $roleid) {
1.54      www      4652: 		  $expiretime=120;
                   4653:                }
                   4654: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4655:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4656:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4657: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4658:                }
1.620     albertel 4659:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4660:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4661: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4662:                        &log($env{'user.domain'},$env{'user.name'},
                   4663:                             $env{'user.home'},
1.57      www      4664:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4665:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4666:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4667: 		       return '';
                   4668:                    }
                   4669:                }
1.620     albertel 4670:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4671:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4672: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4673:                        &log($env{'user.domain'},$env{'user.name'},
                   4674:                             $env{'user.home'},
1.57      www      4675:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4676:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4677:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4678: 		       return '';
                   4679:                    }
                   4680:                }
                   4681: 	   }
1.29      www      4682:        }
1.52      www      4683:     }
                   4684:    
                   4685: #
                   4686: # Rest of the restrictions depend on selected course
                   4687: #
                   4688: 
1.620     albertel 4689:     unless ($env{'request.course.id'}) {
1.766     albertel 4690: 	if ($thisallowed eq 'A') {
                   4691: 	    return 'A';
1.814     raeburn  4692:         } elsif ($thisallowed eq 'B') {
                   4693:             return 'B';
1.766     albertel 4694: 	} else {
                   4695: 	    return '1';
                   4696: 	}
1.52      www      4697:     }
1.29      www      4698: 
1.52      www      4699: #
                   4700: # Now user is definitely in a course
                   4701: #
1.53      www      4702: 
                   4703: 
                   4704: # Course preferences
                   4705: 
                   4706:    if ($thisallowed=~/C/) {
1.620     albertel 4707:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4708:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4709:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4710: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4711: 	   if ($priv ne 'pch') { 
                   4712: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4713: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4714: 			$env{'request.course.id'});
                   4715: 	   }
1.237     www      4716:            return '';
                   4717:        }
                   4718: 
1.620     albertel 4719:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4720: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4721: 	   if ($priv ne 'pch') { 
                   4722: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4723: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4724: 			$env{'request.course.id'});
                   4725: 	   }
1.54      www      4726:            return '';
                   4727:        }
1.53      www      4728:    }
                   4729: 
                   4730: # Resource preferences
                   4731: 
                   4732:    if ($thisallowed=~/R/) {
1.620     albertel 4733:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4734:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4735: 	   if ($priv ne 'pch') { 
                   4736: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4737: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4738: 	   }
                   4739: 	   return '';
1.54      www      4740:        }
1.53      www      4741:    }
1.30      www      4742: 
1.246     www      4743: # Restricted by state or randomout?
1.30      www      4744: 
1.52      www      4745:    if ($thisallowed=~/X/) {
1.620     albertel 4746:       if ($env{'acc.randomout'}) {
1.579     albertel 4747: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4748:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4749:             return ''; 
                   4750:          }
1.247     www      4751:       }
                   4752:       if (&condval($statecond)) {
1.52      www      4753: 	 return '2';
                   4754:       } else {
                   4755:          return '';
                   4756:       }
                   4757:    }
1.30      www      4758: 
1.766     albertel 4759:     if ($thisallowed eq 'A') {
                   4760: 	return 'A';
1.814     raeburn  4761:     } elsif ($thisallowed eq 'B') {
                   4762:         return 'B';
1.766     albertel 4763:     }
1.52      www      4764:    return 'F';
1.232     www      4765: }
                   4766: 
1.710     albertel 4767: sub split_uri_for_cond {
                   4768:     my $uri=&deversion(&declutter(shift));
                   4769:     my @uriparts=split(/\//,$uri);
                   4770:     my $filename=pop(@uriparts);
                   4771:     my $pathname=join('/',@uriparts);
                   4772:     return ($pathname,$filename);
                   4773: }
1.232     www      4774: # --------------------------------------------------- Is a resource on the map?
                   4775: 
                   4776: sub is_on_map {
1.710     albertel 4777:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4778:     #Trying to find the conditional for the file
1.620     albertel 4779:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4780: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4781:     if ($match) {
1.289     bowersj2 4782: 	return (1,$1);
                   4783:     } else {
1.434     www      4784: 	return (0,0);
1.289     bowersj2 4785:     }
1.12      www      4786: }
                   4787: 
1.427     www      4788: # --------------------------------------------------------- Get symb from alias
                   4789: 
                   4790: sub get_symb_from_alias {
                   4791:     my $symb=shift;
                   4792:     my ($map,$resid,$url)=&decode_symb($symb);
                   4793: # Already is a symb
                   4794:     if ($url) { return $symb; }
                   4795: # Must be an alias
                   4796:     my $aliassymb='';
                   4797:     my %bighash;
1.620     albertel 4798:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4799:                             &GDBM_READER(),0640)) {
                   4800:         my $rid=$bighash{'mapalias_'.$symb};
                   4801: 	if ($rid) {
                   4802: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4803: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4804: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4805: 	}
                   4806:         untie %bighash;
                   4807:     }
                   4808:     return $aliassymb;
                   4809: }
                   4810: 
1.12      www      4811: # ----------------------------------------------------------------- Define Role
                   4812: 
                   4813: sub definerole {
                   4814:   if (allowed('mcr','/')) {
                   4815:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4816:     foreach my $role (split(':',$sysrole)) {
                   4817: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4818:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4819:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4820: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4821:                return "refused:s:$crole&$cqual"; 
                   4822:             }
                   4823:         }
1.191     harris41 4824:     }
1.800     albertel 4825:     foreach my $role (split(':',$domrole)) {
                   4826: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4827:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4828:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4829: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4830:                return "refused:d:$crole&$cqual"; 
                   4831:             }
                   4832:         }
1.191     harris41 4833:     }
1.800     albertel 4834:     foreach my $role (split(':',$courole)) {
                   4835: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4836:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4837:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4838: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4839:                return "refused:c:$crole&$cqual"; 
                   4840:             }
                   4841:         }
1.191     harris41 4842:     }
1.620     albertel 4843:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4844:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4845: 	        "rolesdef_$rolename=".
                   4846:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4847:     return reply($command,$env{'user.home'});
1.12      www      4848:   } else {
                   4849:     return 'refused';
                   4850:   }
1.105     harris41 4851: }
                   4852: 
                   4853: # ---------------- Make a metadata query against the network of library servers
                   4854: 
                   4855: sub metadata_query {
1.244     matthew  4856:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4857:     my %rhash;
1.845     albertel 4858:     my %libserv = &all_library();
1.244     matthew  4859:     my @server_list = (defined($server_array) ? @$server_array
                   4860:                                               : keys(%libserv) );
                   4861:     for my $server (@server_list) {
1.118     harris41 4862: 	unless ($custom or $customshow) {
                   4863: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4864: 	    $rhash{$server}=$reply;
                   4865: 	}
                   4866: 	else {
                   4867: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4868: 			     &escape($custom).':'.&escape($customshow),
                   4869: 			     $server);
                   4870: 	    $rhash{$server}=$reply;
                   4871: 	}
1.112     harris41 4872:     }
1.118     harris41 4873:     return \%rhash;
1.240     www      4874: }
                   4875: 
                   4876: # ----------------------------------------- Send log queries and wait for reply
                   4877: 
                   4878: sub log_query {
                   4879:     my ($uname,$udom,$query,%filters)=@_;
                   4880:     my $uhome=&homeserver($uname,$udom);
                   4881:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4882:     my $uhost=&hostname($uhome);
1.800     albertel 4883:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4884:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4885:                        $uhome);
1.479     albertel 4886:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4887:     return get_query_reply($queryid);
                   4888: }
                   4889: 
1.818     raeburn  4890: # -------------------------- Update MySQL table for portfolio file
                   4891: 
                   4892: sub update_portfolio_table {
1.821     raeburn  4893:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4894:     my $homeserver = &homeserver($uname,$udom);
                   4895:     my $queryid=
1.821     raeburn  4896:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4897:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4898:     my $reply = &get_query_reply($queryid);
                   4899:     return $reply;
                   4900: }
                   4901: 
1.899     raeburn  4902: # -------------------------- Update MySQL allusers table
                   4903: 
                   4904: sub update_allusers_table {
                   4905:     my ($uname,$udom,$names) = @_;
                   4906:     my $homeserver = &homeserver($uname,$udom);
                   4907:     my $queryid=
                   4908:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4909:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4910:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4911:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4912:                'generation='.&escape($names->{'generation'}).'%%'.
                   4913:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4914:                'id='.&escape($names->{'id'}),$homeserver);
                   4915:     my $reply = &get_query_reply($queryid);
                   4916:     return $reply;
                   4917: }
                   4918: 
1.508     raeburn  4919: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4920: 
                   4921: sub fetch_enrollment_query {
1.511     raeburn  4922:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4923:     my $homeserver;
1.547     raeburn  4924:     my $maxtries = 1;
1.508     raeburn  4925:     if ($context eq 'automated') {
                   4926:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4927:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4928:     } else {
                   4929:         $homeserver = &homeserver($cnum,$dom);
                   4930:     }
1.838     albertel 4931:     my $host=&hostname($homeserver);
1.506     raeburn  4932:     my $cmd = '';
1.800     albertel 4933:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4934:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4935:     }
                   4936:     $cmd =~ s/%%$//;
                   4937:     $cmd = &escape($cmd);
                   4938:     my $query = 'fetchenrollment';
1.620     albertel 4939:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4940:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4941:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4942:         return 'error: '.$queryid;
                   4943:     }
1.506     raeburn  4944:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4945:     my $tries = 1;
                   4946:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4947:         $reply = &get_query_reply($queryid);
                   4948:         $tries ++;
                   4949:     }
1.526     raeburn  4950:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4951:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4952:     } else {
1.901     albertel 4953:         my @responses = split(/:/,$reply);
1.515     raeburn  4954:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4955:             foreach my $line (@responses) {
                   4956:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4957:                 $$replyref{$key} = $value;
                   4958:             }
                   4959:         } else {
1.506     raeburn  4960:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4961:             foreach my $line (@responses) {
                   4962:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4963:                 $$replyref{$key} = $value;
                   4964:                 if ($value > 0) {
1.800     albertel 4965:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4966:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4967:                         my $destname = $pathname.'/'.$filename;
                   4968:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4969:                         if ($xml_classlist =~ /^error/) {
                   4970:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4971:                         } else {
1.506     raeburn  4972:                             if ( open(FILE,">$destname") ) {
                   4973:                                 print FILE &unescape($xml_classlist);
                   4974:                                 close(FILE);
1.526     raeburn  4975:                             } else {
                   4976:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4977:                             }
                   4978:                         }
                   4979:                     }
                   4980:                 }
                   4981:             }
                   4982:         }
                   4983:         return 'ok';
                   4984:     }
                   4985:     return 'error';
                   4986: }
                   4987: 
1.242     www      4988: sub get_query_reply {
                   4989:     my $queryid=shift;
1.240     www      4990:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4991:     my $reply='';
                   4992:     for (1..100) {
                   4993: 	sleep 2;
                   4994:         if (-e $replyfile.'.end') {
1.448     albertel 4995: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4996: 		$reply = join('',<$fh>);
                   4997: 		close($fh);
1.240     www      4998: 	   } else { return 'error: reply_file_error'; }
1.242     www      4999:            return &unescape($reply);
                   5000: 	}
1.240     www      5001:     }
1.242     www      5002:     return 'timeout:'.$queryid;
1.240     www      5003: }
                   5004: 
                   5005: sub courselog_query {
1.241     www      5006: #
                   5007: # possible filters:
                   5008: # url: url or symb
                   5009: # username
                   5010: # domain
                   5011: # action: view, submit, grade
                   5012: # start: timestamp
                   5013: # end: timestamp
                   5014: #
1.240     www      5015:     my (%filters)=@_;
1.620     albertel 5016:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5017:     if ($filters{'url'}) {
                   5018: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5019:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5020:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5021:     }
1.620     albertel 5022:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5023:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5024:     return &log_query($cname,$cdom,'courselog',%filters);
                   5025: }
                   5026: 
                   5027: sub userlog_query {
1.858     raeburn  5028: #
                   5029: # possible filters:
                   5030: # action: log check role
                   5031: # start: timestamp
                   5032: # end: timestamp
                   5033: #
1.240     www      5034:     my ($uname,$udom,%filters)=@_;
                   5035:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5036: }
                   5037: 
1.506     raeburn  5038: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5039: 
                   5040: sub auto_run {
1.508     raeburn  5041:     my ($cnum,$cdom) = @_;
1.876     raeburn  5042:     my $response = 0;
                   5043:     my $settings;
                   5044:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5045:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5046:         $settings = $domconfig{'autoenroll'};
                   5047:         if ($settings->{'run'} eq '1') {
                   5048:             $response = 1;
                   5049:         }
                   5050:     } else {
1.934     raeburn  5051:         my $homeserver;
                   5052:         if (&is_course($cdom,$cnum)) {
                   5053:             $homeserver = &homeserver($cnum,$cdom);
                   5054:         } else {
                   5055:             $homeserver = &domain($cdom,'primary');
                   5056:         }
                   5057:         if ($homeserver ne 'no_host') {
                   5058:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5059:         }
1.876     raeburn  5060:     }
1.506     raeburn  5061:     return $response;
                   5062: }
1.776     albertel 5063: 
1.506     raeburn  5064: sub auto_get_sections {
1.508     raeburn  5065:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5066:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5067:     my @secs = ();
1.511     raeburn  5068:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5069:     unless ($response eq 'refused') {
1.901     albertel 5070:         @secs = split(/:/,$response);
1.506     raeburn  5071:     }
                   5072:     return @secs;
                   5073: }
1.776     albertel 5074: 
1.506     raeburn  5075: sub auto_new_course {
1.508     raeburn  5076:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5077:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5078:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5079:     return $response;
                   5080: }
1.776     albertel 5081: 
1.506     raeburn  5082: sub auto_validate_courseID {
1.508     raeburn  5083:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5084:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5085:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5086:     return $response;
                   5087: }
1.776     albertel 5088: 
1.506     raeburn  5089: sub auto_create_password {
1.873     raeburn  5090:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5091:     my ($homeserver,$response);
1.506     raeburn  5092:     my $create_passwd = 0;
                   5093:     my $authchk = '';
1.873     raeburn  5094:     if ($udom =~ /^$match_domain$/) {
                   5095:         $homeserver = &domain($udom,'primary');
                   5096:     }
                   5097:     if ($homeserver eq '') {
                   5098:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5099:             $homeserver = &homeserver($cnum,$cdom);
                   5100:         }
                   5101:     }
                   5102:     if ($homeserver eq '') {
                   5103:         $authchk = 'nodomain';
1.506     raeburn  5104:     } else {
1.873     raeburn  5105:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5106:         if ($response eq 'refused') {
                   5107:             $authchk = 'refused';
                   5108:         } else {
1.901     albertel 5109:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5110:         }
1.506     raeburn  5111:     }
                   5112:     return ($authparam,$create_passwd,$authchk);
                   5113: }
                   5114: 
1.706     raeburn  5115: sub auto_photo_permission {
                   5116:     my ($cnum,$cdom,$students) = @_;
                   5117:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5118:     my ($outcome,$perm_reqd,$conditions) = 
                   5119: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5120:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5121: 	return (undef,undef);
                   5122:     }
1.706     raeburn  5123:     return ($outcome,$perm_reqd,$conditions);
                   5124: }
                   5125: 
                   5126: sub auto_checkphotos {
                   5127:     my ($uname,$udom,$pid) = @_;
                   5128:     my $homeserver = &homeserver($uname,$udom);
                   5129:     my ($result,$resulttype);
                   5130:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5131: 				   &escape($uname).':'.&escape($pid),
                   5132: 				   $homeserver));
1.709     albertel 5133:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5134: 	return (undef,undef);
                   5135:     }
1.706     raeburn  5136:     if ($outcome) {
                   5137:         ($result,$resulttype) = split(/:/,$outcome);
                   5138:     } 
                   5139:     return ($result,$resulttype);
                   5140: }
                   5141: 
                   5142: sub auto_photochoice {
                   5143:     my ($cnum,$cdom) = @_;
                   5144:     my $homeserver = &homeserver($cnum,$cdom);
                   5145:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5146: 						       &escape($cdom),
                   5147: 						       $homeserver)));
1.709     albertel 5148:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5149: 	return (undef,undef);
                   5150:     }
1.706     raeburn  5151:     return ($update,$comment);
                   5152: }
                   5153: 
                   5154: sub auto_photoupdate {
                   5155:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5156:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5157:     my $host=&hostname($homeserver);
1.706     raeburn  5158:     my $cmd = '';
                   5159:     my $maxtries = 1;
1.800     albertel 5160:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5161:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5162:     }
                   5163:     $cmd =~ s/%%$//;
                   5164:     $cmd = &escape($cmd);
                   5165:     my $query = 'institutionalphotos';
                   5166:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5167:     unless ($queryid=~/^\Q$host\E\_/) {
                   5168:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5169:         return 'error: '.$queryid;
                   5170:     }
                   5171:     my $reply = &get_query_reply($queryid);
                   5172:     my $tries = 1;
                   5173:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5174:         $reply = &get_query_reply($queryid);
                   5175:         $tries ++;
                   5176:     }
                   5177:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5178:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5179:     } else {
                   5180:         my @responses = split(/:/,$reply);
                   5181:         my $outcome = shift(@responses); 
                   5182:         foreach my $item (@responses) {
                   5183:             my ($key,$value) = split(/=/,$item);
                   5184:             $$photo{$key} = $value;
                   5185:         }
                   5186:         return $outcome;
                   5187:     }
                   5188:     return 'error';
                   5189: }
                   5190: 
1.521     raeburn  5191: sub auto_instcode_format {
1.793     albertel 5192:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5193: 	$cat_order) = @_;
1.521     raeburn  5194:     my $courses = '';
1.772     raeburn  5195:     my @homeservers;
1.521     raeburn  5196:     if ($caller eq 'global') {
1.841     albertel 5197: 	my %servers = &get_servers($codedom,'library');
                   5198: 	foreach my $tryserver (keys(%servers)) {
                   5199: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5200: 		push(@homeservers,$tryserver);
                   5201: 	    }
1.584     raeburn  5202:         }
1.521     raeburn  5203:     } else {
1.772     raeburn  5204:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5205:     }
1.793     albertel 5206:     foreach my $code (keys(%{$instcodes})) {
                   5207:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5208:     }
                   5209:     chop($courses);
1.772     raeburn  5210:     my $ok_response = 0;
                   5211:     my $response;
                   5212:     while (@homeservers > 0 && $ok_response == 0) {
                   5213:         my $server = shift(@homeservers); 
                   5214:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5215:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5216:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5217: 		split(/:/,$response);
1.772     raeburn  5218:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5219:             push(@{$codetitles},&str2array($codetitles_str));
                   5220:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5221:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5222:             $ok_response = 1;
                   5223:         }
                   5224:     }
                   5225:     if ($ok_response) {
1.521     raeburn  5226:         return 'ok';
1.772     raeburn  5227:     } else {
                   5228:         return $response;
1.521     raeburn  5229:     }
                   5230: }
                   5231: 
1.792     raeburn  5232: sub auto_instcode_defaults {
                   5233:     my ($domain,$returnhash,$code_order) = @_;
                   5234:     my @homeservers;
1.841     albertel 5235: 
                   5236:     my %servers = &get_servers($domain,'library');
                   5237:     foreach my $tryserver (keys(%servers)) {
                   5238: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5239: 	    push(@homeservers,$tryserver);
                   5240: 	}
1.792     raeburn  5241:     }
1.841     albertel 5242: 
1.792     raeburn  5243:     my $response;
1.841     albertel 5244:     foreach my $server (@homeservers) {
1.792     raeburn  5245:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5246:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5247: 	
                   5248: 	foreach my $pair (split(/\&/,$response)) {
                   5249: 	    my ($name,$value)=split(/\=/,$pair);
                   5250: 	    if ($name eq 'code_order') {
                   5251: 		@{$code_order} = split(/\&/,&unescape($value));
                   5252: 	    } else {
                   5253: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5254: 	    }
                   5255: 	}
                   5256: 	return 'ok';
1.792     raeburn  5257:     }
1.841     albertel 5258: 
                   5259:     return $response;
1.792     raeburn  5260: } 
                   5261: 
1.777     albertel 5262: sub auto_validate_class_sec {
1.918     raeburn  5263:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5264:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5265:     my $ownerlist;
                   5266:     if (ref($owners) eq 'ARRAY') {
                   5267:         $ownerlist = join(',',@{$owners});
                   5268:     } else {
                   5269:         $ownerlist = $owners;
                   5270:     }
1.773     raeburn  5271:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5272:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5273:     return $response;
                   5274: }
                   5275: 
1.679     raeburn  5276: # ------------------------------------------------------- Course Group routines
                   5277: 
                   5278: sub get_coursegroups {
1.809     raeburn  5279:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5280:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5281: }
                   5282: 
1.679     raeburn  5283: sub modify_coursegroup {
                   5284:     my ($cdom,$cnum,$groupsettings) = @_;
                   5285:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5286: }
                   5287: 
1.809     raeburn  5288: sub toggle_coursegroup_status {
                   5289:     my ($cdom,$cnum,$group,$action) = @_;
                   5290:     my ($from_namespace,$to_namespace);
                   5291:     if ($action eq 'delete') {
                   5292:         $from_namespace = 'coursegroups';
                   5293:         $to_namespace = 'deleted_groups';
                   5294:     } else {
                   5295:         $from_namespace = 'deleted_groups';
                   5296:         $to_namespace = 'coursegroups';
                   5297:     }
                   5298:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5299:     if (my $tmp = &error(%curr_group)) {
                   5300:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5301:         return ('read error',$tmp);
                   5302:     } else {
                   5303:         my %savedsettings = %curr_group; 
1.809     raeburn  5304:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5305:         my $deloutcome;
                   5306:         if ($result eq 'ok') {
1.809     raeburn  5307:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5308:         } else {
                   5309:             return ('write error',$result);
                   5310:         }
                   5311:         if ($deloutcome eq 'ok') {
                   5312:             return 'ok';
                   5313:         } else {
                   5314:             return ('delete error',$deloutcome);
                   5315:         }
                   5316:     }
                   5317: }
                   5318: 
1.679     raeburn  5319: sub modify_group_roles {
1.957     raeburn  5320:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5321:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5322:     my $role = 'gr/'.&escape($userprivs);
                   5323:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5324:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5325:     if ($result eq 'ok') {
                   5326:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5327:     }
1.679     raeburn  5328:     return $result;
                   5329: }
                   5330: 
                   5331: sub modify_coursegroup_membership {
                   5332:     my ($cdom,$cnum,$membership) = @_;
                   5333:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5334:     return $result;
                   5335: }
                   5336: 
1.682     raeburn  5337: sub get_active_groups {
                   5338:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5339:     my $now = time;
                   5340:     my %groups = ();
                   5341:     foreach my $key (keys(%env)) {
1.811     albertel 5342:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5343:             my ($start,$end) = split(/\./,$env{$key});
                   5344:             if (($end!=0) && ($end<$now)) { next; }
                   5345:             if (($start!=0) && ($start>$now)) { next; }
                   5346:             if ($1 eq $cdom && $2 eq $cnum) {
                   5347:                 $groups{$3} = $env{$key} ;
                   5348:             }
                   5349:         }
                   5350:     }
                   5351:     return %groups;
                   5352: }
                   5353: 
1.683     raeburn  5354: sub get_group_membership {
                   5355:     my ($cdom,$cnum,$group) = @_;
                   5356:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5357: }
                   5358: 
                   5359: sub get_users_groups {
                   5360:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5361:     my @usersgroups;
1.683     raeburn  5362:     my $cachetime=1800;
                   5363: 
                   5364:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5365:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5366:     if (defined($cached)) {
1.734     albertel 5367:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5368:     } else {  
                   5369:         $grouplist = '';
1.816     raeburn  5370:         my $courseurl = &courseid_to_courseurl($courseid);
                   5371:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5372:         my $access_end = $env{'course.'.$courseid.
                   5373:                               '.default_enrollment_end_date'};
                   5374:         my $now = time;
                   5375:         foreach my $key (keys(%roleshash)) {
                   5376:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5377:                 my $group = $1;
                   5378:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5379:                     my $start = $2;
                   5380:                     my $end = $1;
                   5381:                     if ($start == -1) { next; } # deleted from group
                   5382:                     if (($start!=0) && ($start>$now)) { next; }
                   5383:                     if (($end!=0) && ($end<$now)) {
                   5384:                         if ($access_end && $access_end < $now) {
                   5385:                             if ($access_end - $end < 86400) {
                   5386:                                 push(@usersgroups,$group);
1.733     raeburn  5387:                             }
                   5388:                         }
1.817     raeburn  5389:                         next;
1.733     raeburn  5390:                     }
1.817     raeburn  5391:                     push(@usersgroups,$group);
1.683     raeburn  5392:                 }
                   5393:             }
                   5394:         }
1.817     raeburn  5395:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5396:         $grouplist = join(':',@usersgroups);
                   5397:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5398:     }
1.733     raeburn  5399:     return @usersgroups;
1.683     raeburn  5400: }
                   5401: 
                   5402: sub devalidate_getgroups_cache {
                   5403:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5404:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5405: 
1.683     raeburn  5406:     my $hashid="$udom:$uname:$courseid";
                   5407:     &devalidate_cache_new('getgroups',$hashid);
                   5408: }
                   5409: 
1.12      www      5410: # ------------------------------------------------------------------ Plain Text
                   5411: 
                   5412: sub plaintext {
1.742     raeburn  5413:     my ($short,$type,$cid) = @_;
1.758     albertel 5414:     if ($short =~ /^cr/) {
                   5415: 	return (split('/',$short))[-1];
                   5416:     }
1.742     raeburn  5417:     if (!defined($cid)) {
                   5418:         $cid = $env{'request.course.id'};
                   5419:     }
                   5420:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5421:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5422:                                           '.plaintext'});
                   5423:     }
                   5424:     my %rolenames = (
                   5425:                       Course => 'std',
                   5426:                       Group => 'alt1',
                   5427:                     );
                   5428:     if (defined($type) && 
                   5429:          defined($rolenames{$type}) && 
                   5430:          defined($prp{$short}{$rolenames{$type}})) {
                   5431:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5432:     } else {
                   5433:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5434:     }
1.12      www      5435: }
                   5436: 
                   5437: # ----------------------------------------------------------------- Assign Role
                   5438: 
                   5439: sub assignrole {
1.957     raeburn  5440:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5441:         $context)=@_;
1.21      www      5442:     my $mrole;
                   5443:     if ($role =~ /^cr\//) {
1.393     www      5444:         my $cwosec=$url;
1.811     albertel 5445:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5446: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5447:            &logthis('Refused custom assignrole: '.
                   5448:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5449: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5450:            return 'refused'; 
                   5451:         }
1.21      www      5452:         $mrole='cr';
1.678     raeburn  5453:     } elsif ($role =~ /^gr\//) {
                   5454:         my $cwogrp=$url;
1.811     albertel 5455:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5456:         unless (&allowed('mdg',$cwogrp)) {
                   5457:             &logthis('Refused group assignrole: '.
                   5458:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5459:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5460:             return 'refused';
                   5461:         }
                   5462:         $mrole='gr';
1.21      www      5463:     } else {
1.82      www      5464:         my $cwosec=$url;
1.811     albertel 5465:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5466:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5467:             my $refused;
                   5468:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5469:                 if (!(&allowed('c'.$role,$url))) {
                   5470:                     $refused = 1;
                   5471:                 }
                   5472:             } else {
                   5473:                 $refused = 1;
                   5474:             }
1.947     raeburn  5475:             if ($refused) {
                   5476:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5477:                     $refused = '';
                   5478:                 } else {
                   5479:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5480:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5481: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5482:                     return 'refused';
                   5483:                 }
1.932     raeburn  5484:             }
1.104     www      5485:         }
1.21      www      5486:         $mrole=$role;
                   5487:     }
1.620     albertel 5488:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5489:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5490:     if ($end) { $command.='_'.$end; }
1.21      www      5491:     if ($start) {
                   5492: 	if ($end) { 
1.81      www      5493:            $command.='_'.$start; 
1.21      www      5494:         } else {
1.81      www      5495:            $command.='_0_'.$start;
1.21      www      5496:         }
                   5497:     }
1.739     raeburn  5498:     my $origstart = $start;
                   5499:     my $origend = $end;
1.957     raeburn  5500:     my $delflag;
1.357     www      5501: # actually delete
                   5502:     if ($deleteflag) {
1.373     www      5503: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5504: # modify command to delete the role
1.620     albertel 5505:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5506:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5507: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5508: # set start and finish to negative values for userrolelog
                   5509:            $start=-1;
                   5510:            $end=-1;
1.957     raeburn  5511:            $delflag = 1;
1.357     www      5512:         }
                   5513:     }
                   5514: # send command
1.349     www      5515:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5516: # log new user role if status is ok
1.349     www      5517:     if ($answer eq 'ok') {
1.663     raeburn  5518: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5519: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5520:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5521:         unless ($role =~ /^gr/) {
                   5522:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5523:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5524:         }
1.349     www      5525:     }
                   5526:     return $answer;
1.169     harris41 5527: }
                   5528: 
                   5529: # -------------------------------------------------- Modify user authentication
1.197     www      5530: # Overrides without validation
                   5531: 
1.169     harris41 5532: sub modifyuserauth {
                   5533:     my ($udom,$uname,$umode,$upass)=@_;
                   5534:     my $uhome=&homeserver($uname,$udom);
1.197     www      5535:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5536:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5537:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5538:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5539:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5540: 		     &escape($upass),$uhome);
1.620     albertel 5541:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5542:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5543:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5544:     &log($udom,,$uname,$uhome,
1.620     albertel 5545:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5546:                                      $env{'user.name'}.', '.$umode.
1.197     www      5547:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5548:     unless ($reply eq 'ok') {
1.197     www      5549:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5550: 	return 'error: '.$reply;
                   5551:     }   
1.170     harris41 5552:     return 'ok';
1.80      www      5553: }
                   5554: 
1.81      www      5555: # --------------------------------------------------------------- Modify a user
1.80      www      5556: 
1.81      www      5557: sub modifyuser {
1.206     matthew  5558:     my ($udom,    $uname, $uid,
                   5559:         $umode,   $upass, $first,
                   5560:         $middle,  $last,  $gene,
1.963   ! raeburn  5561:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5562:     $udom= &LONCAPA::clean_domain($udom);
                   5563:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5564:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5565:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5566: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5567:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5568:                                      ' desiredhome not specified'). 
1.620     albertel 5569:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5570:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5571:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5572: # ----------------------------------------------------------------- Create User
1.406     albertel 5573:     if (($uhome eq 'no_host') && 
                   5574: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5575:         my $unhome='';
1.844     albertel 5576:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5577:             $unhome = $desiredhome;
1.620     albertel 5578: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5579: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5580:         } else { # load balancing routine for determining $unhome
1.81      www      5581:             my $loadm=10000000;
1.841     albertel 5582: 	    my %servers = &get_servers($udom,'library');
                   5583: 	    foreach my $tryserver (keys(%servers)) {
                   5584: 		my $answer=reply('load',$tryserver);
                   5585: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5586: 		    $loadm=$answer;
                   5587: 		    $unhome=$tryserver;
                   5588: 		}
1.80      www      5589: 	    }
                   5590:         }
                   5591:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5592: 	    return 'error: unable to find a home server for '.$uname.
                   5593:                    ' in domain '.$udom;
1.80      www      5594:         }
                   5595:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5596:                          &escape($upass),$unhome);
                   5597: 	unless ($reply eq 'ok') {
                   5598:             return 'error: '.$reply;
                   5599:         }   
1.230     stredwic 5600:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5601:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5602: 	    return 'error: unable verify users home machine.';
1.80      www      5603:         }
1.209     matthew  5604:     }   # End of creation of new user
1.80      www      5605: # ---------------------------------------------------------------------- Add ID
                   5606:     if ($uid) {
                   5607:        $uid=~tr/A-Z/a-z/;
                   5608:        my %uidhash=&idrget($udom,$uname);
1.196     www      5609:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5610:          && (!$forceid)) {
1.80      www      5611: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5612: 	      return 'error: user id "'.$uid.'" does not match '.
                   5613:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5614:           }
                   5615:        } else {
                   5616: 	  &idput($udom,($uname => $uid));
                   5617:        }
                   5618:     }
                   5619: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5620:     my @tmp=&get('environment',
1.899     raeburn  5621: 		   ['firstname','middlename','lastname','generation','id',
1.963   ! raeburn  5622:                     'permanentemail','inststatus'],
1.134     albertel 5623: 		   $udom,$uname);
1.313     matthew  5624:     my %names;
                   5625:     if ($tmp[0] =~ m/^error:.*/) { 
                   5626:         %names=(); 
                   5627:     } else {
                   5628:         %names = @tmp;
                   5629:     }
1.388     www      5630: #
                   5631: # Make sure to not trash student environment if instructor does not bother
                   5632: # to supply name and email information
                   5633: #
                   5634:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5635:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5636:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5637:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5638:     if ($email) {
                   5639:        $email=~s/[^\w\@\.\-\,]//gs;
1.963   ! raeburn  5640:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5641:     }
1.899     raeburn  5642:     if ($uid) { $names{'id'}  = $uid; }
1.963   ! raeburn  5643:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5644:     my $reply = &put('environment', \%names, $udom,$uname);
                   5645:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5646:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5647:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963   ! raeburn  5648:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
        !          5649:                  $umode.', '.$first.', '.$middle.', '.
        !          5650: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
        !          5651:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
        !          5652:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
        !          5653:     } else {
        !          5654:         $logmsg .= ' during self creation';
        !          5655:     }
        !          5656:     &logthis($logmsg);
1.134     albertel 5657:     return 'ok';
1.80      www      5658: }
                   5659: 
1.81      www      5660: # -------------------------------------------------------------- Modify student
1.80      www      5661: 
1.81      www      5662: sub modifystudent {
                   5663:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5664:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5665:         $selfenroll,$context)=@_;
1.455     albertel 5666:     if (!$cid) {
1.620     albertel 5667: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5668: 	    return 'not_in_class';
                   5669: 	}
1.80      www      5670:     }
                   5671: # --------------------------------------------------------------- Make the user
1.81      www      5672:     my $reply=&modifyuser
1.209     matthew  5673: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5674:          $desiredhome,$email);
1.80      www      5675:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5676:     # This will cause &modify_student_enrollment to get the uid from the
                   5677:     # students environment
                   5678:     $uid = undef if (!$forceid);
1.455     albertel 5679:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5680: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5681:     return $reply;
                   5682: }
                   5683: 
                   5684: sub modify_student_enrollment {
1.957     raeburn  5685:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5686:     my ($cdom,$cnum,$chome);
                   5687:     if (!$cid) {
1.620     albertel 5688: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5689: 	    return 'not_in_class';
                   5690: 	}
1.620     albertel 5691: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5692: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5693:     } else {
                   5694: 	($cdom,$cnum)=split(/_/,$cid);
                   5695:     }
1.620     albertel 5696:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5697:     if (!$chome) {
1.457     raeburn  5698: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5699:     }
1.455     albertel 5700:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5701:     # Make sure the user exists
1.81      www      5702:     my $uhome=&homeserver($uname,$udom);
                   5703:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5704: 	return 'error: no such user';
                   5705:     }
1.297     matthew  5706:     # Get student data if we were not given enough information
                   5707:     if (!defined($first)  || $first  eq '' || 
                   5708:         !defined($last)   || $last   eq '' || 
                   5709:         !defined($uid)    || $uid    eq '' || 
                   5710:         !defined($middle) || $middle eq '' || 
                   5711:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5712:         # They did not supply us with enough data to enroll the student, so
                   5713:         # we need to pick up more information.
1.297     matthew  5714:         my %tmp = &get('environment',
1.294     matthew  5715:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5716:                        ,$udom,$uname);
                   5717: 
1.800     albertel 5718:         #foreach my $key (keys(%tmp)) {
                   5719:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5720:         #}
1.294     matthew  5721:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5722:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5723:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5724:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5725:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5726:     }
1.556     albertel 5727:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5728:     my $reply=cput('classlist',
                   5729: 		   {"$uname:$udom" => 
1.515     raeburn  5730: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5731: 		   $cdom,$cnum);
1.81      www      5732:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5733: 	return 'error: '.$reply;
1.652     albertel 5734:     } else {
                   5735: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5736:     }
1.297     matthew  5737:     # Add student role to user
1.83      www      5738:     my $uurl='/'.$cid;
1.81      www      5739:     $uurl=~s/\_/\//g;
                   5740:     if ($usec) {
                   5741: 	$uurl.='/'.$usec;
                   5742:     }
1.957     raeburn  5743:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5744: }
                   5745: 
1.556     albertel 5746: sub format_name {
                   5747:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5748:     my $name;
                   5749:     if ($first ne 'lastname') {
                   5750: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5751:     } else {
                   5752: 	if ($lastname=~/\S/) {
                   5753: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5754: 	    $name=~s/\s+,/,/;
                   5755: 	} else {
                   5756: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5757: 	}
                   5758:     }
                   5759:     $name=~s/^\s+//;
                   5760:     $name=~s/\s+$//;
                   5761:     $name=~s/\s+/ /g;
                   5762:     return $name;
                   5763: }
                   5764: 
1.84      www      5765: # ------------------------------------------------- Write to course preferences
                   5766: 
                   5767: sub writecoursepref {
                   5768:     my ($courseid,%prefs)=@_;
                   5769:     $courseid=~s/^\///;
                   5770:     $courseid=~s/\_/\//g;
                   5771:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5772:     my $chome=homeserver($cnum,$cdomain);
                   5773:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5774: 	return 'error: no such course';
                   5775:     }
                   5776:     my $cstring='';
1.800     albertel 5777:     foreach my $pref (keys(%prefs)) {
                   5778: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5779:     }
1.84      www      5780:     $cstring=~s/\&$//;
                   5781:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5782: }
                   5783: 
                   5784: # ---------------------------------------------------------- Make/modify course
                   5785: 
                   5786: sub createcourse {
1.741     raeburn  5787:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5788:         $course_owner,$crstype)=@_;
1.84      www      5789:     $url=&declutter($url);
                   5790:     my $cid='';
1.264     matthew  5791:     unless (&allowed('ccc',$udom)) {
1.84      www      5792:         return 'refused';
                   5793:     }
                   5794: # ------------------------------------------------------------------- Create ID
1.674     www      5795:    my $uname=int(1+rand(9)).
                   5796:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5797:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5798:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5799: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5800:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5801:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5802:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5803:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5804:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5805:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5806:            return 'error: unable to generate unique course-ID';
                   5807:        } 
                   5808:    }
1.264     matthew  5809: # ------------------------------------------------ Check supplied server name
1.620     albertel 5810:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5811:     if (! &is_library($course_server)) {
1.264     matthew  5812:         return 'error:bad server name '.$course_server;
                   5813:     }
1.84      www      5814: # ------------------------------------------------------------- Make the course
                   5815:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5816:                       $course_server);
1.84      www      5817:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5818:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5819:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5820: 	return 'error: no such course';
                   5821:     }
1.271     www      5822: # ----------------------------------------------------------------- Course made
1.516     raeburn  5823: # log existence
1.918     raeburn  5824:     my $newcourse = {
                   5825:                     $udom.'_'.$uname => {
1.921     raeburn  5826:                                      description => $description,
                   5827:                                      inst_code   => $inst_code,
                   5828:                                      owner       => $course_owner,
                   5829:                                      type        => $crstype,
1.918     raeburn  5830:                                                 },
                   5831:                     };
1.921     raeburn  5832:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5833: # set toplevel url
1.271     www      5834:     my $topurl=$url;
                   5835:     unless ($nonstandard) {
                   5836: # ------------------------------------------ For standard courses, make top url
                   5837:         my $mapurl=&clutter($url);
1.278     www      5838:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5839:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5840: <map>
                   5841: <resource id="1" type="start"></resource>
                   5842: <resource id="2" src="$mapurl"></resource>
                   5843: <resource id="3" type="finish"></resource>
                   5844: <link index="1" from="1" to="2"></link>
                   5845: <link index="2" from="2" to="3"></link>
                   5846: </map>
                   5847: ENDINITMAP
                   5848:         $topurl=&declutter(
1.638     albertel 5849:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5850:                           );
                   5851:     }
                   5852: # ----------------------------------------------------------- Write preferences
1.84      www      5853:     &writecoursepref($udom.'_'.$uname,
                   5854:                      ('description' => $description,
1.271     www      5855:                       'url'         => $topurl));
1.84      www      5856:     return '/'.$udom.'/'.$uname;
                   5857: }
                   5858: 
1.813     albertel 5859: sub is_course {
                   5860:     my ($cdom,$cnum) = @_;
                   5861:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5862: 				undef,'.');
1.813     albertel 5863:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5864:         return 1;
                   5865:     }
                   5866:     return 0;
                   5867: }
                   5868: 
1.21      www      5869: # ---------------------------------------------------------- Assign Custom Role
                   5870: 
                   5871: sub assigncustomrole {
1.957     raeburn  5872:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5873:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  5874:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      5875: }
                   5876: 
                   5877: # ----------------------------------------------------------------- Revoke Role
                   5878: 
                   5879: sub revokerole {
1.957     raeburn  5880:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5881:     my $now=time;
1.957     raeburn  5882:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag,$selfenroll,$context);
1.21      www      5883: }
                   5884: 
                   5885: # ---------------------------------------------------------- Revoke Custom Role
                   5886: 
                   5887: sub revokecustomrole {
1.957     raeburn  5888:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5889:     my $now=time;
1.357     www      5890:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  5891:            $deleteflag,$selfenroll,$context);
1.17      www      5892: }
                   5893: 
1.533     banghart 5894: # ------------------------------------------------------------ Disk usage
1.535     albertel 5895: sub diskusage {
1.955     raeburn  5896:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   5897:     $directorypath =~ s/\/$//;
                   5898:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   5899:                        .&escape($getpropath).':'.&escape($uname).':'
                   5900:                        .&escape($udom),homeserver($uname,$udom));
                   5901:     if ($listing eq 'unknown_cmd') {
                   5902:         if ($getpropath) {
                   5903:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   5904:         }
                   5905:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   5906:     }
1.514     albertel 5907:     return $listing;
1.512     banghart 5908: }
                   5909: 
1.566     banghart 5910: sub is_locked {
                   5911:     my ($file_name, $domain, $user) = @_;
                   5912:     my @check;
                   5913:     my $is_locked;
                   5914:     push @check, $file_name;
1.613     albertel 5915:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5916: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5917:     my ($tmp)=keys(%locked);
                   5918:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5919:     
1.566     banghart 5920:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5921:         $is_locked = 'false';
                   5922:         foreach my $entry (@{$locked{$file_name}}) {
                   5923:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5924:                $is_locked = 'true';
                   5925:                last;
1.745     raeburn  5926:            }
                   5927:        }
1.566     banghart 5928:     } else {
                   5929:         $is_locked = 'false';
                   5930:     }
                   5931: }
                   5932: 
1.759     albertel 5933: sub declutter_portfile {
                   5934:     my ($file) = @_;
1.833     albertel 5935:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5936:     return $file;
                   5937: }
                   5938: 
1.559     banghart 5939: # ------------------------------------------------------------- Mark as Read Only
                   5940: 
                   5941: sub mark_as_readonly {
                   5942:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5943:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5944:     my ($tmp)=keys(%current_permissions);
                   5945:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5946:     foreach my $file (@{$files}) {
1.759     albertel 5947: 	$file = &declutter_portfile($file);
1.561     banghart 5948:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5949:     }
1.613     albertel 5950:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5951:     return;
                   5952: }
                   5953: 
1.572     banghart 5954: # ------------------------------------------------------------Save Selected Files
                   5955: 
                   5956: sub save_selected_files {
                   5957:     my ($user, $path, @files) = @_;
                   5958:     my $filename = $user."savedfiles";
1.573     banghart 5959:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5960:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5961:     foreach my $file (@files) {
1.620     albertel 5962:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5963:     }
                   5964:     foreach my $file (@other_files) {
1.574     banghart 5965:         print (OUT $file."\n");
1.572     banghart 5966:     }
1.574     banghart 5967:     close (OUT);
1.572     banghart 5968:     return 'ok';
                   5969: }
                   5970: 
1.574     banghart 5971: sub clear_selected_files {
                   5972:     my ($user) = @_;
                   5973:     my $filename = $user."savedfiles";
                   5974:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5975:     print (OUT undef);
                   5976:     close (OUT);
                   5977:     return ("ok");    
                   5978: }
                   5979: 
1.572     banghart 5980: sub files_in_path {
                   5981:     my ($user, $path) = @_;
                   5982:     my $filename = $user."savedfiles";
                   5983:     my %return_files;
1.574     banghart 5984:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5985:     while (my $line_in = <IN>) {
1.574     banghart 5986:         chomp ($line_in);
                   5987:         my @paths_and_file = split (m!/!, $line_in);
                   5988:         my $file_part = pop (@paths_and_file);
                   5989:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5990:         $path_part.='/';
                   5991:         my $path_and_file = $path_part.$file_part;
                   5992:         if ($path_part eq $path) {
                   5993:             $return_files{$file_part}= 'selected';
                   5994:         }
                   5995:     }
1.574     banghart 5996:     close (IN);
                   5997:     return (\%return_files);
1.572     banghart 5998: }
                   5999: 
                   6000: # called in portfolio select mode, to show files selected NOT in current directory
                   6001: sub files_not_in_path {
                   6002:     my ($user, $path) = @_;
                   6003:     my $filename = $user."savedfiles";
                   6004:     my @return_files;
                   6005:     my $path_part;
1.800     albertel 6006:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6007:     while (my $line = <IN>) {
1.572     banghart 6008:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6009:         my @paths_and_file = split(m|/|, $line);
                   6010:         my $file_part = pop(@paths_and_file);
                   6011:         chomp($file_part);
                   6012:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6013:         $path_part .= '/';
                   6014:         my $path_and_file = $path_part.$file_part;
                   6015:         if ($path_part ne $path) {
1.800     albertel 6016:             push(@return_files, ($path_and_file));
1.572     banghart 6017:         }
                   6018:     }
1.800     albertel 6019:     close(OUT);
1.574     banghart 6020:     return (@return_files);
1.572     banghart 6021: }
                   6022: 
1.745     raeburn  6023: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6024: 
1.745     raeburn  6025: sub get_portfile_permissions {
                   6026:     my ($domain,$user) = @_;
1.613     albertel 6027:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6028:     my ($tmp)=keys(%current_permissions);
                   6029:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6030:     return \%current_permissions;
                   6031: }
                   6032: 
                   6033: #---------------------------------------------Get portfolio file access controls
                   6034: 
1.749     raeburn  6035: sub get_access_controls {
1.745     raeburn  6036:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6037:     my %access;
                   6038:     my $real_file = $file;
                   6039:     $file =~ s/\.meta$//;
1.745     raeburn  6040:     if (defined($file)) {
1.749     raeburn  6041:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6042:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6043:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6044:             }
                   6045:         }
1.745     raeburn  6046:     } else {
1.749     raeburn  6047:         foreach my $key (keys(%{$current_permissions})) {
                   6048:             if ($key =~ /\0accesscontrol$/) {
                   6049:                 if (defined($group)) {
                   6050:                     if ($key !~ m-^\Q$group\E/-) {
                   6051:                         next;
                   6052:                     }
                   6053:                 }
                   6054:                 my ($fullpath) = split(/\0/,$key);
                   6055:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6056:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6057:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6058:                     }
                   6059:                 }
                   6060:             }
                   6061:         }
                   6062:     }
                   6063:     return %access;
                   6064: }
                   6065: 
                   6066: sub modify_access_controls {
                   6067:     my ($file_name,$changes,$domain,$user)=@_;
                   6068:     my ($outcome,$deloutcome);
                   6069:     my %store_permissions;
                   6070:     my %new_values;
                   6071:     my %new_control;
                   6072:     my %translation;
                   6073:     my @deletions = ();
                   6074:     my $now = time;
                   6075:     if (exists($$changes{'activate'})) {
                   6076:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6077:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6078:             my $numnew = scalar(@newitems);
                   6079:             for (my $i=0; $i<$numnew; $i++) {
                   6080:                 my $newkey = $newitems[$i];
                   6081:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6082:                 if ($newkey =~ /^\d+:/) { 
                   6083:                     $newkey =~ s/^(\d+)/$newid/;
                   6084:                     $translation{$1} = $newid;
                   6085:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6086:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6087:                     $translation{$1} = $newid;
                   6088:                 }
1.749     raeburn  6089:                 $new_values{$file_name."\0".$newkey} = 
                   6090:                                           $$changes{'activate'}{$newitems[$i]};
                   6091:                 $new_control{$newkey} = $now;
                   6092:             }
                   6093:         }
                   6094:     }
                   6095:     my %todelete;
                   6096:     my %changed_items;
                   6097:     foreach my $action ('delete','update') {
                   6098:         if (exists($$changes{$action})) {
                   6099:             if (ref($$changes{$action}) eq 'HASH') {
                   6100:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6101:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6102:                     if ($action eq 'delete') { 
                   6103:                         $todelete{$itemnum} = 1;
                   6104:                     } else {
                   6105:                         $changed_items{$itemnum} = $key;
                   6106:                     }
                   6107:                 }
1.745     raeburn  6108:             }
                   6109:         }
1.749     raeburn  6110:     }
                   6111:     # get lock on access controls for file.
                   6112:     my $lockhash = {
                   6113:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6114:                                                        ':'.$env{'user.domain'},
                   6115:                    }; 
                   6116:     my $tries = 0;
                   6117:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6118:    
                   6119:     while (($gotlock ne 'ok') && $tries <3) {
                   6120:         $tries ++;
                   6121:         sleep 1;
                   6122:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6123:     }
                   6124:     if ($gotlock eq 'ok') {
                   6125:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6126:         my ($tmp)=keys(%curr_permissions);
                   6127:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6128:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6129:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6130:             if (ref($curr_controls) eq 'HASH') {
                   6131:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6132:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6133:                     if (defined($todelete{$itemnum})) {
                   6134:                         push(@deletions,$file_name."\0".$control_item);
                   6135:                     } else {
                   6136:                         if (defined($changed_items{$itemnum})) {
                   6137:                             $new_control{$changed_items{$itemnum}} = $now;
                   6138:                             push(@deletions,$file_name."\0".$control_item);
                   6139:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6140:                         } else {
                   6141:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6142:                         }
                   6143:                     }
1.745     raeburn  6144:                 }
                   6145:             }
                   6146:         }
1.749     raeburn  6147:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6148:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6149:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6150:         #  remove lock
                   6151:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6152:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6153:         my ($file,$group);
                   6154:         if (&is_course($domain,$user)) {
                   6155:             ($group,$file) = split(/\//,$file_name,2);
                   6156:         } else {
                   6157:             $file = $file_name;
                   6158:         }
                   6159:         my $sqlresult =
                   6160:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6161:                                     $group);
1.749     raeburn  6162:     } else {
                   6163:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6164:     }
1.749     raeburn  6165:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6166: }
                   6167: 
1.827     raeburn  6168: sub make_public_indefinitely {
                   6169:     my ($requrl) = @_;
                   6170:     my $now = time;
                   6171:     my $action = 'activate';
                   6172:     my $aclnum = 0;
                   6173:     if (&is_portfolio_url($requrl)) {
                   6174:         my (undef,$udom,$unum,$file_name,$group) =
                   6175:             &parse_portfolio_url($requrl);
                   6176:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6177:         my %access_controls = &get_access_controls($current_perms,
                   6178:                                                    $group,$file_name);
                   6179:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6180:             my ($num,$scope,$end,$start) = 
                   6181:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6182:             if ($scope eq 'public') {
                   6183:                 if ($start <= $now && $end == 0) {
                   6184:                     $action = 'none';
                   6185:                 } else {
                   6186:                     $action = 'update';
                   6187:                     $aclnum = $num;
                   6188:                 }
                   6189:                 last;
                   6190:             }
                   6191:         }
                   6192:         if ($action eq 'none') {
                   6193:              return 'ok';
                   6194:         } else {
                   6195:             my %changes;
                   6196:             my $newend = 0;
                   6197:             my $newstart = $now;
                   6198:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6199:             $changes{$action}{$newkey} = {
                   6200:                 type => 'public',
                   6201:                 time => {
                   6202:                     start => $newstart,
                   6203:                     end   => $newend,
                   6204:                 },
                   6205:             };
                   6206:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6207:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6208:             return $outcome;
                   6209:         }
                   6210:     } else {
                   6211:         return 'invalid';
                   6212:     }
                   6213: }
                   6214: 
1.745     raeburn  6215: #------------------------------------------------------Get Marked as Read Only
                   6216: 
                   6217: sub get_marked_as_readonly {
                   6218:     my ($domain,$user,$what,$group) = @_;
                   6219:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6220:     my @readonly_files;
1.629     banghart 6221:     my $cmp1=$what;
                   6222:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6223:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6224:         if (defined($group)) {
                   6225:             if ($file_name !~ m-^\Q$group\E/-) {
                   6226:                 next;
                   6227:             }
                   6228:         }
1.561     banghart 6229:         if (ref($value) eq "ARRAY"){
                   6230:             foreach my $stored_what (@{$value}) {
1.629     banghart 6231:                 my $cmp2=$stored_what;
1.759     albertel 6232:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6233:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6234:                 }
1.629     banghart 6235:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6236:                     push(@readonly_files, $file_name);
1.745     raeburn  6237:                     last;
1.563     banghart 6238:                 } elsif (!defined($what)) {
                   6239:                     push(@readonly_files, $file_name);
1.745     raeburn  6240:                     last;
1.561     banghart 6241:                 }
                   6242:             }
1.745     raeburn  6243:         }
1.561     banghart 6244:     }
                   6245:     return @readonly_files;
                   6246: }
1.577     banghart 6247: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6248: 
1.577     banghart 6249: sub get_marked_as_readonly_hash {
1.745     raeburn  6250:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6251:     my %readonly_files;
1.745     raeburn  6252:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6253:         if (defined($group)) {
                   6254:             if ($file_name !~ m-^\Q$group\E/-) {
                   6255:                 next;
                   6256:             }
                   6257:         }
1.577     banghart 6258:         if (ref($value) eq "ARRAY"){
                   6259:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6260:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6261:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6262:                         if ($lock_descriptor eq 'graded') {
                   6263:                             $readonly_files{$file_name} = 'graded';
                   6264:                         } elsif ($lock_descriptor eq 'handback') {
                   6265:                             $readonly_files{$file_name} = 'handback';
                   6266:                         } else {
                   6267:                             if (!exists($readonly_files{$file_name})) {
                   6268:                                 $readonly_files{$file_name} = 'locked';
                   6269:                             }
                   6270:                         }
1.745     raeburn  6271:                     }
1.750     banghart 6272:                 } 
1.577     banghart 6273:             }
                   6274:         } 
                   6275:     }
                   6276:     return %readonly_files;
                   6277: }
1.559     banghart 6278: # ------------------------------------------------------------ Unmark as Read Only
                   6279: 
                   6280: sub unmark_as_readonly {
1.629     banghart 6281:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6282:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6283:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6284:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6285:     my $symb_crs = $what;
                   6286:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6287:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6288:     my ($tmp)=keys(%current_permissions);
                   6289:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6290:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6291:     foreach my $file (@readonly_files) {
1.759     albertel 6292: 	my $clean_file = &declutter_portfile($file);
                   6293: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6294: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6295:         my @new_locks;
                   6296:         my @del_keys;
                   6297:         if (ref($current_locks) eq "ARRAY"){
                   6298:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6299:                 my $compare=$locker;
1.749     raeburn  6300:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6301:                     $compare=join('',@{$locker});
1.746     raeburn  6302:                     if ($compare ne $symb_crs) {
                   6303:                         push(@new_locks, $locker);
                   6304:                     }
1.563     banghart 6305:                 }
                   6306:             }
1.650     albertel 6307:             if (scalar(@new_locks) > 0) {
1.563     banghart 6308:                 $current_permissions{$file} = \@new_locks;
                   6309:             } else {
                   6310:                 push(@del_keys, $file);
1.613     albertel 6311:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6312:                 delete($current_permissions{$file});
1.563     banghart 6313:             }
                   6314:         }
1.561     banghart 6315:     }
1.613     albertel 6316:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6317:     return;
                   6318: }
1.512     banghart 6319: 
1.17      www      6320: # ------------------------------------------------------------ Directory lister
                   6321: 
                   6322: sub dirlist {
1.955     raeburn  6323:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6324:     $uri=~s/^\///;
                   6325:     $uri=~s/\/$//;
1.253     stredwic 6326:     my ($udom, $uname);
1.955     raeburn  6327:     if ($getuserdir) {
1.253     stredwic 6328:         $udom = $userdomain;
                   6329:         $uname = $username;
1.955     raeburn  6330:     } else {
                   6331:         (undef,$udom,$uname)=split(/\//,$uri);
                   6332:         if(defined($userdomain)) {
                   6333:             $udom = $userdomain;
                   6334:         }
                   6335:         if(defined($username)) {
                   6336:             $uname = $username;
                   6337:         }
1.253     stredwic 6338:     }
1.955     raeburn  6339:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6340: 
1.955     raeburn  6341:     $dirRoot = $perlvar{'lonDocRoot'};
                   6342:     if (defined($getpropath)) {
                   6343:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6344:         $dirRoot =~ s/\/$//;
1.955     raeburn  6345:     } elsif (defined($getuserdir)) {
                   6346:         my $subdir=$uname.'__';
                   6347:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6348:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6349:                    ."/$udom/$subdir/$uname";
                   6350:     } elsif (defined($alternateRoot)) {
                   6351:         $dirRoot = $alternateRoot;
1.751     banghart 6352:     }
1.253     stredwic 6353: 
                   6354:     if($udom) {
                   6355:         if($uname) {
1.955     raeburn  6356:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6357:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6358:                               .':'.&escape($uname).':'.&escape($udom),
                   6359:                               &homeserver($uname,$udom));
                   6360:             if ($listing eq 'unknown_cmd') {
                   6361:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6362:                                   &homeserver($uname,$udom));
                   6363:             } else {
                   6364:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6365:             }
1.605     matthew  6366:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6367:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6368: 				  &homeserver($uname,$udom));
1.605     matthew  6369:                 @listing_results = split(/:/,$listing);
                   6370:             } else {
                   6371:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6372:             }
                   6373:             return @listing_results;
1.955     raeburn  6374:         } elsif(!$alternateRoot) {
1.800     albertel 6375:             my %allusers;
1.841     albertel 6376: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6377:  	    foreach my $tryserver (keys(%servers)) {
                   6378:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6379:                                   &escape($udom),$tryserver);
                   6380:                 if ($listing eq 'unknown_cmd') {
                   6381: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6382: 				      $udom, $tryserver);
                   6383:                 } else {
                   6384:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6385:                 }
1.841     albertel 6386: 		if ($listing eq 'unknown_cmd') {
                   6387: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6388: 				      $udom, $tryserver);
                   6389: 		    @listing_results = split(/:/,$listing);
                   6390: 		} else {
                   6391: 		    @listing_results =
                   6392: 			map { &unescape($_); } split(/:/,$listing);
                   6393: 		}
                   6394: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6395: 		    $listing_results[0] ne 'empty'       &&
                   6396: 		    $listing_results[0] ne 'con_lost') {
                   6397: 		    foreach my $line (@listing_results) {
                   6398: 			my ($entry) = split(/&/,$line,2);
                   6399: 			$allusers{$entry} = 1;
                   6400: 		    }
                   6401: 		}
1.253     stredwic 6402:             }
                   6403:             my $alluserstr='';
1.800     albertel 6404:             foreach my $user (sort(keys(%allusers))) {
                   6405:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6406:             }
                   6407:             $alluserstr=~s/:$//;
                   6408:             return split(/:/,$alluserstr);
                   6409:         } else {
1.800     albertel 6410:             return ('missing user name');
1.253     stredwic 6411:         }
1.955     raeburn  6412:     } elsif(!defined($getpropath)) {
1.841     albertel 6413:         my @all_domains = sort(&all_domains());
1.955     raeburn  6414:         foreach my $domain (@all_domains) {
                   6415:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6416:         }
                   6417:         return @all_domains;
                   6418:     } else {
1.800     albertel 6419:         return ('missing domain');
1.275     stredwic 6420:     }
                   6421: }
                   6422: 
                   6423: # --------------------------------------------- GetFileTimestamp
                   6424: # This function utilizes dirlist and returns the date stamp for
                   6425: # when it was last modified.  It will also return an error of -1
                   6426: # if an error occurs
                   6427: 
                   6428: sub GetFileTimestamp {
1.955     raeburn  6429:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6430:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6431:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6432:     my ($fileStat) = 
                   6433:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6434:                                  undef,$getuserdir);
1.275     stredwic 6435:     my @stats = split('&', $fileStat);
                   6436:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6437:         # @stats contains first the filename, then the stat output
                   6438:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6439:     } else {
                   6440:         return -1;
1.253     stredwic 6441:     }
1.26      www      6442: }
                   6443: 
1.712     albertel 6444: sub stat_file {
                   6445:     my ($uri) = @_;
1.787     albertel 6446:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6447: 
1.955     raeburn  6448:     my ($udom,$uname,$file);
1.712     albertel 6449:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6450: 	($udom,$uname,$file) =
1.811     albertel 6451: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6452: 	$file = 'userfiles/'.$file;
                   6453:     }
                   6454:     if ($uri =~ m-^/res/-) {
                   6455: 	($udom,$uname) = 
1.807     albertel 6456: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6457: 	$file = $uri;
                   6458:     }
                   6459: 
                   6460:     if (!$udom || !$uname || !$file) {
                   6461: 	# unable to handle the uri
                   6462: 	return ();
                   6463:     }
1.956     raeburn  6464:     my $getpropath;
                   6465:     if ($file =~ /^userfiles\//) {
                   6466:         $getpropath = 1;
                   6467:     }
1.955     raeburn  6468:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6469:     my @stats = split('&', $result);
1.721     banghart 6470:     
1.712     albertel 6471:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6472: 	shift(@stats); #filename is first
                   6473: 	return @stats;
                   6474:     }
                   6475:     return ();
                   6476: }
                   6477: 
1.26      www      6478: # -------------------------------------------------------- Value of a Condition
                   6479: 
1.713     albertel 6480: # gets the value of a specific preevaluated condition
                   6481: #    stored in the string  $env{user.state.<cid>}
                   6482: # or looks up a condition reference in the bighash and if if hasn't
                   6483: # already been evaluated recurses into docondval to get the value of
                   6484: # the condition, then memoizing it to 
                   6485: #   $env{user.state.<cid>.<condition>}
1.40      www      6486: sub directcondval {
                   6487:     my $number=shift;
1.620     albertel 6488:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6489: 	&Apache::lonuserstate::evalstate();
                   6490:     }
1.713     albertel 6491:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6492: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6493:     } elsif ($number =~ /^_/) {
                   6494: 	my $sub_condition;
                   6495: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6496: 		&GDBM_READER(),0640)) {
                   6497: 	    $sub_condition=$bighash{'conditions'.$number};
                   6498: 	    untie(%bighash);
                   6499: 	}
                   6500: 	my $value = &docondval($sub_condition);
1.949     raeburn  6501: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6502: 	return $value;
                   6503:     }
1.620     albertel 6504:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6505:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6506:     } else {
                   6507:        return 2;
                   6508:     }
                   6509: }
                   6510: 
1.713     albertel 6511: # get the collection of conditions for this resource
1.26      www      6512: sub condval {
                   6513:     my $condidx=shift;
1.54      www      6514:     my $allpathcond='';
1.713     albertel 6515:     foreach my $cond (split(/\|/,$condidx)) {
                   6516: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6517: 	    $allpathcond.=
                   6518: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6519: 	}
1.191     harris41 6520:     }
1.54      www      6521:     $allpathcond=~s/\|$//;
1.713     albertel 6522:     return &docondval($allpathcond);
                   6523: }
                   6524: 
                   6525: #evaluates an expression of conditions
                   6526: sub docondval {
                   6527:     my ($allpathcond) = @_;
                   6528:     my $result=0;
                   6529:     if ($env{'request.course.id'}
                   6530: 	&& defined($allpathcond)) {
                   6531: 	my $operand='|';
                   6532: 	my @stack;
                   6533: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6534: 	    if ($chunk eq '(') {
                   6535: 		push @stack,($operand,$result);
                   6536: 	    } elsif ($chunk eq ')') {
                   6537: 		my $before=pop @stack;
                   6538: 		if (pop @stack eq '&') {
                   6539: 		    $result=$result>$before?$before:$result;
                   6540: 		} else {
                   6541: 		    $result=$result>$before?$result:$before;
                   6542: 		}
                   6543: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6544: 		$operand=$chunk;
                   6545: 	    } else {
                   6546: 		my $new=directcondval($chunk);
                   6547: 		if ($operand eq '&') {
                   6548: 		    $result=$result>$new?$new:$result;
                   6549: 		} else {
                   6550: 		    $result=$result>$new?$result:$new;
                   6551: 		}
                   6552: 	    }
                   6553: 	}
1.26      www      6554:     }
                   6555:     return $result;
1.421     albertel 6556: }
                   6557: 
                   6558: # ---------------------------------------------------- Devalidate courseresdata
                   6559: 
                   6560: sub devalidatecourseresdata {
                   6561:     my ($coursenum,$coursedomain)=@_;
                   6562:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6563:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6564: }
                   6565: 
1.763     www      6566: 
1.200     www      6567: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6568: #
                   6569: #  Parameters:
                   6570: #      $coursenum    - Number of the course.
                   6571: #      $coursedomain - Domain at which the course was created.
                   6572: #  Returns:
                   6573: #     A hash of the course parameters along (I think) with timestamps
                   6574: #     and version info.
1.877     foxr     6575: 
1.624     albertel 6576: sub get_courseresdata {
                   6577:     my ($coursenum,$coursedomain)=@_;
1.200     www      6578:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6579:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6580:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6581:     my %dumpreply;
1.417     albertel 6582:     unless (defined($cached)) {
1.624     albertel 6583: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6584: 	$result=\%dumpreply;
1.251     albertel 6585: 	my ($tmp) = keys(%dumpreply);
                   6586: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6587: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6588: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6589: 	    return $tmp;
1.416     albertel 6590: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6591: 	    $result=undef;
1.599     albertel 6592: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6593: 	}
                   6594:     }
1.624     albertel 6595:     return $result;
                   6596: }
                   6597: 
1.633     albertel 6598: sub devalidateuserresdata {
                   6599:     my ($uname,$udom)=@_;
                   6600:     my $hashid="$udom:$uname";
                   6601:     &devalidate_cache_new('userres',$hashid);
                   6602: }
                   6603: 
1.624     albertel 6604: sub get_userresdata {
                   6605:     my ($uname,$udom)=@_;
                   6606:     #most student don\'t have any data set, check if there is some data
                   6607:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6608: 
                   6609:     my $hashid="$udom:$uname";
                   6610:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6611:     if (!defined($cached)) {
                   6612: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6613: 	$result=\%resourcedata;
                   6614: 	&do_cache_new('userres',$hashid,$result,600);
                   6615:     }
                   6616:     my ($tmp)=keys(%$result);
                   6617:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6618: 	return $result;
                   6619:     }
                   6620:     #error 2 occurs when the .db doesn't exist
                   6621:     if ($tmp!~/error: 2 /) {
1.672     albertel 6622: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6623: 		 " Trying to get resource data for ".
                   6624: 		 $uname." at ".$udom.": ".
                   6625: 		 $tmp."</font>");
                   6626:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6627: 	#&EXT_cache_set($udom,$uname);
                   6628: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6629: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6630:     }
                   6631:     return $tmp;
                   6632: }
1.879     foxr     6633: #----------------------------------------------- resdata - return resource data
                   6634: #  Purpose:
                   6635: #    Return resource data for either users or for a course.
                   6636: #  Parameters:
                   6637: #     $name      - Course/user name.
                   6638: #     $domain    - Name of the domain the user/course is registered on.
                   6639: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6640: #     @which     - Array of names of resources desired.
                   6641: #  Returns:
                   6642: #     The value of the first reasource in @which that is found in the
                   6643: #     resource hash.
                   6644: #  Exceptional Conditions:
                   6645: #     If the $type passed in is not valid (not the string 'course' or 
                   6646: #     'user', an undefined  reference is returned.
                   6647: #     If none of the resources are found, an undef is returned
1.624     albertel 6648: sub resdata {
                   6649:     my ($name,$domain,$type,@which)=@_;
                   6650:     my $result;
                   6651:     if ($type eq 'course') {
                   6652: 	$result=&get_courseresdata($name,$domain);
                   6653:     } elsif ($type eq 'user') {
                   6654: 	$result=&get_userresdata($name,$domain);
                   6655:     }
                   6656:     if (!ref($result)) { return $result; }    
1.251     albertel 6657:     foreach my $item (@which) {
1.927     albertel 6658: 	if (defined($result->{$item->[0]})) {
                   6659: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6660: 	}
1.250     albertel 6661:     }
1.291     albertel 6662:     return undef;
1.200     www      6663: }
                   6664: 
1.379     matthew  6665: #
                   6666: # EXT resource caching routines
                   6667: #
                   6668: 
                   6669: sub clear_EXT_cache_status {
1.383     albertel 6670:     &delenv('cache.EXT.');
1.379     matthew  6671: }
                   6672: 
                   6673: sub EXT_cache_status {
                   6674:     my ($target_domain,$target_user) = @_;
1.383     albertel 6675:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6676:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6677:         # We know already the user has no data
                   6678:         return 1;
                   6679:     } else {
                   6680:         return 0;
                   6681:     }
                   6682: }
                   6683: 
                   6684: sub EXT_cache_set {
                   6685:     my ($target_domain,$target_user) = @_;
1.383     albertel 6686:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6687:     #&appenv({$cachename => time});
1.379     matthew  6688: }
                   6689: 
1.28      www      6690: # --------------------------------------------------------- Value of a Variable
1.58      www      6691: sub EXT {
1.715     albertel 6692: 
1.395     albertel 6693:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6694:     unless ($varname) { return ''; }
1.218     albertel 6695:     #get real user name/domain, courseid and symb
                   6696:     my $courseid;
1.359     albertel 6697:     my $publicuser;
1.427     www      6698:     if ($symbparm) {
                   6699: 	$symbparm=&get_symb_from_alias($symbparm);
                   6700:     }
1.218     albertel 6701:     if (!($uname && $udom)) {
1.790     albertel 6702:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6703:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6704:     } else {
1.620     albertel 6705: 	$courseid=$env{'request.course.id'};
1.218     albertel 6706:     }
1.48      www      6707:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6708:     my $rest;
1.320     albertel 6709:     if (defined($therest[0])) {
1.48      www      6710:        $rest=join('.',@therest);
                   6711:     } else {
                   6712:        $rest='';
                   6713:     }
1.320     albertel 6714: 
1.57      www      6715:     my $qualifierrest=$qualifier;
                   6716:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6717:     my $spacequalifierrest=$space;
                   6718:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6719:     if ($realm eq 'user') {
1.48      www      6720: # --------------------------------------------------------------- user.resource
                   6721: 	if ($space eq 'resource') {
1.651     albertel 6722: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6723: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6724: 		 &&
1.744     albertel 6725: 		 ($symbparm eq &symbread()) ) {	
                   6726: 		# if we are in the middle of processing the resource the
                   6727: 		# get the value we are planning on committing
                   6728:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6729:                     return $Apache::lonhomework::results{$qualifierrest};
                   6730:                 } else {
                   6731:                     return $Apache::lonhomework::history{$qualifierrest};
                   6732:                 }
1.335     albertel 6733: 	    } else {
1.359     albertel 6734: 		my %restored;
1.620     albertel 6735: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6736: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6737: 		} else {
                   6738: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6739: 		}
1.335     albertel 6740: 		return $restored{$qualifierrest};
                   6741: 	    }
1.48      www      6742: # ----------------------------------------------------------------- user.access
                   6743:         } elsif ($space eq 'access') {
1.218     albertel 6744: 	    # FIXME - not supporting calls for a specific user
1.48      www      6745:             return &allowed($qualifier,$rest);
                   6746: # ------------------------------------------ user.preferences, user.environment
                   6747:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6748: 	    if (($uname eq $env{'user.name'}) &&
                   6749: 		($udom eq $env{'user.domain'})) {
                   6750: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6751: 	    } else {
1.359     albertel 6752: 		my %returnhash;
                   6753: 		if (!$publicuser) {
                   6754: 		    %returnhash=&userenvironment($udom,$uname,
                   6755: 						 $qualifierrest);
                   6756: 		}
1.218     albertel 6757: 		return $returnhash{$qualifierrest};
                   6758: 	    }
1.48      www      6759: # ----------------------------------------------------------------- user.course
                   6760:         } elsif ($space eq 'course') {
1.218     albertel 6761: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6762:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6763: # ------------------------------------------------------------------- user.role
                   6764:         } elsif ($space eq 'role') {
1.218     albertel 6765: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6766:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6767:             if ($qualifier eq 'value') {
                   6768: 		return $role;
                   6769:             } elsif ($qualifier eq 'extent') {
                   6770:                 return $where;
                   6771:             }
                   6772: # ----------------------------------------------------------------- user.domain
                   6773:         } elsif ($space eq 'domain') {
1.218     albertel 6774:             return $udom;
1.48      www      6775: # ------------------------------------------------------------------- user.name
                   6776:         } elsif ($space eq 'name') {
1.218     albertel 6777:             return $uname;
1.48      www      6778: # ---------------------------------------------------- Any other user namespace
1.29      www      6779:         } else {
1.359     albertel 6780: 	    my %reply;
                   6781: 	    if (!$publicuser) {
                   6782: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6783: 	    }
                   6784: 	    return $reply{$qualifierrest};
1.48      www      6785:         }
1.236     www      6786:     } elsif ($realm eq 'query') {
                   6787: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6788:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6789: 						[$spacequalifierrest]);
1.620     albertel 6790: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6791:    } elsif ($realm eq 'request') {
1.48      www      6792: # ------------------------------------------------------------- request.browser
                   6793:         if ($space eq 'browser') {
1.430     www      6794: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6795: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6796: 		    return 1;
                   6797: 		} else {
                   6798: 		    return 0;
                   6799: 		}
                   6800: 	    } else {
1.620     albertel 6801: 		return $env{'browser.'.$qualifier};
1.430     www      6802: 	    }
1.57      www      6803: # ------------------------------------------------------------ request.filename
                   6804:         } else {
1.620     albertel 6805:             return $env{'request.'.$spacequalifierrest};
1.29      www      6806:         }
1.28      www      6807:     } elsif ($realm eq 'course') {
1.48      www      6808: # ---------------------------------------------------------- course.description
1.620     albertel 6809:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6810:     } elsif ($realm eq 'resource') {
1.165     www      6811: 
1.620     albertel 6812: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6813: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6814: 	}
1.693     albertel 6815: 
                   6816: 	if ($space eq 'title') {
                   6817: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6818: 	    return &gettitle($symbparm);
                   6819: 	}
                   6820: 	
                   6821: 	if ($space eq 'map') {
                   6822: 	    my ($map) = &decode_symb($symbparm);
                   6823: 	    return &symbread($map);
                   6824: 	}
1.905     albertel 6825: 	if ($space eq 'filename') {
                   6826: 	    if ($symbparm) {
                   6827: 		return &clutter((&decode_symb($symbparm))[2]);
                   6828: 	    }
                   6829: 	    return &hreflocation('',$env{'request.filename'});
                   6830: 	}
1.693     albertel 6831: 
                   6832: 	my ($section, $group, @groups);
1.593     albertel 6833: 	my ($courselevelm,$courselevel);
1.539     albertel 6834: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6835: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6836: 
1.218     albertel 6837: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6838: 
1.60      www      6839: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6840: 	    my $symbp=$symbparm;
1.735     albertel 6841: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6842: 
                   6843: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6844: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6845: 
1.620     albertel 6846: 	    if (($env{'user.name'} eq $uname) &&
                   6847: 		($env{'user.domain'} eq $udom)) {
                   6848: 		$section=$env{'request.course.sec'};
1.733     raeburn  6849:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6850:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6851: 	    } else {
1.539     albertel 6852: 		if (! defined($usection)) {
1.551     albertel 6853: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6854: 		} else {
                   6855: 		    $section = $usection;
                   6856: 		}
1.733     raeburn  6857:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6858: 	    }
                   6859: 
                   6860: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6861: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6862: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6863: 
1.593     albertel 6864: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6865: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6866: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6867: 
1.60      www      6868: # ----------------------------------------------------------- first, check user
1.624     albertel 6869: 
                   6870: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6871: 				       ([$courselevelr,'resource'],
                   6872: 					[$courselevelm,'map'     ],
                   6873: 					[$courselevel, 'course'  ]));
1.931     albertel 6874: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6875: 
1.594     albertel 6876: # ------------------------------------------------ second, check some of course
1.684     raeburn  6877:             my $coursereply;
1.691     raeburn  6878:             if (@groups > 0) {
                   6879:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6880:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6881:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6882:             }
1.96      www      6883: 
1.684     raeburn  6884: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6885: 				  $env{'course.'.$courseid.'.domain'},
                   6886: 				  'course',
                   6887: 				  ([$seclevelr,   'resource'],
                   6888: 				   [$seclevelm,   'map'     ],
                   6889: 				   [$seclevel,    'course'  ],
                   6890: 				   [$courselevelr,'resource']));
                   6891: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6892: 
1.60      www      6893: # ------------------------------------------------------ third, check map parms
1.218     albertel 6894: 	    my %parmhash=();
                   6895: 	    my $thisparm='';
                   6896: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6897: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6898: 		    &GDBM_READER(),0640)) {
1.218     albertel 6899: 		$thisparm=$parmhash{$symbparm};
                   6900: 		untie(%parmhash);
                   6901: 	    }
1.927     albertel 6902: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6903: 	}
1.594     albertel 6904: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6905: 
1.218     albertel 6906: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6907: 	my $filename;
                   6908: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6909: 	if ($symbparm) {
1.409     www      6910: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6911: 	} else {
1.620     albertel 6912: 	    $filename=$env{'request.filename'};
1.282     albertel 6913: 	}
                   6914: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6915: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6916: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6917: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6918: 
1.927     albertel 6919: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6920: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6921: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6922: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6923: 				     $env{'course.'.$courseid.'.domain'},
                   6924: 				     'course',
1.927     albertel 6925: 				     ([$courselevelm,'map'   ],
                   6926: 				      [$courselevel, 'course']));
                   6927: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6928: 	}
1.145     www      6929: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6930: 	unless ($space eq '0') {
1.336     albertel 6931: 	    my @parts=split(/_/,$space);
                   6932: 	    my $id=pop(@parts);
                   6933: 	    my $part=join('_',@parts);
                   6934: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6935: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6936: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6937: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6938: 	}
1.395     albertel 6939: 	if ($recurse) { return undef; }
                   6940: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6941: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6942: # ---------------------------------------------------- Any other user namespace
                   6943:     } elsif ($realm eq 'environment') {
                   6944: # ----------------------------------------------------------------- environment
1.620     albertel 6945: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6946: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6947: 	} else {
1.770     albertel 6948: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6949: 		return '';
                   6950: 	    }
1.219     albertel 6951: 	    my %returnhash=&userenvironment($udom,$uname,
                   6952: 					    $spacequalifierrest);
                   6953: 	    return $returnhash{$spacequalifierrest};
                   6954: 	}
1.28      www      6955:     } elsif ($realm eq 'system') {
1.48      www      6956: # ----------------------------------------------------------------- system.time
                   6957: 	if ($space eq 'time') {
                   6958: 	    return time;
                   6959:         }
1.696     albertel 6960:     } elsif ($realm eq 'server') {
                   6961: # ----------------------------------------------------------------- system.time
                   6962: 	if ($space eq 'name') {
                   6963: 	    return $ENV{'SERVER_NAME'};
                   6964:         }
1.28      www      6965:     }
1.48      www      6966:     return '';
1.61      www      6967: }
                   6968: 
1.927     albertel 6969: sub get_reply {
                   6970:     my ($reply_value) = @_;
1.940     raeburn  6971:     if (ref($reply_value) eq 'ARRAY') {
                   6972:         if (wantarray) {
                   6973: 	    return @$reply_value;
                   6974:         }
                   6975:         return $reply_value->[0];
                   6976:     } else {
                   6977:         return $reply_value;
1.927     albertel 6978:     }
                   6979: }
                   6980: 
1.691     raeburn  6981: sub check_group_parms {
                   6982:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6983:     my @groupitems = ();
                   6984:     my $resultitem;
1.927     albertel 6985:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6986:     foreach my $group (@{$groups}) {
                   6987:         foreach my $level (@levels) {
1.927     albertel 6988:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6989:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6990:         }
                   6991:     }
                   6992:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6993:                             $env{'course.'.$courseid.'.domain'},
                   6994:                                      'course',@groupitems);
                   6995:     return $coursereply;
                   6996: }
                   6997: 
                   6998: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6999:     my ($courseid,@groups) = @_;
                   7000:     @groups = sort(@groups);
1.691     raeburn  7001:     return @groups;
                   7002: }
                   7003: 
1.395     albertel 7004: sub packages_tab_default {
                   7005:     my ($uri,$varname)=@_;
                   7006:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7007: 
                   7008:     my (@extension,@specifics,$do_default);
                   7009:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7010: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7011: 	if ($pack_type eq 'default') {
                   7012: 	    $do_default=1;
                   7013: 	} elsif ($pack_type eq 'extension') {
                   7014: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7015: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7016: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7017: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7018: 	}
                   7019:     }
                   7020:     # first look for a package that matches the requested part id
                   7021:     foreach my $package (@specifics) {
                   7022: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7023: 	next if ($pack_part ne $part);
                   7024: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7025: 	    return $packagetab{"$pack_type&$name&default"};
                   7026: 	}
                   7027:     }
                   7028:     # look for any possible matching non extension_ package
                   7029:     foreach my $package (@specifics) {
                   7030: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7031: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7032: 	    return $packagetab{"$pack_type&$name&default"};
                   7033: 	}
1.585     albertel 7034: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7035: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7036: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7037: 	}
                   7038:     }
1.738     albertel 7039:     # look for any posible extension_ match
                   7040:     foreach my $package (@extension) {
                   7041: 	my ($package,$pack_type)=@{$package};
                   7042: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7043: 	    return $packagetab{"$pack_type&$name&default"};
                   7044: 	}
                   7045: 	if (defined($packagetab{$package."&$name&default"})) {
                   7046: 	    return $packagetab{$package."&$name&default"};
                   7047: 	}
                   7048:     }
                   7049:     # look for a global default setting
                   7050:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7051: 	return $packagetab{"default&$name&default"};
                   7052:     }
1.395     albertel 7053:     return undef;
                   7054: }
                   7055: 
1.334     albertel 7056: sub add_prefix_and_part {
                   7057:     my ($prefix,$part)=@_;
                   7058:     my $keyroot;
                   7059:     if (defined($prefix) && $prefix !~ /^__/) {
                   7060: 	# prefix that has a part already
                   7061: 	$keyroot=$prefix;
                   7062:     } elsif (defined($prefix)) {
                   7063: 	# prefix that is missing a part
                   7064: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7065:     } else {
                   7066: 	# no prefix at all
                   7067: 	if (defined($part)) { $keyroot='_'.$part; }
                   7068:     }
                   7069:     return $keyroot;
                   7070: }
                   7071: 
1.71      www      7072: # ---------------------------------------------------------------- Get metadata
                   7073: 
1.599     albertel 7074: my %metaentry;
1.71      www      7075: sub metadata {
1.176     www      7076:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7077:     $uri=&declutter($uri);
1.288     albertel 7078:     # if it is a non metadata possible uri return quickly
1.529     albertel 7079:     if (($uri eq '') || 
                   7080: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7081: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7082:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7083: 	return undef;
                   7084:     }
                   7085:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7086: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7087: 	return undef;
1.288     albertel 7088:     }
1.73      www      7089:     my $filename=$uri;
                   7090:     $uri=~s/\.meta$//;
1.172     www      7091: #
                   7092: # Is the metadata already cached?
1.177     www      7093: # Look at timestamp of caching
1.172     www      7094: # Everything is cached by the main uri, libraries are never directly cached
                   7095: #
1.428     albertel 7096:     if (!defined($liburi)) {
1.599     albertel 7097: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7098: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7099:     }
                   7100:     {
1.172     www      7101: #
                   7102: # Is this a recursive call for a library?
                   7103: #
1.599     albertel 7104: #	if (! exists($metacache{$uri})) {
                   7105: #	    $metacache{$uri}={};
                   7106: #	}
1.924     albertel 7107: 	my $cachetime = 60*60;
1.171     www      7108:         if ($liburi) {
                   7109: 	    $liburi=&declutter($liburi);
                   7110:             $filename=$liburi;
1.401     bowersj2 7111:         } else {
1.599     albertel 7112: 	    &devalidate_cache_new('meta',$uri);
                   7113: 	    undef(%metaentry);
1.401     bowersj2 7114: 	}
1.140     www      7115:         my %metathesekeys=();
1.73      www      7116:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7117: 	my $metastring;
1.924     albertel 7118: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7119: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7120: 	    $metastring = 
1.929     albertel 7121: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7122: 					  ('grade_target' => 'meta'));
                   7123: 	    $cachetime = 1; # only want this cached in the child not long term
                   7124: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7125: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7126: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7127: 	    $metastring=&getfile($file);
1.489     albertel 7128: 	}
1.208     albertel 7129:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7130:         my $token;
1.140     www      7131:         undef %metathesekeys;
1.71      www      7132:         while ($token=$parser->get_token) {
1.339     albertel 7133: 	    if ($token->[0] eq 'S') {
                   7134: 		if (defined($token->[2]->{'package'})) {
1.172     www      7135: #
                   7136: # This is a package - get package info
                   7137: #
1.339     albertel 7138: 		    my $package=$token->[2]->{'package'};
                   7139: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7140: 		    if (defined($token->[2]->{'id'})) { 
                   7141: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7142: 		    }
1.599     albertel 7143: 		    if ($metaentry{':packages'}) {
                   7144: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7145: 		    } else {
1.599     albertel 7146: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7147: 		    }
1.736     albertel 7148: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7149: 			my $part=$keyroot;
                   7150: 			$part=~s/^\_//;
1.736     albertel 7151: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7152: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7153: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7154: 			    # ignore package.tab specified default values
                   7155:                             # here &package_tab_default() will fetch those
                   7156: 			    if ($subp eq 'default') { next; }
1.736     albertel 7157: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7158: 			    my $unikey;
                   7159: 			    if ($pack =~ /_0$/) {
                   7160: 				$unikey='parameter_0_'.$name;
                   7161: 				$part=0;
                   7162: 			    } else {
                   7163: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7164: 			    }
1.339     albertel 7165: 			    if ($subp eq 'display') {
                   7166: 				$value.=' [Part: '.$part.']';
                   7167: 			    }
1.599     albertel 7168: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7169: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7170: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7171: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7172: 			    }
1.599     albertel 7173: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7174: 				$metaentry{':'.$unikey}=
                   7175: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7176: 			    }
1.339     albertel 7177: 			}
                   7178: 		    }
                   7179: 		} else {
1.172     www      7180: #
                   7181: # This is not a package - some other kind of start tag
1.339     albertel 7182: #
                   7183: 		    my $entry=$token->[1];
                   7184: 		    my $unikey;
                   7185: 		    if ($entry eq 'import') {
                   7186: 			$unikey='';
                   7187: 		    } else {
                   7188: 			$unikey=$entry;
                   7189: 		    }
                   7190: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7191: 
                   7192: 		    if (defined($token->[2]->{'id'})) { 
                   7193: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7194: 		    }
1.175     www      7195: 
1.339     albertel 7196: 		    if ($entry eq 'import') {
1.175     www      7197: #
                   7198: # Importing a library here
1.339     albertel 7199: #
                   7200: 			if ($depthcount<20) {
                   7201: 			    my $location=$parser->get_text('/import');
                   7202: 			    my $dir=$filename;
                   7203: 			    $dir=~s|[^/]*$||;
                   7204: 			    $location=&filelocation($dir,$location);
1.736     albertel 7205: 			    my $metadata = 
                   7206: 				&metadata($uri,'keys', $location,$unikey,
                   7207: 					  $depthcount+1);
                   7208: 			    foreach my $meta (split(',',$metadata)) {
                   7209: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7210: 				$metathesekeys{$meta}=1;
1.339     albertel 7211: 			    }
                   7212: 			}
                   7213: 		    } else { 
                   7214: 			
                   7215: 			if (defined($token->[2]->{'name'})) { 
                   7216: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7217: 			}
                   7218: 			$metathesekeys{$unikey}=1;
1.736     albertel 7219: 			foreach my $param (@{$token->[3]}) {
                   7220: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7221: 				$token->[2]->{$param};
1.339     albertel 7222: 			}
                   7223: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7224: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7225: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7226: 		 # only ws inside the tag, and not in default, so use default
                   7227: 		 # as value
1.599     albertel 7228: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7229: 			} elsif ( $internaltext =~ /\S/ ) {
                   7230: 		  # something interesting inside the tag
                   7231: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7232: 			} else {
1.908     albertel 7233: 		  # no interesting values, don't set a default
1.339     albertel 7234: 			}
1.172     www      7235: # end of not-a-package not-a-library import
1.339     albertel 7236: 		    }
1.172     www      7237: # end of not-a-package start tag
1.339     albertel 7238: 		}
1.172     www      7239: # the next is the end of "start tag"
1.339     albertel 7240: 	    }
                   7241: 	}
1.483     albertel 7242: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7243: 	$extension = lc($extension);
                   7244: 	if ($extension eq 'htm') { $extension='html'; }
                   7245: 
1.737     albertel 7246: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7247: 	    #no specific packages #how's our extension
                   7248: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7249: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7250: 					 \%metathesekeys);
                   7251: 	}
1.883     albertel 7252: 
                   7253: 	if (!exists($metaentry{':packages'})
                   7254: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7255: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7256: 		#no specific packages well let's get default then
                   7257: 		if ($key!~/^default&/) { next; }
1.488     albertel 7258: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7259: 					     \%metathesekeys);
                   7260: 	    }
                   7261: 	}
1.338     www      7262: # are there custom rights to evaluate
1.599     albertel 7263: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7264: 
1.338     www      7265:     #
                   7266:     # Importing a rights file here
1.339     albertel 7267:     #
                   7268: 	    unless ($depthcount) {
1.599     albertel 7269: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7270: 		my $dir=$filename;
                   7271: 		$dir=~s|[^/]*$||;
                   7272: 		$location=&filelocation($dir,$location);
1.736     albertel 7273: 		my $rights_metadata =
                   7274: 		    &metadata($uri,'keys',$location,'_rights',
                   7275: 			      $depthcount+1);
                   7276: 		foreach my $rights (split(',',$rights_metadata)) {
                   7277: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7278: 		    $metathesekeys{$rights}=1;
1.339     albertel 7279: 		}
                   7280: 	    }
                   7281: 	}
1.737     albertel 7282: 	# uniqifiy package listing
                   7283: 	my %seen;
                   7284: 	my @uniq_packages =
                   7285: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7286: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7287: 
                   7288: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7289: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7290: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7291: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7292: # this is the end of "was not already recently cached
1.71      www      7293:     }
1.599     albertel 7294:     return $metaentry{':'.$what};
1.261     albertel 7295: }
                   7296: 
1.488     albertel 7297: sub metadata_create_package_def {
1.483     albertel 7298:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7299:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7300:     if ($subp eq 'default') { next; }
                   7301:     
1.599     albertel 7302:     if (defined($metaentry{':packages'})) {
                   7303: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7304:     } else {
1.599     albertel 7305: 	$metaentry{':packages'}=$package;
1.483     albertel 7306:     }
                   7307:     my $value=$packagetab{$key};
                   7308:     my $unikey;
                   7309:     $unikey='parameter_0_'.$name;
1.599     albertel 7310:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7311:     $$metathesekeys{$unikey}=1;
1.599     albertel 7312:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7313: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7314:     }
1.599     albertel 7315:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7316: 	$metaentry{':'.$unikey}=
                   7317: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7318:     }
                   7319: }
                   7320: 
1.261     albertel 7321: sub metadata_generate_part0 {
                   7322:     my ($metadata,$metacache,$uri) = @_;
                   7323:     my %allnames;
1.737     albertel 7324:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7325: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7326: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7327: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7328: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7329: 	    $allnames{$name}=$part;
                   7330: 	  }
                   7331: 	}
                   7332:     }
                   7333:     foreach my $name (keys(%allnames)) {
                   7334:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7335:       my $key=":parameter_0_$name";
1.261     albertel 7336:       $$metacache{"$key.part"}='0';
                   7337:       $$metacache{"$key.name"}=$name;
1.428     albertel 7338:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7339: 					   $allnames{$name}.'_'.$name.
                   7340: 					   '.type'};
1.428     albertel 7341:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7342: 			     '.display'};
1.644     www      7343:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7344:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7345:       $$metacache{"$key.display"}=$olddis;
                   7346:     }
1.71      www      7347: }
                   7348: 
1.764     albertel 7349: # ------------------------------------------------------ Devalidate title cache
                   7350: 
                   7351: sub devalidate_title_cache {
                   7352:     my ($url)=@_;
                   7353:     if (!$env{'request.course.id'}) { return; }
                   7354:     my $symb=&symbread($url);
                   7355:     if (!$symb) { return; }
                   7356:     my $key=$env{'request.course.id'}."\0".$symb;
                   7357:     &devalidate_cache_new('title',$key);
                   7358: }
                   7359: 
1.301     www      7360: # ------------------------------------------------- Get the title of a resource
                   7361: 
                   7362: sub gettitle {
                   7363:     my $urlsymb=shift;
                   7364:     my $symb=&symbread($urlsymb);
1.534     albertel 7365:     if ($symb) {
1.620     albertel 7366: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7367: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7368: 	if (defined($cached)) { 
                   7369: 	    return $result;
                   7370: 	}
1.534     albertel 7371: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7372: 	my $title='';
1.907     albertel 7373: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7374: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7375: 	} else {
                   7376: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7377: 		    &GDBM_READER(),0640)) {
                   7378: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7379: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7380: 		untie(%bighash);
                   7381: 	    }
1.534     albertel 7382: 	}
                   7383: 	$title=~s/\&colon\;/\:/gs;
                   7384: 	if ($title) {
1.599     albertel 7385: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7386: 	}
                   7387: 	$urlsymb=$url;
                   7388:     }
                   7389:     my $title=&metadata($urlsymb,'title');
                   7390:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7391:     return $title;
1.301     www      7392: }
1.613     albertel 7393: 
1.614     albertel 7394: sub get_slot {
                   7395:     my ($which,$cnum,$cdom)=@_;
                   7396:     if (!$cnum || !$cdom) {
1.790     albertel 7397: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7398: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7399: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7400:     }
1.703     albertel 7401:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7402:     my %slotinfo;
                   7403:     if (exists($remembered{$key})) {
                   7404: 	$slotinfo{$which} = $remembered{$key};
                   7405:     } else {
                   7406: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7407: 	&Apache::lonhomework::showhash(%slotinfo);
                   7408: 	my ($tmp)=keys(%slotinfo);
                   7409: 	if ($tmp=~/^error:/) { return (); }
                   7410: 	$remembered{$key} = $slotinfo{$which};
                   7411:     }
1.616     albertel 7412:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7413: 	return %{$slotinfo{$which}};
                   7414:     }
                   7415:     return $slotinfo{$which};
1.614     albertel 7416: }
1.31      www      7417: # ------------------------------------------------- Update symbolic store links
                   7418: 
                   7419: sub symblist {
                   7420:     my ($mapname,%newhash)=@_;
1.438     www      7421:     $mapname=&deversion(&declutter($mapname));
1.31      www      7422:     my %hash;
1.620     albertel 7423:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7424:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7425:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7426: 	    foreach my $url (keys %newhash) {
                   7427: 		next if ($url eq 'last_known'
                   7428: 			 && $env{'form.no_update_last_known'});
                   7429: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7430: 						    $newhash{$url}->[1],
                   7431: 						    $newhash{$url}->[0]);
1.191     harris41 7432:             }
1.31      www      7433:             if (untie(%hash)) {
                   7434: 		return 'ok';
                   7435:             }
                   7436:         }
                   7437:     }
                   7438:     return 'error';
1.212     www      7439: }
                   7440: 
                   7441: # --------------------------------------------------------------- Verify a symb
                   7442: 
                   7443: sub symbverify {
1.510     www      7444:     my ($symb,$thisurl)=@_;
                   7445:     my $thisfn=$thisurl;
1.439     www      7446:     $thisfn=&declutter($thisfn);
1.215     www      7447: # direct jump to resource in page or to a sequence - will construct own symbs
                   7448:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7449: # check URL part
1.409     www      7450:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7451: 
1.431     www      7452:     unless ($url eq $thisfn) { return 0; }
1.213     www      7453: 
1.216     www      7454:     $symb=&symbclean($symb);
1.510     www      7455:     $thisurl=&deversion($thisurl);
1.439     www      7456:     $thisfn=&deversion($thisfn);
1.213     www      7457: 
                   7458:     my %bighash;
                   7459:     my $okay=0;
1.431     www      7460: 
1.620     albertel 7461:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7462:                             &GDBM_READER(),0640)) {
1.510     www      7463:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7464:         unless ($ids) { 
1.510     www      7465:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7466:         }
                   7467:         if ($ids) {
                   7468: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7469: 	    foreach my $id (split(/\,/,$ids)) {
                   7470: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7471:                if (
                   7472:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7473:    eq $symb) { 
1.620     albertel 7474: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7475: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7476: 		       $okay=1; 
                   7477: 		   }
                   7478: 	       }
1.216     www      7479: 	   }
                   7480:         }
1.213     www      7481: 	untie(%bighash);
                   7482:     }
                   7483:     return $okay;
1.31      www      7484: }
                   7485: 
1.210     www      7486: # --------------------------------------------------------------- Clean-up symb
                   7487: 
                   7488: sub symbclean {
                   7489:     my $symb=shift;
1.568     albertel 7490:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7491: # remove version from map
                   7492:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7493: 
1.210     www      7494: # remove version from URL
                   7495:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7496: 
1.507     www      7497: # remove wrapper
                   7498: 
1.510     www      7499:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7500:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7501:     return $symb;
1.409     www      7502: }
                   7503: 
                   7504: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7505: 
                   7506: sub encode_symb {
                   7507:     my ($map,$resid,$url)=@_;
                   7508:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7509: }
1.409     www      7510: 
                   7511: sub decode_symb {
1.568     albertel 7512:     my $symb=shift;
                   7513:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7514:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7515:     return (&fixversion($map),$resid,&fixversion($url));
                   7516: }
                   7517: 
                   7518: sub fixversion {
                   7519:     my $fn=shift;
1.609     banghart 7520:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7521:     my %bighash;
                   7522:     my $uri=&clutter($fn);
1.620     albertel 7523:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7524: # is this cached?
1.599     albertel 7525:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7526:     if (defined($cached)) { return $result; }
                   7527: # unfortunately not cached, or expired
1.620     albertel 7528:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7529: 	    &GDBM_READER(),0640)) {
                   7530:  	if ($bighash{'version_'.$uri}) {
                   7531:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7532:  	    unless (($version eq 'mostrecent') || 
                   7533: 		    ($version==&getversion($uri))) {
1.440     www      7534:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7535:  	    }
                   7536:  	}
                   7537:  	untie %bighash;
1.413     www      7538:     }
1.599     albertel 7539:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7540: }
                   7541: 
                   7542: sub deversion {
                   7543:     my $url=shift;
                   7544:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7545:     return $url;
1.210     www      7546: }
                   7547: 
1.31      www      7548: # ------------------------------------------------------ Return symb list entry
                   7549: 
                   7550: sub symbread {
1.249     www      7551:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7552:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7553:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7554: # no filename provided? try from environment
1.44      www      7555:     unless ($thisfn) {
1.620     albertel 7556:         if ($env{'request.symb'}) {
                   7557: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7558: 	}
1.620     albertel 7559: 	$thisfn=$env{'request.filename'};
1.44      www      7560:     }
1.569     albertel 7561:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7562: # is that filename actually a symb? Verify, clean, and return
                   7563:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7564: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7565: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7566: 	}
1.242     www      7567:     }
1.44      www      7568:     $thisfn=declutter($thisfn);
1.31      www      7569:     my %hash;
1.37      www      7570:     my %bighash;
                   7571:     my $syval='';
1.620     albertel 7572:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7573:         my $targetfn = $thisfn;
1.609     banghart 7574:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7575:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7576:         }
1.687     albertel 7577: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7578: 	    $targetfn=$1;
                   7579: 	}
1.620     albertel 7580:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7581:                       &GDBM_READER(),0640)) {
1.481     raeburn  7582: 	    $syval=$hash{$targetfn};
1.37      www      7583:             untie(%hash);
                   7584:         }
                   7585: # ---------------------------------------------------------- There was an entry
                   7586:         if ($syval) {
1.601     albertel 7587: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7588: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7589: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7590: 		    #return $env{$cache_str}='';
1.601     albertel 7591: 		#}    
                   7592: 		#$syval.=$1;
                   7593: 	    #}
1.37      www      7594:         } else {
                   7595: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7596:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7597:                             &GDBM_READER(),0640)) {
1.37      www      7598: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7599:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7600:               unless ($ids) { 
                   7601:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7602:               }
                   7603:               unless ($ids) {
                   7604: # alias?
                   7605: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7606:               }
1.37      www      7607:               if ($ids) {
                   7608: # ------------------------------------------------------------------- Has ID(s)
                   7609:                  my @possibilities=split(/\,/,$ids);
1.39      www      7610:                  if ($#possibilities==0) {
                   7611: # ----------------------------------------------- There is only one possibility
1.37      www      7612: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7613: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7614: 						    $resid,$thisfn);
1.249     www      7615:                  } elsif (!$donotrecurse) {
1.39      www      7616: # ------------------------------------------ There is more than one possibility
                   7617:                      my $realpossible=0;
1.800     albertel 7618:                      foreach my $id (@possibilities) {
                   7619: 			 my $file=$bighash{'src_'.$id};
1.39      www      7620:                          if (&allowed('bre',$file)) {
1.800     albertel 7621:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7622:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7623: 				$realpossible++;
1.626     albertel 7624:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7625: 						    $resid,$thisfn);
1.39      www      7626:                             }
                   7627: 			 }
1.191     harris41 7628:                      }
1.39      www      7629: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7630:                  } else {
                   7631:                      $syval='';
1.37      www      7632:                  }
                   7633: 	      }
                   7634:               untie(%bighash)
1.481     raeburn  7635:            }
1.31      www      7636:         }
1.62      www      7637:         if ($syval) {
1.620     albertel 7638: 	    return $env{$cache_str}=$syval;
1.62      www      7639:         }
1.31      www      7640:     }
1.949     raeburn  7641:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7642:     return $env{$cache_str}='';
1.31      www      7643: }
                   7644: 
                   7645: # ---------------------------------------------------------- Return random seed
                   7646: 
1.32      www      7647: sub numval {
                   7648:     my $txt=shift;
                   7649:     $txt=~tr/A-J/0-9/;
                   7650:     $txt=~tr/a-j/0-9/;
                   7651:     $txt=~tr/K-T/0-9/;
                   7652:     $txt=~tr/k-t/0-9/;
                   7653:     $txt=~tr/U-Z/0-5/;
                   7654:     $txt=~tr/u-z/0-5/;
                   7655:     $txt=~s/\D//g;
1.564     albertel 7656:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7657:     return int($txt);
1.368     albertel 7658: }
                   7659: 
1.484     albertel 7660: sub numval2 {
                   7661:     my $txt=shift;
                   7662:     $txt=~tr/A-J/0-9/;
                   7663:     $txt=~tr/a-j/0-9/;
                   7664:     $txt=~tr/K-T/0-9/;
                   7665:     $txt=~tr/k-t/0-9/;
                   7666:     $txt=~tr/U-Z/0-5/;
                   7667:     $txt=~tr/u-z/0-5/;
                   7668:     $txt=~s/\D//g;
                   7669:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7670:     my $total;
                   7671:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7672:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7673:     return int($total);
                   7674: }
                   7675: 
1.575     albertel 7676: sub numval3 {
                   7677:     use integer;
                   7678:     my $txt=shift;
                   7679:     $txt=~tr/A-J/0-9/;
                   7680:     $txt=~tr/a-j/0-9/;
                   7681:     $txt=~tr/K-T/0-9/;
                   7682:     $txt=~tr/k-t/0-9/;
                   7683:     $txt=~tr/U-Z/0-5/;
                   7684:     $txt=~tr/u-z/0-5/;
                   7685:     $txt=~s/\D//g;
                   7686:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7687:     my $total;
                   7688:     foreach my $val (@txts) { $total+=$val; }
                   7689:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7690:     return $total;
                   7691: }
                   7692: 
1.675     albertel 7693: sub digest {
                   7694:     my ($data)=@_;
                   7695:     my $digest=&Digest::MD5::md5($data);
                   7696:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7697:     my ($e,$f);
                   7698:     {
                   7699:         use integer;
                   7700:         $e=($a+$b);
                   7701:         $f=($c+$d);
                   7702:         if ($_64bit) {
                   7703:             $e=(($e<<32)>>32);
                   7704:             $f=(($f<<32)>>32);
                   7705:         }
                   7706:     }
                   7707:     if (wantarray) {
                   7708: 	return ($e,$f);
                   7709:     } else {
                   7710: 	my $g;
                   7711: 	{
                   7712: 	    use integer;
                   7713: 	    $g=($e+$f);
                   7714: 	    if ($_64bit) {
                   7715: 		$g=(($g<<32)>>32);
                   7716: 	    }
                   7717: 	}
                   7718: 	return $g;
                   7719:     }
                   7720: }
                   7721: 
1.368     albertel 7722: sub latest_rnd_algorithm_id {
1.675     albertel 7723:     return '64bit5';
1.366     albertel 7724: }
1.32      www      7725: 
1.503     albertel 7726: sub get_rand_alg {
                   7727:     my ($courseid)=@_;
1.790     albertel 7728:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7729:     if ($courseid) {
1.620     albertel 7730: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7731:     }
                   7732:     return &latest_rnd_algorithm_id();
                   7733: }
                   7734: 
1.562     albertel 7735: sub validCODE {
                   7736:     my ($CODE)=@_;
                   7737:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7738:     return 0;
                   7739: }
                   7740: 
1.491     albertel 7741: sub getCODE {
1.620     albertel 7742:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7743:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7744: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7745: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7746: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7747:     }
                   7748:     return undef;
                   7749: }
                   7750: 
1.31      www      7751: sub rndseed {
1.155     albertel 7752:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7753:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7754:     if (!defined($symb)) {
1.366     albertel 7755: 	unless ($symb=$wsymb) { return time; }
                   7756:     }
                   7757:     if (!$courseid) { $courseid=$wcourseid; }
                   7758:     if (!$domain) { $domain=$wdomain; }
                   7759:     if (!$username) { $username=$wusername }
1.503     albertel 7760:     my $which=&get_rand_alg();
1.803     albertel 7761: 
1.491     albertel 7762:     if (defined(&getCODE())) {
1.675     albertel 7763: 	if ($which eq '64bit5') {
                   7764: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7765: 	} elsif ($which eq '64bit4') {
1.575     albertel 7766: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7767: 	} else {
                   7768: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7769: 	}
1.675     albertel 7770:     } elsif ($which eq '64bit5') {
                   7771: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7772:     } elsif ($which eq '64bit4') {
                   7773: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7774:     } elsif ($which eq '64bit3') {
                   7775: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7776:     } elsif ($which eq '64bit2') {
                   7777: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7778:     } elsif ($which eq '64bit') {
                   7779: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7780:     }
                   7781:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7782: }
                   7783: 
                   7784: sub rndseed_32bit {
                   7785:     my ($symb,$courseid,$domain,$username)=@_;
                   7786:     {
                   7787: 	use integer;
                   7788: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7789: 	my $symbseed=numval($symb) << 22;
                   7790: 	my $namechck=unpack("%32C*",$username) << 17;
                   7791: 	my $nameseed=numval($username) << 12;
                   7792: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7793: 	my $courseseed=unpack("%32C*",$courseid);
                   7794: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7795: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7796: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7797: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7798: 	return $num;
                   7799:     }
                   7800: }
                   7801: 
                   7802: sub rndseed_64bit {
                   7803:     my ($symb,$courseid,$domain,$username)=@_;
                   7804:     {
                   7805: 	use integer;
                   7806: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7807: 	my $symbseed=numval($symb) << 10;
                   7808: 	my $namechck=unpack("%32S*",$username);
                   7809: 	
                   7810: 	my $nameseed=numval($username) << 21;
                   7811: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7812: 	my $courseseed=unpack("%32S*",$courseid);
                   7813: 	
                   7814: 	my $num1=$symbchck+$symbseed+$namechck;
                   7815: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7816: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7817: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7818: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7819: 	return "$num1,$num2";
1.155     albertel 7820:     }
1.366     albertel 7821: }
                   7822: 
1.443     albertel 7823: sub rndseed_64bit2 {
                   7824:     my ($symb,$courseid,$domain,$username)=@_;
                   7825:     {
                   7826: 	use integer;
                   7827: 	# strings need to be an even # of cahracters long, it it is odd the
                   7828:         # last characters gets thrown away
                   7829: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7830: 	my $symbseed=numval($symb) << 10;
                   7831: 	my $namechck=unpack("%32S*",$username.' ');
                   7832: 	
                   7833: 	my $nameseed=numval($username) << 21;
1.501     albertel 7834: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7835: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7836: 	
                   7837: 	my $num1=$symbchck+$symbseed+$namechck;
                   7838: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7839: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7840: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7841: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7842: 	return "$num1,$num2";
                   7843:     }
                   7844: }
                   7845: 
                   7846: sub rndseed_64bit3 {
                   7847:     my ($symb,$courseid,$domain,$username)=@_;
                   7848:     {
                   7849: 	use integer;
                   7850: 	# strings need to be an even # of cahracters long, it it is odd the
                   7851:         # last characters gets thrown away
                   7852: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7853: 	my $symbseed=numval2($symb) << 10;
                   7854: 	my $namechck=unpack("%32S*",$username.' ');
                   7855: 	
                   7856: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7857: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7858: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7859: 	
                   7860: 	my $num1=$symbchck+$symbseed+$namechck;
                   7861: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7862: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7863: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7864: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7865: 	
1.503     albertel 7866: 	return "$num1:$num2";
1.443     albertel 7867:     }
                   7868: }
                   7869: 
1.575     albertel 7870: sub rndseed_64bit4 {
                   7871:     my ($symb,$courseid,$domain,$username)=@_;
                   7872:     {
                   7873: 	use integer;
                   7874: 	# strings need to be an even # of cahracters long, it it is odd the
                   7875:         # last characters gets thrown away
                   7876: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7877: 	my $symbseed=numval3($symb) << 10;
                   7878: 	my $namechck=unpack("%32S*",$username.' ');
                   7879: 	
                   7880: 	my $nameseed=numval3($username) << 21;
                   7881: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7882: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7883: 	
                   7884: 	my $num1=$symbchck+$symbseed+$namechck;
                   7885: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7886: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7887: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7888: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7889: 	
                   7890: 	return "$num1:$num2";
                   7891:     }
                   7892: }
                   7893: 
1.675     albertel 7894: sub rndseed_64bit5 {
                   7895:     my ($symb,$courseid,$domain,$username)=@_;
                   7896:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7897:     return "$num1:$num2";
                   7898: }
                   7899: 
1.366     albertel 7900: sub rndseed_CODE_64bit {
                   7901:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7902:     {
1.366     albertel 7903: 	use integer;
1.443     albertel 7904: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7905: 	my $symbseed=numval2($symb);
1.491     albertel 7906: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7907: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7908: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7909: 	my $num1=$symbseed+$CODEchck;
                   7910: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7911: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7912: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7913: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7914: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7915: 	return "$num1:$num2";
1.366     albertel 7916:     }
                   7917: }
                   7918: 
1.575     albertel 7919: sub rndseed_CODE_64bit4 {
                   7920:     my ($symb,$courseid,$domain,$username)=@_;
                   7921:     {
                   7922: 	use integer;
                   7923: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7924: 	my $symbseed=numval3($symb);
                   7925: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7926: 	my $CODEseed=numval3(&getCODE());
                   7927: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7928: 	my $num1=$symbseed+$CODEchck;
                   7929: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7930: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7931: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7932: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7933: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7934: 	return "$num1:$num2";
                   7935:     }
                   7936: }
                   7937: 
1.675     albertel 7938: sub rndseed_CODE_64bit5 {
                   7939:     my ($symb,$courseid,$domain,$username)=@_;
                   7940:     my $code = &getCODE();
                   7941:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7942:     return "$num1:$num2";
                   7943: }
                   7944: 
1.366     albertel 7945: sub setup_random_from_rndseed {
                   7946:     my ($rndseed)=@_;
1.503     albertel 7947:     if ($rndseed =~/([,:])/) {
                   7948: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7949: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7950:     } else {
                   7951: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7952:     }
1.36      albertel 7953: }
                   7954: 
1.474     albertel 7955: sub latest_receipt_algorithm_id {
1.835     albertel 7956:     return 'receipt3';
1.474     albertel 7957: }
                   7958: 
1.480     www      7959: sub recunique {
                   7960:     my $fucourseid=shift;
                   7961:     my $unique;
1.835     albertel 7962:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7963: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7964: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7965:     } else {
                   7966: 	$unique=$perlvar{'lonReceipt'};
                   7967:     }
                   7968:     return unpack("%32C*",$unique);
                   7969: }
                   7970: 
                   7971: sub recprefix {
                   7972:     my $fucourseid=shift;
                   7973:     my $prefix;
1.835     albertel 7974:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7975: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7976: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7977:     } else {
                   7978: 	$prefix=$perlvar{'lonHostID'};
                   7979:     }
                   7980:     return unpack("%32C*",$prefix);
                   7981: }
                   7982: 
1.76      www      7983: sub ireceipt {
1.474     albertel 7984:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7985: 
                   7986:     my $return =&recprefix($fucourseid).'-';
                   7987: 
                   7988:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7989: 	$env{'request.state'} eq 'construct') {
                   7990: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7991: 	return $return;
                   7992:     }
                   7993: 
1.76      www      7994:     my $cuname=unpack("%32C*",$funame);
                   7995:     my $cudom=unpack("%32C*",$fudom);
                   7996:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7997:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7998:     my $cunique=&recunique($fucourseid);
1.474     albertel 7999:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8000:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8001: 
1.790     albertel 8002: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8003: 			       
                   8004: 	$return.= ($cunique%$cuname+
                   8005: 		   $cunique%$cudom+
                   8006: 		   $cusymb%$cuname+
                   8007: 		   $cusymb%$cudom+
                   8008: 		   $cucourseid%$cuname+
                   8009: 		   $cucourseid%$cudom+
                   8010: 		   $cpart%$cuname+
                   8011: 		   $cpart%$cudom);
                   8012:     } else {
                   8013: 	$return.= ($cunique%$cuname+
                   8014: 		   $cunique%$cudom+
                   8015: 		   $cusymb%$cuname+
                   8016: 		   $cusymb%$cudom+
                   8017: 		   $cucourseid%$cuname+
                   8018: 		   $cucourseid%$cudom);
                   8019:     }
                   8020:     return $return;
1.76      www      8021: }
                   8022: 
                   8023: sub receipt {
1.474     albertel 8024:     my ($part)=@_;
1.790     albertel 8025:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8026:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8027: }
1.260     ng       8028: 
1.790     albertel 8029: sub whichuser {
                   8030:     my ($passedsymb)=@_;
                   8031:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8032:     if (defined($env{'form.grade_symb'})) {
                   8033: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8034: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8035: 	if (!$allowed &&
                   8036: 	    exists($env{'request.course.sec'}) &&
                   8037: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8038: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8039: 			      '/'.$env{'request.course.sec'});
                   8040: 	}
                   8041: 	if ($allowed) {
                   8042: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8043: 	    $courseid=$tmp_courseid;
                   8044: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8045: 	    ($name)=&get_env_multiple('form.grade_username');
                   8046: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8047: 	}
                   8048:     }
                   8049:     if (!$passedsymb) {
                   8050: 	$symb=&symbread();
                   8051:     } else {
                   8052: 	$symb=$passedsymb;
                   8053:     }
                   8054:     $courseid=$env{'request.course.id'};
                   8055:     $domain=$env{'user.domain'};
                   8056:     $name=$env{'user.name'};
                   8057:     if ($name eq 'public' && $domain eq 'public') {
                   8058: 	if (!defined($env{'form.username'})) {
                   8059: 	    $env{'form.username'}.=time.rand(10000000);
                   8060: 	}
                   8061: 	$name.=$env{'form.username'};
                   8062:     }
                   8063:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8064: 
                   8065: }
                   8066: 
1.36      albertel 8067: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8068: # returns either the contents of the file or 
                   8069: # -1 if the file doesn't exist
1.481     raeburn  8070: #
                   8071: # if the target is a file that was uploaded via DOCS, 
                   8072: # a check will be made to see if a current copy exists on the local server,
                   8073: # if it does this will be served, otherwise a copy will be retrieved from
                   8074: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8075: # the local server.   
1.472     albertel 8076: 
1.36      albertel 8077: sub getfile {
1.538     albertel 8078:     my ($file) = @_;
1.609     banghart 8079:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8080:     &repcopy($file);
                   8081:     return &readfile($file);
                   8082: }
                   8083: 
                   8084: sub repcopy_userfile {
                   8085:     my ($file)=@_;
1.609     banghart 8086:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8087:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8088:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8089: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8090:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8091:     if (-e "$file") {
1.828     www      8092: # we already have a local copy, check it out
1.538     albertel 8093: 	my @fileinfo = stat($file);
1.828     www      8094: 	my $rtncode;
                   8095: 	my $info;
1.538     albertel 8096: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8097: 	if ($lwpresp ne 'ok') {
1.828     www      8098: # there is no such file anymore, even though we had a local copy
1.482     albertel 8099: 	    if ($rtncode eq '404') {
1.538     albertel 8100: 		unlink($file);
1.482     albertel 8101: 	    }
                   8102: 	    return -1;
                   8103: 	}
                   8104: 	if ($info < $fileinfo[9]) {
1.828     www      8105: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8106: 	    return 'ok';
1.828     www      8107: 	} else {
                   8108: # the file is outdated, get rid of it
                   8109: 	    unlink($file);
1.482     albertel 8110: 	}
1.828     www      8111:     }
                   8112: # one way or the other, at this point, we don't have the file
                   8113: # construct the correct path for the file
                   8114:     my @parts = ($cdom,$cnum); 
                   8115:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8116: 	push @parts, split(/\//,$1);
                   8117:     }
                   8118:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8119:     foreach my $part (@parts) {
                   8120: 	$path .= '/'.$part;
                   8121: 	if (!-e $path) {
                   8122: 	    mkdir($path,0770);
1.482     albertel 8123: 	}
                   8124:     }
1.828     www      8125: # now the path exists for sure
                   8126: # get a user agent
                   8127:     my $ua=new LWP::UserAgent;
                   8128:     my $transferfile=$file.'.in.transfer';
                   8129: # FIXME: this should flock
                   8130:     if (-e $transferfile) { return 'ok'; }
                   8131:     my $request;
                   8132:     $uri=~s/^\///;
1.838     albertel 8133:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8134:     my $response=$ua->request($request,$transferfile);
                   8135: # did it work?
                   8136:     if ($response->is_error()) {
                   8137: 	unlink($transferfile);
                   8138: 	&logthis("Userfile repcopy failed for $uri");
                   8139: 	return -1;
                   8140:     }
                   8141: # worked, rename the transfer file
                   8142:     rename($transferfile,$file);
1.607     raeburn  8143:     return 'ok';
1.481     raeburn  8144: }
                   8145: 
1.517     albertel 8146: sub tokenwrapper {
                   8147:     my $uri=shift;
1.552     albertel 8148:     $uri=~s|^http\://([^/]+)||;
                   8149:     $uri=~s|^/||;
1.620     albertel 8150:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8151:     my $token=$1;
1.552     albertel 8152:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8153:     if ($udom && $uname && $file) {
                   8154: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8155:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8156:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8157:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8158:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8159:     } else {
                   8160:         return '/adm/notfound.html';
                   8161:     }
                   8162: }
                   8163: 
1.828     www      8164: # call with reqtype HEAD: get last modification time
                   8165: # call with reqtype GET: get the file contents
                   8166: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8167: #
1.481     raeburn  8168: sub getuploaded {
                   8169:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8170:     $uri=~s/^\///;
1.838     albertel 8171:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8172:     my $ua=new LWP::UserAgent;
                   8173:     my $request=new HTTP::Request($reqtype,$uri);
                   8174:     my $response=$ua->request($request);
                   8175:     $$rtncode = $response->code;
1.482     albertel 8176:     if (! $response->is_success()) {
                   8177: 	return 'failed';
                   8178:     }      
                   8179:     if ($reqtype eq 'HEAD') {
1.486     www      8180: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8181:     } elsif ($reqtype eq 'GET') {
                   8182: 	$$info = $response->content;
1.472     albertel 8183:     }
1.482     albertel 8184:     return 'ok';
1.36      albertel 8185: }
                   8186: 
1.481     raeburn  8187: sub readfile {
                   8188:     my $file = shift;
                   8189:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8190:     my $fh;
                   8191:     open($fh,"<$file");
                   8192:     my $a='';
1.800     albertel 8193:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8194:     return $a;
                   8195: }
                   8196: 
1.36      albertel 8197: sub filelocation {
1.590     banghart 8198:     my ($dir,$file) = @_;
                   8199:     my $location;
                   8200:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8201: 
                   8202:     if ($file =~ m-^/adm/-) {
                   8203: 	$file=~s-^/adm/wrapper/-/-;
                   8204: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8205:     }
1.882     albertel 8206: 
1.590     banghart 8207:     if ($file=~m:^/~:) { # is a contruction space reference
                   8208:         $location = $file;
                   8209:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8210:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8211: 	# is a correct contruction space reference
                   8212:         $location = $file;
1.956     raeburn  8213:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8214:         $location = $file;
1.609     banghart 8215:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8216:         my ($udom,$uname,$filename)=
1.811     albertel 8217:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8218:         my $home=&homeserver($uname,$udom);
                   8219:         my $is_me=0;
                   8220:         my @ids=&current_machine_ids();
                   8221:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8222:         if ($is_me) {
1.955     raeburn  8223:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8224:         } else {
                   8225:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8226:   	      $udom.'/'.$uname.'/'.$filename;
                   8227:         }
1.882     albertel 8228:     } elsif ($file =~ m-^/adm/-) {
                   8229: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8230:     } else {
                   8231:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8232:         $file=~s:^/res/:/:;
                   8233:         if ( !( $file =~ m:^/:) ) {
                   8234:             $location = $dir. '/'.$file;
                   8235:         } else {
                   8236:             $location = '/home/httpd/html/res'.$file;
                   8237:         }
1.59      albertel 8238:     }
1.590     banghart 8239:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8240:     while ($location=~m{/\.\./}) {
                   8241: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8242: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8243: 	} else {
                   8244: 	    $location=~ s{/\.\./}{/}g;
                   8245: 	}
                   8246:     } #remove dir/..
1.590     banghart 8247:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8248:     return $location;
1.46      www      8249: }
1.36      albertel 8250: 
1.46      www      8251: sub hreflocation {
                   8252:     my ($dir,$file)=@_;
1.460     albertel 8253:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8254: 	$file=filelocation($dir,$file);
1.700     albertel 8255:     } elsif ($file=~m-^/adm/-) {
                   8256: 	$file=~s-^/adm/wrapper/-/-;
                   8257: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8258:     }
                   8259:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8260: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8261:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8262: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8263:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8264: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8265: 	    -/uploaded/$1/$2/-x;
1.46      www      8266:     }
1.913     albertel 8267:     if ($file=~ m{^/userfiles/}) {
                   8268: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8269:     }
1.462     albertel 8270:     return $file;
1.465     albertel 8271: }
                   8272: 
                   8273: sub current_machine_domains {
1.853     albertel 8274:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8275: }
                   8276: 
                   8277: sub machine_domains {
                   8278:     my ($hostname) = @_;
1.465     albertel 8279:     my @domains;
1.838     albertel 8280:     my %hostname = &all_hostnames();
1.465     albertel 8281:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8282: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8283: 	if ($hostname eq $name) {
1.844     albertel 8284: 	    push(@domains,&host_domain($id));
1.465     albertel 8285: 	}
                   8286:     }
                   8287:     return @domains;
                   8288: }
                   8289: 
                   8290: sub current_machine_ids {
1.853     albertel 8291:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8292: }
                   8293: 
                   8294: sub machine_ids {
                   8295:     my ($hostname) = @_;
                   8296:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8297:     my @ids;
1.888     albertel 8298:     my %name_to_host = &all_names();
1.889     albertel 8299:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8300: 	return @{ $name_to_host{$hostname} };
                   8301:     }
                   8302:     return;
1.31      www      8303: }
                   8304: 
1.824     raeburn  8305: sub additional_machine_domains {
                   8306:     my @domains;
                   8307:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8308:     while( my $line = <$fh>) {
                   8309:         $line =~ s/\s//g;
                   8310:         push(@domains,$line);
                   8311:     }
                   8312:     return @domains;
                   8313: }
                   8314: 
                   8315: sub default_login_domain {
                   8316:     my $domain = $perlvar{'lonDefDomain'};
                   8317:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8318:     foreach my $posdom (&current_machine_domains(),
                   8319:                         &additional_machine_domains()) {
                   8320:         if (lc($posdom) eq lc($testdomain)) {
                   8321:             $domain=$posdom;
                   8322:             last;
                   8323:         }
                   8324:     }
                   8325:     return $domain;
                   8326: }
                   8327: 
1.31      www      8328: # ------------------------------------------------------------- Declutters URLs
                   8329: 
                   8330: sub declutter {
                   8331:     my $thisfn=shift;
1.569     albertel 8332:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8333:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8334:     $thisfn=~s/^\///;
1.697     albertel 8335:     $thisfn=~s|^adm/wrapper/||;
                   8336:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8337:     $thisfn=~s/^res\///;
1.235     www      8338:     $thisfn=~s/\?.+$//;
1.268     www      8339:     return $thisfn;
                   8340: }
                   8341: 
                   8342: # ------------------------------------------------------------- Clutter up URLs
                   8343: 
                   8344: sub clutter {
                   8345:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8346:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8347: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8348:        $thisfn='/res'.$thisfn; 
                   8349:     }
1.694     albertel 8350:     if ($thisfn !~m|/adm|) {
1.695     albertel 8351: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8352: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8353: 	} else {
                   8354: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8355: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8356: 	    if ($embstyle eq 'ssi'
                   8357: 		|| ($embstyle eq 'hdn')
                   8358: 		|| ($embstyle eq 'rat')
                   8359: 		|| ($embstyle eq 'prv')
                   8360: 		|| ($embstyle eq 'ign')) {
                   8361: 		#do nothing with these
                   8362: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8363: 		|| ($embstyle eq 'emb')
                   8364: 		|| ($embstyle eq 'wrp')) {
                   8365: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8366: 	    } elsif ($embstyle eq 'unk'
                   8367: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8368: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8369: 	    } else {
1.718     www      8370: #		&logthis("Got a blank emb style");
1.695     albertel 8371: 	    }
1.694     albertel 8372: 	}
                   8373:     }
1.31      www      8374:     return $thisfn;
1.12      www      8375: }
                   8376: 
1.787     albertel 8377: sub clutter_with_no_wrapper {
                   8378:     my $uri = &clutter(shift);
                   8379:     if ($uri =~ m-^/adm/-) {
                   8380: 	$uri =~ s-^/adm/wrapper/-/-;
                   8381: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8382:     }
                   8383:     return $uri;
                   8384: }
                   8385: 
1.557     albertel 8386: sub freeze_escape {
                   8387:     my ($value)=@_;
                   8388:     if (ref($value)) {
                   8389: 	$value=&nfreeze($value);
                   8390: 	return '__FROZEN__'.&escape($value);
                   8391:     }
                   8392:     return &escape($value);
                   8393: }
                   8394: 
1.11      www      8395: 
1.557     albertel 8396: sub thaw_unescape {
                   8397:     my ($value)=@_;
                   8398:     if ($value =~ /^__FROZEN__/) {
                   8399: 	substr($value,0,10,undef);
                   8400: 	$value=&unescape($value);
                   8401: 	return &thaw($value);
                   8402:     }
                   8403:     return &unescape($value);
                   8404: }
                   8405: 
1.436     albertel 8406: sub correct_line_ends {
                   8407:     my ($result)=@_;
                   8408:     $$result =~s/\r\n/\n/mg;
                   8409:     $$result =~s/\r/\n/mg;
1.415     albertel 8410: }
1.1       albertel 8411: # ================================================================ Main Program
                   8412: 
1.184     www      8413: sub goodbye {
1.204     albertel 8414:    &logthis("Starting Shut down");
1.443     albertel 8415: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8416:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8417: #converted
1.599     albertel 8418: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8419:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8420: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8421: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8422: #1.1 only
1.870     albertel 8423: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8424: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8425: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8426: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8427:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8428:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8429:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8430:    &flushcourselogs();
                   8431:    &logthis("Shutting down");
                   8432: }
                   8433: 
1.852     albertel 8434: sub get_dns {
1.869     albertel 8435:     my ($url,$func,$ignore_cache) = @_;
                   8436:     if (!$ignore_cache) {
                   8437: 	my ($content,$cached)=
                   8438: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8439: 	if ($cached) {
                   8440: 	    &$func($content);
                   8441: 	    return;
                   8442: 	}
                   8443:     }
                   8444: 
                   8445:     my %alldns;
1.852     albertel 8446:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8447:     foreach my $dns (<$config>) {
                   8448: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8449: 	$alldns{$1} = 1;
                   8450:     }
                   8451:     while (%alldns) {
                   8452: 	my ($dns) = keys(%alldns);
                   8453: 	delete($alldns{$dns});
1.852     albertel 8454: 	my $ua=new LWP::UserAgent;
                   8455: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8456: 	my $response=$ua->request($request);
                   8457: 	next if ($response->is_error());
                   8458: 	my @content = split("\n",$response->content);
1.869     albertel 8459: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8460: 	&$func(\@content);
1.869     albertel 8461: 	return;
1.852     albertel 8462:     }
                   8463:     close($config);
1.871     albertel 8464:     my $which = (split('/',$url))[3];
                   8465:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8466:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8467:     my @content = <$config>;
                   8468:     &$func(\@content);
                   8469:     return;
1.852     albertel 8470: }
1.327     albertel 8471: # ------------------------------------------------------------ Read domain file
                   8472: {
1.852     albertel 8473:     my $loaded;
1.846     albertel 8474:     my %domain;
                   8475: 
1.852     albertel 8476:     sub parse_domain_tab {
                   8477: 	my ($lines) = @_;
                   8478: 	foreach my $line (@$lines) {
                   8479: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8480: 
1.846     albertel 8481: 	    chomp($line);
1.852     albertel 8482: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8483: 	    my %this_domain;
                   8484: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8485: 			       'lang_def', 'city', 'longi', 'lati',
                   8486: 			       'primary') {
                   8487: 		$this_domain{$field} = shift(@elements);
                   8488: 	    }
                   8489: 	    $domain{$name} = \%this_domain;
1.852     albertel 8490: 	}
                   8491:     }
1.864     albertel 8492: 
                   8493:     sub reset_domain_info {
                   8494: 	undef($loaded);
                   8495: 	undef(%domain);
                   8496:     }
                   8497: 
1.852     albertel 8498:     sub load_domain_tab {
1.869     albertel 8499: 	my ($ignore_cache) = @_;
                   8500: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8501: 	my $fh;
                   8502: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8503: 	    my @lines = <$fh>;
                   8504: 	    &parse_domain_tab(\@lines);
1.448     albertel 8505: 	}
1.852     albertel 8506: 	close($fh);
                   8507: 	$loaded = 1;
1.327     albertel 8508:     }
1.846     albertel 8509: 
                   8510:     sub domain {
1.852     albertel 8511: 	&load_domain_tab() if (!$loaded);
                   8512: 
1.846     albertel 8513: 	my ($name,$what) = @_;
                   8514: 	return if ( !exists($domain{$name}) );
                   8515: 
                   8516: 	if (!$what) {
                   8517: 	    return $domain{$name}{'description'};
                   8518: 	}
                   8519: 	return $domain{$name}{$what};
                   8520:     }
1.327     albertel 8521: }
                   8522: 
                   8523: 
1.1       albertel 8524: # ------------------------------------------------------------- Read hosts file
                   8525: {
1.838     albertel 8526:     my %hostname;
1.844     albertel 8527:     my %hostdom;
1.845     albertel 8528:     my %libserv;
1.852     albertel 8529:     my $loaded;
1.888     albertel 8530:     my %name_to_host;
1.852     albertel 8531: 
                   8532:     sub parse_hosts_tab {
                   8533: 	my ($file) = @_;
                   8534: 	foreach my $configline (@$file) {
                   8535: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8536: 	    next if ($configline =~ /^\^/);
                   8537: 	    chomp($configline);
                   8538: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8539: 	    $name=~s/\s//g;
                   8540: 	    if ($id && $domain && $role && $name) {
                   8541: 		$hostname{$id}=$name;
1.888     albertel 8542: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8543: 		$hostdom{$id}=$domain;
                   8544: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8545: 	    }
                   8546: 	}
                   8547:     }
1.864     albertel 8548:     
                   8549:     sub reset_hosts_info {
1.897     albertel 8550: 	&purge_remembered();
1.864     albertel 8551: 	&reset_domain_info();
                   8552: 	&reset_hosts_ip_info();
1.892     albertel 8553: 	undef(%name_to_host);
1.864     albertel 8554: 	undef(%hostname);
                   8555: 	undef(%hostdom);
                   8556: 	undef(%libserv);
                   8557: 	undef($loaded);
                   8558:     }
1.1       albertel 8559: 
1.852     albertel 8560:     sub load_hosts_tab {
1.869     albertel 8561: 	my ($ignore_cache) = @_;
                   8562: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8563: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8564: 	my @config = <$config>;
                   8565: 	&parse_hosts_tab(\@config);
                   8566: 	close($config);
                   8567: 	$loaded=1;
1.1       albertel 8568:     }
1.852     albertel 8569: 
1.838     albertel 8570:     sub hostname {
1.852     albertel 8571: 	&load_hosts_tab() if (!$loaded);
                   8572: 
1.838     albertel 8573: 	my ($lonid) = @_;
                   8574: 	return $hostname{$lonid};
                   8575:     }
1.845     albertel 8576: 
1.838     albertel 8577:     sub all_hostnames {
1.852     albertel 8578: 	&load_hosts_tab() if (!$loaded);
                   8579: 
1.838     albertel 8580: 	return %hostname;
                   8581:     }
1.845     albertel 8582: 
1.888     albertel 8583:     sub all_names {
                   8584: 	&load_hosts_tab() if (!$loaded);
                   8585: 
                   8586: 	return %name_to_host;
                   8587:     }
                   8588: 
1.845     albertel 8589:     sub is_library {
1.852     albertel 8590: 	&load_hosts_tab() if (!$loaded);
                   8591: 
1.845     albertel 8592: 	return exists($libserv{$_[0]});
                   8593:     }
                   8594: 
                   8595:     sub all_library {
1.852     albertel 8596: 	&load_hosts_tab() if (!$loaded);
                   8597: 
1.845     albertel 8598: 	return %libserv;
                   8599:     }
                   8600: 
1.841     albertel 8601:     sub get_servers {
1.852     albertel 8602: 	&load_hosts_tab() if (!$loaded);
                   8603: 
1.841     albertel 8604: 	my ($domain,$type) = @_;
                   8605: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8606: 	                                          : %hostname;
                   8607: 	my %result;
1.842     albertel 8608: 	if (ref($domain) eq 'ARRAY') {
                   8609: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8610: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8611: 		    $result{$host} = $hostname;
                   8612: 		}
                   8613: 	    }
                   8614: 	} else {
                   8615: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8616: 		if ($hostdom{$host} eq $domain) {
                   8617: 		    $result{$host} = $hostname;
                   8618: 		}
1.841     albertel 8619: 	    }
                   8620: 	}
                   8621: 	return %result;
                   8622:     }
1.845     albertel 8623: 
1.844     albertel 8624:     sub host_domain {
1.852     albertel 8625: 	&load_hosts_tab() if (!$loaded);
                   8626: 
1.844     albertel 8627: 	my ($lonid) = @_;
                   8628: 	return $hostdom{$lonid};
                   8629:     }
                   8630: 
1.841     albertel 8631:     sub all_domains {
1.852     albertel 8632: 	&load_hosts_tab() if (!$loaded);
                   8633: 
1.841     albertel 8634: 	my %seen;
                   8635: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8636: 	return @uniq;
                   8637:     }
1.1       albertel 8638: }
                   8639: 
1.847     albertel 8640: { 
                   8641:     my %iphost;
1.856     albertel 8642:     my %name_to_ip;
                   8643:     my %lonid_to_ip;
1.869     albertel 8644: 
1.847     albertel 8645:     sub get_hosts_from_ip {
                   8646: 	my ($ip) = @_;
                   8647: 	my %iphosts = &get_iphost();
                   8648: 	if (ref($iphosts{$ip})) {
                   8649: 	    return @{$iphosts{$ip}};
                   8650: 	}
                   8651: 	return;
1.839     albertel 8652:     }
1.864     albertel 8653:     
                   8654:     sub reset_hosts_ip_info {
                   8655: 	undef(%iphost);
                   8656: 	undef(%name_to_ip);
                   8657: 	undef(%lonid_to_ip);
                   8658:     }
1.856     albertel 8659: 
                   8660:     sub get_host_ip {
                   8661: 	my ($lonid) = @_;
                   8662: 	if (exists($lonid_to_ip{$lonid})) {
                   8663: 	    return $lonid_to_ip{$lonid};
                   8664: 	}
                   8665: 	my $name=&hostname($lonid);
                   8666:    	my $ip = gethostbyname($name);
                   8667: 	return if (!$ip || length($ip) ne 4);
                   8668: 	$ip=inet_ntoa($ip);
                   8669: 	$name_to_ip{$name}   = $ip;
                   8670: 	$lonid_to_ip{$lonid} = $ip;
                   8671: 	return $ip;
                   8672:     }
1.847     albertel 8673:     
                   8674:     sub get_iphost {
1.869     albertel 8675: 	my ($ignore_cache) = @_;
1.894     albertel 8676: 
1.869     albertel 8677: 	if (!$ignore_cache) {
                   8678: 	    if (%iphost) {
                   8679: 		return %iphost;
                   8680: 	    }
                   8681: 	    my ($ip_info,$cached)=
                   8682: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8683: 	    if ($cached) {
                   8684: 		%iphost      = %{$ip_info->[0]};
                   8685: 		%name_to_ip  = %{$ip_info->[1]};
                   8686: 		%lonid_to_ip = %{$ip_info->[2]};
                   8687: 		return %iphost;
                   8688: 	    }
                   8689: 	}
1.894     albertel 8690: 
                   8691: 	# get yesterday's info for fallback
                   8692: 	my %old_name_to_ip;
                   8693: 	my ($ip_info,$cached)=
                   8694: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8695: 	if ($cached) {
                   8696: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8697: 	}
                   8698: 
1.888     albertel 8699: 	my %name_to_host = &all_names();
                   8700: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8701: 	    my $ip;
                   8702: 	    if (!exists($name_to_ip{$name})) {
                   8703: 		$ip = gethostbyname($name);
                   8704: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8705: 		    if (defined($old_name_to_ip{$name})) {
                   8706: 			$ip = $old_name_to_ip{$name};
                   8707: 			&logthis("Can't find $name defaulting to old $ip");
                   8708: 		    } else {
                   8709: 			&logthis("Name $name no IP found");
                   8710: 			next;
                   8711: 		    }
                   8712: 		} else {
                   8713: 		    $ip=inet_ntoa($ip);
1.847     albertel 8714: 		}
                   8715: 		$name_to_ip{$name} = $ip;
                   8716: 	    } else {
                   8717: 		$ip = $name_to_ip{$name};
1.653     albertel 8718: 	    }
1.888     albertel 8719: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8720: 		$lonid_to_ip{$id} = $ip;
                   8721: 	    }
                   8722: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8723: 	}
1.869     albertel 8724: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8725: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8726: 				      48*60*60);
1.869     albertel 8727: 
1.847     albertel 8728: 	return %iphost;
1.598     albertel 8729:     }
                   8730: }
                   8731: 
1.862     albertel 8732: BEGIN {
                   8733: 
                   8734: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8735:     unless ($readit) {
                   8736: {
                   8737:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8738:     %perlvar = (%perlvar,%{$configvars});
                   8739: }
                   8740: 
                   8741: 
1.1       albertel 8742: # ------------------------------------------------------ Read spare server file
                   8743: {
1.448     albertel 8744:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8745: 
                   8746:     while (my $configline=<$config>) {
                   8747:        chomp($configline);
1.284     matthew  8748:        if ($configline) {
1.784     albertel 8749: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8750: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8751: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8752:        }
                   8753:     }
1.448     albertel 8754:     close($config);
1.1       albertel 8755: }
1.11      www      8756: # ------------------------------------------------------------ Read permissions
                   8757: {
1.448     albertel 8758:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8759: 
                   8760:     while (my $configline=<$config>) {
1.448     albertel 8761: 	chomp($configline);
                   8762: 	if ($configline) {
                   8763: 	    my ($role,$perm)=split(/ /,$configline);
                   8764: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8765: 	}
1.11      www      8766:     }
1.448     albertel 8767:     close($config);
1.11      www      8768: }
                   8769: 
                   8770: # -------------------------------------------- Read plain texts for permissions
                   8771: {
1.448     albertel 8772:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8773: 
                   8774:     while (my $configline=<$config>) {
1.448     albertel 8775: 	chomp($configline);
                   8776: 	if ($configline) {
1.742     raeburn  8777: 	    my ($short,@plain)=split(/:/,$configline);
                   8778:             %{$prp{$short}} = ();
                   8779: 	    if (@plain > 0) {
                   8780:                 $prp{$short}{'std'} = $plain[0];
                   8781:                 for (my $i=1; $i<@plain; $i++) {
                   8782:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8783:                 }
                   8784:             }
1.448     albertel 8785: 	}
1.135     www      8786:     }
1.448     albertel 8787:     close($config);
1.135     www      8788: }
                   8789: 
                   8790: # ---------------------------------------------------------- Read package table
                   8791: {
1.448     albertel 8792:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8793: 
                   8794:     while (my $configline=<$config>) {
1.483     albertel 8795: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8796: 	chomp($configline);
                   8797: 	my ($short,$plain)=split(/:/,$configline);
                   8798: 	my ($pack,$name)=split(/\&/,$short);
                   8799: 	if ($plain ne '') {
                   8800: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8801: 	    $packagetab{$short}=$plain; 
                   8802: 	}
1.11      www      8803:     }
1.448     albertel 8804:     close($config);
1.329     matthew  8805: }
                   8806: 
                   8807: # ------------- set up temporary directory
                   8808: {
                   8809:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8810: 
1.11      www      8811: }
                   8812: 
1.794     albertel 8813: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8814: 				'compress_threshold'=> 20_000,
                   8815:  			        });
1.185     www      8816: 
1.281     www      8817: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8818: $dumpcount=0;
1.958     www      8819: $locknum=0;
1.22      www      8820: 
1.163     harris41 8821: &logtouch();
1.672     albertel 8822: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8823: $readit=1;
1.564     albertel 8824:     {
                   8825: 	use integer;
                   8826: 	my $test=(2**32)+1;
1.568     albertel 8827: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8828: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8829:     }
1.195     www      8830: }
1.1       albertel 8831: }
1.179     www      8832: 
1.1       albertel 8833: 1;
1.191     harris41 8834: __END__
                   8835: 
1.243     albertel 8836: =pod
                   8837: 
1.191     harris41 8838: =head1 NAME
                   8839: 
1.243     albertel 8840: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8841: 
                   8842: =head1 SYNOPSIS
                   8843: 
1.243     albertel 8844: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8845: 
                   8846:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8847: 
1.243     albertel 8848: Common parameters:
                   8849: 
                   8850: =over 4
                   8851: 
                   8852: =item *
                   8853: 
                   8854: $uname : an internal username (if $cname expecting a course Id specifically)
                   8855: 
                   8856: =item *
                   8857: 
                   8858: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8859: 
                   8860: =item *
                   8861: 
                   8862: $symb : a resource instance identifier
                   8863: 
                   8864: =item *
                   8865: 
                   8866: $namespace : the name of a .db file that contains the data needed or
                   8867: being set.
                   8868: 
                   8869: =back
                   8870: 
1.394     bowersj2 8871: =head1 OVERVIEW
1.191     harris41 8872: 
1.394     bowersj2 8873: lonnet provides subroutines which interact with the
                   8874: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8875: about classes, users, and resources.
1.243     albertel 8876: 
                   8877: For many of these objects you can also use this to store data about
                   8878: them or modify them in various ways.
1.191     harris41 8879: 
1.394     bowersj2 8880: =head2 Symbs
1.191     harris41 8881: 
1.394     bowersj2 8882: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8883: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8884: map, the resource number of the resource in the map, and the URL of
                   8885: the resource itself. The latter is somewhat redundant, but might help
                   8886: if maps change.
                   8887: 
                   8888: An example is
                   8889: 
                   8890:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8891: 
                   8892: The respective map entry is
                   8893: 
                   8894:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8895:   title="Problem 2">
                   8896:  </resource>
                   8897: 
                   8898: Symbs are used by the random number generator, as well as to store and
                   8899: restore data specific to a certain instance of for example a problem.
                   8900: 
                   8901: =head2 Storing And Retrieving Data
                   8902: 
                   8903: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8904: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8905: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8906: is is the non-critical message twin of cstore. These functions are for
                   8907: handlers to store a perl hash to a user's permanent data space in an
                   8908: easy manner, and to retrieve it again on another call. It is expected
                   8909: that a handler would use this once at the beginning to retrieve data,
                   8910: and then again once at the end to send only the new data back.
                   8911: 
                   8912: The data is stored in the user's data directory on the user's
                   8913: homeserver under the ID of the course.
                   8914: 
                   8915: The hash that is returned by restore will have all of the previous
                   8916: value for all of the elements of the hash.
                   8917: 
                   8918: Example:
                   8919: 
                   8920:  #creating a hash
                   8921:  my %hash;
                   8922:  $hash{'foo'}='bar';
                   8923: 
                   8924:  #storing it
                   8925:  &Apache::lonnet::cstore(\%hash);
                   8926: 
                   8927:  #changing a value
                   8928:  $hash{'foo'}='notbar';
                   8929: 
                   8930:  #adding a new value
                   8931:  $hash{'bar'}='foo';
                   8932:  &Apache::lonnet::cstore(\%hash);
                   8933: 
                   8934:  #retrieving the hash
                   8935:  my %history=&Apache::lonnet::restore();
                   8936: 
                   8937:  #print the hash
                   8938:  foreach my $key (sort(keys(%history))) {
                   8939:    print("\%history{$key} = $history{$key}");
                   8940:  }
                   8941: 
                   8942: Will print out:
1.191     harris41 8943: 
1.394     bowersj2 8944:  %history{1:foo} = bar
                   8945:  %history{1:keys} = foo:timestamp
                   8946:  %history{1:timestamp} = 990455579
                   8947:  %history{2:bar} = foo
                   8948:  %history{2:foo} = notbar
                   8949:  %history{2:keys} = foo:bar:timestamp
                   8950:  %history{2:timestamp} = 990455580
                   8951:  %history{bar} = foo
                   8952:  %history{foo} = notbar
                   8953:  %history{timestamp} = 990455580
                   8954:  %history{version} = 2
                   8955: 
                   8956: Note that the special hash entries C<keys>, C<version> and
                   8957: C<timestamp> were added to the hash. C<version> will be equal to the
                   8958: total number of versions of the data that have been stored. The
                   8959: C<timestamp> attribute will be the UNIX time the hash was
                   8960: stored. C<keys> is available in every historical section to list which
                   8961: keys were added or changed at a specific historical revision of a
                   8962: hash.
                   8963: 
                   8964: B<Warning>: do not store the hash that restore returns directly. This
                   8965: will cause a mess since it will restore the historical keys as if the
                   8966: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8967: 
1.394     bowersj2 8968: Calling convention:
1.191     harris41 8969: 
1.394     bowersj2 8970:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8971:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8972: 
1.394     bowersj2 8973: For more detailed information, see lonnet specific documentation.
1.191     harris41 8974: 
1.394     bowersj2 8975: =head1 RETURN MESSAGES
1.191     harris41 8976: 
1.394     bowersj2 8977: =over 4
1.191     harris41 8978: 
1.394     bowersj2 8979: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8980: 
1.394     bowersj2 8981: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8982: when the connection is brought back up
1.191     harris41 8983: 
1.394     bowersj2 8984: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8985: for later delivery
1.191     harris41 8986: 
1.394     bowersj2 8987: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8988: 
1.394     bowersj2 8989: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8990: that was requested
1.191     harris41 8991: 
1.243     albertel 8992: =back
1.191     harris41 8993: 
1.243     albertel 8994: =head1 PUBLIC SUBROUTINES
1.191     harris41 8995: 
1.243     albertel 8996: =head2 Session Environment Functions
1.191     harris41 8997: 
1.243     albertel 8998: =over 4
1.191     harris41 8999: 
1.394     bowersj2 9000: =item * 
                   9001: X<appenv()>
1.949     raeburn  9002: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9003: the user envirnoment file, and will be restored for each access this
1.620     albertel 9004: user makes during this session, also modifies the %env for the current
1.949     raeburn  9005: process. Optional rolesarrayref - if defined contains a reference to an array
                   9006: of roles which are exempt from the restriction on modifying user.role entries 
                   9007: in the user's environment.db and in %env.    
1.191     harris41 9008: 
                   9009: =item *
1.394     bowersj2 9010: X<delenv()>
                   9011: B<delenv($regexp)>: removes all items from the session
                   9012: environment file that matches the regular expression in $regexp. The
1.620     albertel 9013: values are also delted from the current processes %env.
1.191     harris41 9014: 
1.795     albertel 9015: =item * get_env_multiple($name) 
                   9016: 
                   9017: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9018: values may be defined and end up as an array ref.
                   9019: 
                   9020: returns an array of values
                   9021: 
1.243     albertel 9022: =back
                   9023: 
                   9024: =head2 User Information
1.191     harris41 9025: 
1.243     albertel 9026: =over 4
1.191     harris41 9027: 
                   9028: =item *
1.394     bowersj2 9029: X<queryauthenticate()>
                   9030: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9031: authentication scheme
                   9032: 
                   9033: =item *
1.394     bowersj2 9034: X<authenticate()>
                   9035: B<authenticate($uname,$upass,$udom)>: try to
                   9036: authenticate user from domain's lib servers (first use the current
                   9037: one). C<$upass> should be the users password.
1.191     harris41 9038: 
                   9039: =item *
1.394     bowersj2 9040: X<homeserver()>
                   9041: B<homeserver($uname,$udom)>: find the server which has
                   9042: the user's directory and files (there must be only one), this caches
                   9043: the answer, and also caches if there is a borken connection.
1.191     harris41 9044: 
                   9045: =item *
1.394     bowersj2 9046: X<idget()>
                   9047: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9048: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9049: username, and only 1 username per ID in a specific domain) (returns
                   9050: hash: id=>name,id=>name)
1.191     harris41 9051: 
                   9052: =item *
1.394     bowersj2 9053: X<idrget()>
                   9054: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9055: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9056: 
                   9057: =item *
1.394     bowersj2 9058: X<idput()>
                   9059: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9060: 
                   9061: =item *
1.394     bowersj2 9062: X<rolesinit()>
                   9063: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9064: 
                   9065: =item *
1.551     albertel 9066: X<getsection()>
                   9067: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9068: course $cname, return section name/number or '' for "not in course"
                   9069: and '-1' for "no section"
                   9070: 
                   9071: =item *
1.394     bowersj2 9072: X<userenvironment()>
                   9073: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9074: passed in @what from the requested user's environment, returns a hash
                   9075: 
1.858     raeburn  9076: =item * 
                   9077: X<userlog_query()>
1.859     albertel 9078: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9079: activity.log file. %filters defines filters applied when parsing the
                   9080: log file. These can be start or end timestamps, or the type of action
                   9081: - log to look for Login or Logout events, check for Checkin or
                   9082: Checkout, role for role selection. The response is in the form
                   9083: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9084: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9085: 
1.243     albertel 9086: =back
                   9087: 
                   9088: =head2 User Roles
                   9089: 
                   9090: =over 4
                   9091: 
                   9092: =item *
                   9093: 
1.810     raeburn  9094: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9095:  F: full access
                   9096:  U,I,K: authentication modes (cxx only)
                   9097:  '': forbidden
                   9098:  1: user needs to choose course
                   9099:  2: browse allowed
1.766     albertel 9100:  A: passphrase authentication needed
1.243     albertel 9101: 
                   9102: =item *
                   9103: 
                   9104: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9105: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9106: and course level
                   9107: 
                   9108: =item *
                   9109: 
                   9110: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9111: explanation of a user role term
                   9112: 
1.832     raeburn  9113: =item *
                   9114: 
1.935     raeburn  9115: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9116: All arguments are optional. Returns a hash of a roles, either for
                   9117: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9118: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9119: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9120: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9121: For each key, value is set to colon-separated start and end times for
                   9122: the role.  If no username and domain are specified, will default to
1.934     raeburn  9123: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9124: of role statuses (active, future or previous), roles 
                   9125: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9126: to restrict the list of roles reported. If no array ref is 
                   9127: provided for types, will default to return only active roles.
1.834     albertel 9128: 
1.243     albertel 9129: =back
                   9130: 
                   9131: =head2 User Modification
                   9132: 
                   9133: =over 4
                   9134: 
                   9135: =item *
                   9136: 
1.957     raeburn  9137: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9138: user for the level given by URL.  Optional start and end dates (leave empty
                   9139: string or zero for "no date")
1.191     harris41 9140: 
                   9141: =item *
                   9142: 
1.243     albertel 9143: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9144: change a users, password, possible return values are: ok,
                   9145: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9146: refused
1.191     harris41 9147: 
                   9148: =item *
                   9149: 
1.243     albertel 9150: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9151: 
                   9152: =item *
                   9153: 
1.963   ! raeburn  9154: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
        !          9155:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9156: modify user
1.191     harris41 9157: 
                   9158: =item *
                   9159: 
1.286     matthew  9160: modifystudent
                   9161: 
1.957     raeburn  9162: modify a student's enrollment and identification information.
1.286     matthew  9163: The course id is resolved based on the current users environment.  
                   9164: This means the envoking user must be a course coordinator or otherwise
                   9165: associated with a course.
                   9166: 
1.297     matthew  9167: This call is essentially a wrapper for lonnet::modifyuser and
                   9168: lonnet::modify_student_enrollment
1.286     matthew  9169: 
                   9170: Inputs: 
                   9171: 
                   9172: =over 4
                   9173: 
1.957     raeburn  9174: =item B<$udom> Student's loncapa domain
1.286     matthew  9175: 
1.957     raeburn  9176: =item B<$uname> Student's loncapa login name
1.286     matthew  9177: 
1.957     raeburn  9178: =item B<$uid> Student's id/student number
1.286     matthew  9179: 
1.957     raeburn  9180: =item B<$umode> Student's authentication mode
1.286     matthew  9181: 
1.957     raeburn  9182: =item B<$upass> Student's password
1.286     matthew  9183: 
1.957     raeburn  9184: =item B<$first> Student's first name
1.286     matthew  9185: 
1.957     raeburn  9186: =item B<$middle> Student's middle name
1.286     matthew  9187: 
1.957     raeburn  9188: =item B<$last> Student's last name
1.286     matthew  9189: 
1.957     raeburn  9190: =item B<$gene> Student's generation
1.286     matthew  9191: 
1.957     raeburn  9192: =item B<$usec> Student's section in course
1.286     matthew  9193: 
                   9194: =item B<$end> Unix time of the roles expiration
                   9195: 
                   9196: =item B<$start> Unix time of the roles start date
                   9197: 
                   9198: =item B<$forceid> If defined, allow $uid to be changed
                   9199: 
                   9200: =item B<$desiredhome> server to use as home server for student
                   9201: 
1.957     raeburn  9202: =item B<$email> Student's permanent e-mail address
                   9203: 
                   9204: =item B<$type> Type of enrollment (auto or manual)
                   9205: 
1.963   ! raeburn  9206: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
        !          9207: 
        !          9208: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9209: 
1.963   ! raeburn  9210: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9211: 
1.963   ! raeburn  9212: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9213: 
1.963   ! raeburn  9214: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9215: 
1.286     matthew  9216: =back
1.297     matthew  9217: 
                   9218: =item *
                   9219: 
                   9220: modify_student_enrollment
                   9221: 
                   9222: Change a students enrollment status in a class.  The environment variable
                   9223: 'role.request.course' must be defined for this function to proceed.
                   9224: 
                   9225: Inputs:
                   9226: 
                   9227: =over 4
                   9228: 
                   9229: =item $udom, students domain
                   9230: 
                   9231: =item $uname, students name
                   9232: 
                   9233: =item $uid, students user id
                   9234: 
                   9235: =item $first, students first name
                   9236: 
                   9237: =item $middle
                   9238: 
                   9239: =item $last
                   9240: 
                   9241: =item $gene
                   9242: 
                   9243: =item $usec
                   9244: 
                   9245: =item $end
                   9246: 
                   9247: =item $start
                   9248: 
1.957     raeburn  9249: =item $type
                   9250: 
                   9251: =item $locktype
                   9252: 
                   9253: =item $cid
                   9254: 
                   9255: =item $selfenroll
                   9256: 
                   9257: =item $context
                   9258: 
1.297     matthew  9259: =back
                   9260: 
1.191     harris41 9261: 
                   9262: =item *
                   9263: 
1.243     albertel 9264: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9265: custom role; give a custom role to a user for the level given by URL.  Specify
                   9266: name and domain of role author, and role name
1.191     harris41 9267: 
                   9268: =item *
                   9269: 
1.243     albertel 9270: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9271: 
                   9272: =item *
                   9273: 
1.243     albertel 9274: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9275: 
                   9276: =back
                   9277: 
                   9278: =head2 Course Infomation
                   9279: 
                   9280: =over 4
1.191     harris41 9281: 
                   9282: =item *
                   9283: 
1.631     albertel 9284: coursedescription($courseid) : returns a hash of information about the
                   9285: specified course id, including all environment settings for the
                   9286: course, the description of the course will be in the hash under the
                   9287: key 'description'
1.191     harris41 9288: 
                   9289: =item *
                   9290: 
1.624     albertel 9291: resdata($name,$domain,$type,@which) : request for current parameter
                   9292: setting for a specific $type, where $type is either 'course' or 'user',
                   9293: @what should be a list of parameters to ask about. This routine caches
                   9294: answers for 5 minutes.
1.243     albertel 9295: 
1.877     foxr     9296: =item *
                   9297: 
                   9298: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9299: data base, returning a hash that is keyed by the resource name and has
                   9300: values that are the resource value.  I believe that the timestamps and
                   9301: versions are also returned.
                   9302: 
                   9303: 
1.243     albertel 9304: =back
                   9305: 
                   9306: =head2 Course Modification
                   9307: 
                   9308: =over 4
1.191     harris41 9309: 
                   9310: =item *
                   9311: 
1.243     albertel 9312: writecoursepref($courseid,%prefs) : write preferences (environment
                   9313: database) for a course
1.191     harris41 9314: 
                   9315: =item *
                   9316: 
1.243     albertel 9317: createcourse($udom,$description,$url) : make/modify course
                   9318: 
                   9319: =back
                   9320: 
                   9321: =head2 Resource Subroutines
                   9322: 
                   9323: =over 4
1.191     harris41 9324: 
                   9325: =item *
                   9326: 
1.243     albertel 9327: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9328: 
                   9329: =item *
                   9330: 
1.243     albertel 9331: repcopy($filename) : subscribes to the requested file, and attempts to
                   9332: replicate from the owning library server, Might return
1.607     raeburn  9333: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9334: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9335: resource. Expects the local filesystem pathname
                   9336: (/home/httpd/html/res/....)
                   9337: 
                   9338: =back
                   9339: 
                   9340: =head2 Resource Information
                   9341: 
                   9342: =over 4
1.191     harris41 9343: 
                   9344: =item *
                   9345: 
1.243     albertel 9346: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9347: a vairety of different possible values, $varname should be a request
                   9348: string, and the other parameters can be used to specify who and what
                   9349: one is asking about.
                   9350: 
                   9351: Possible values for $varname are environment.lastname (or other item
                   9352: from the envirnment hash), user.name (or someother aspect about the
                   9353: user), resource.0.maxtries (or some other part and parameter of a
                   9354: resource)
1.204     albertel 9355: 
                   9356: =item *
                   9357: 
1.243     albertel 9358: directcondval($number) : get current value of a condition; reads from a state
                   9359: string
1.204     albertel 9360: 
                   9361: =item *
                   9362: 
1.243     albertel 9363: condval($condidx) : value of condition index based on state
1.204     albertel 9364: 
                   9365: =item *
                   9366: 
1.243     albertel 9367: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9368: resource's metadata, $what should be either a specific key, or either
                   9369: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9370: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9371: 
                   9372: this function automatically caches all requests
1.191     harris41 9373: 
                   9374: =item *
                   9375: 
1.243     albertel 9376: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9377: network of library servers; returns file handle of where SQL and regex results
                   9378: will be stored for query
1.191     harris41 9379: 
                   9380: =item *
                   9381: 
1.243     albertel 9382: symbread($filename) : return symbolic list entry (filename argument optional);
                   9383: returns the data handle
1.191     harris41 9384: 
                   9385: =item *
                   9386: 
1.243     albertel 9387: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9388: a possible symb for the URL in $thisfn, and if is an encryypted
                   9389: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9390: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9391: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9392: 
1.191     harris41 9393: 
                   9394: =item *
                   9395: 
1.243     albertel 9396: symbclean($symb) : removes versions numbers from a symb, returns the
                   9397: cleaned symb
1.191     harris41 9398: 
                   9399: =item *
                   9400: 
1.243     albertel 9401: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9402: course map, user must be in a course for it to work.
1.191     harris41 9403: 
                   9404: =item *
                   9405: 
1.243     albertel 9406: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9407: 
                   9408: =item *
                   9409: 
1.243     albertel 9410: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9411: a random seed, all arguments are optional, if they aren't sent it uses the
                   9412: environment to derive them. Note: if symb isn't sent and it can't get one
                   9413: from &symbread it will use the current time as its return value
1.191     harris41 9414: 
                   9415: =item *
                   9416: 
1.243     albertel 9417: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9418: unfakeable, receipt
1.191     harris41 9419: 
                   9420: =item *
                   9421: 
1.620     albertel 9422: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9423: 
                   9424: =item *
                   9425: 
1.243     albertel 9426: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9427: 
                   9428: =item *
                   9429: 
1.243     albertel 9430: 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 9431: 
                   9432: =item *
                   9433: 
1.243     albertel 9434: 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 9435: 
                   9436: =item *
                   9437: 
1.243     albertel 9438: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9439: 
                   9440: =item *
                   9441: 
1.243     albertel 9442: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9443: forcing spreadsheet to reevaluate the resource scores next time.
                   9444: 
                   9445: =back
                   9446: 
                   9447: =head2 Storing/Retreiving Data
                   9448: 
                   9449: =over 4
1.191     harris41 9450: 
                   9451: =item *
                   9452: 
1.243     albertel 9453: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9454: for this url; hashref needs to be given and should be a \%hashname; the
                   9455: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9456: be derived from the env
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9461: uses critical subroutine
1.191     harris41 9462: 
                   9463: =item *
                   9464: 
1.243     albertel 9465: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9466: all args are optional
1.191     harris41 9467: 
                   9468: =item *
                   9469: 
1.717     albertel 9470: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9471: dumps the complete (or key matching regexp) namespace into a hash
                   9472: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9473: normally &store()ed into
                   9474: 
                   9475: $range should be either an integer '100' (give me the first 100
                   9476:                                            matching records)
                   9477:               or be  two integers sperated by a - with no spaces
                   9478:                  '30-50' (give me the 30th through the 50th matching
                   9479:                           records)
                   9480: 
                   9481: 
                   9482: =item *
                   9483: 
                   9484: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9485: replaces a &store() version of data with a replacement set of data
                   9486: for a particular resource in a namespace passed in the $storehash hash 
                   9487: reference
                   9488: 
                   9489: =item *
                   9490: 
1.243     albertel 9491: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9492: works very similar to store/cstore, but all data is stored in a
                   9493: temporary location and can be reset using tmpreset, $storehash should
                   9494: be a hash reference, returns nothing on success
1.191     harris41 9495: 
                   9496: =item *
                   9497: 
1.243     albertel 9498: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9499: similar to restore, but all data is stored in a temporary location and
                   9500: can be reset using tmpreset. Returns a hash of values on success,
                   9501: error string otherwise.
1.191     harris41 9502: 
                   9503: =item *
                   9504: 
1.243     albertel 9505: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9506: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9507: 
                   9508: =item *
                   9509: 
1.243     albertel 9510: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9511: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9512: 
                   9513: =item *
                   9514: 
1.243     albertel 9515: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9516: namesp ($udom and $uname are optional)
1.191     harris41 9517: 
                   9518: =item *
                   9519: 
1.702     albertel 9520: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9521: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9522: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9523: 
1.702     albertel 9524: $range should be either an integer '100' (give me the first 100
                   9525:                                            matching records)
                   9526:               or be  two integers sperated by a - with no spaces
                   9527:                  '30-50' (give me the 30th through the 50th matching
                   9528:                           records)
1.449     matthew  9529: =item *
                   9530: 
                   9531: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9532: $store can be a scalar, an array reference, or if the amount to be 
                   9533: incremented is > 1, a hash reference.
                   9534: 
                   9535: ($udom and $uname are optional)
1.191     harris41 9536: 
                   9537: =item *
                   9538: 
1.243     albertel 9539: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9540: ($udom and $uname are optional)
1.191     harris41 9541: 
                   9542: =item *
                   9543: 
1.243     albertel 9544: cput($namespace,$storehash,$udom,$uname) : critical put
                   9545: ($udom and $uname are optional)
1.191     harris41 9546: 
                   9547: =item *
                   9548: 
1.748     albertel 9549: newput($namespace,$storehash,$udom,$uname) :
                   9550: 
                   9551: Attempts to store the items in the $storehash, but only if they don't
                   9552: currently exist, if this succeeds you can be certain that you have 
                   9553: successfully created a new key value pair in the $namespace db.
                   9554: 
                   9555: 
                   9556: Args:
                   9557:  $namespace: name of database to store values to
                   9558:  $storehash: hashref to store to the db
                   9559:  $udom: (optional) domain of user containing the db
                   9560:  $uname: (optional) name of user caontaining the db
                   9561: 
                   9562: Returns:
                   9563:  'ok' -> succeeded in storing all keys of $storehash
                   9564:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9565:                         least <key> already existed in the db (other
                   9566:                         requested keys may also already exist)
                   9567:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9568:  'con_lost' -> unable to contact request server
                   9569:  'refused' -> action was not allowed by remote machine
                   9570: 
                   9571: 
                   9572: =item *
                   9573: 
1.243     albertel 9574: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9575: reference filled in from namesp (encrypts the return communication)
                   9576: ($udom and $uname are optional)
1.191     harris41 9577: 
                   9578: =item *
                   9579: 
1.243     albertel 9580: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9581: critical subroutine
                   9582: 
1.806     raeburn  9583: =item *
                   9584: 
1.860     raeburn  9585: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9586: array reference filled in from namespace found in domain level on either
                   9587: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9588: 
                   9589: =item *
                   9590: 
1.860     raeburn  9591: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9592: domain level either on specified domain server ($uhome) or primary domain 
                   9593: server ($udom and $uhome are optional)
1.806     raeburn  9594: 
1.943     raeburn  9595: =item * 
                   9596: 
                   9597: get_domain_defaults($target_domain) : returns hash with defaults for
                   9598: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9599: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9600: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9601: Values are retrieved from cache (if current), or from domain's configuration.db
                   9602: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9603: or lonTabs/domain.tab. 
                   9604: 
                   9605: %domdefaults = &get_auth_defaults($target_domain);
                   9606: 
1.243     albertel 9607: =back
                   9608: 
                   9609: =head2 Network Status Functions
                   9610: 
                   9611: =over 4
1.191     harris41 9612: 
                   9613: =item *
                   9614: 
                   9615: dirlist($uri) : return directory list based on URI
                   9616: 
                   9617: =item *
                   9618: 
1.243     albertel 9619: spareserver() : find server with least workload from spare.tab
                   9620: 
                   9621: =back
                   9622: 
                   9623: =head2 Apache Request
                   9624: 
                   9625: =over 4
1.191     harris41 9626: 
                   9627: =item *
                   9628: 
1.243     albertel 9629: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9630: localhost, posts hash
                   9631: 
                   9632: =back
                   9633: 
                   9634: =head2 Data to String to Data
                   9635: 
                   9636: =over 4
1.191     harris41 9637: 
                   9638: =item *
                   9639: 
1.243     albertel 9640: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9641: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9642: 
                   9643: =item *
                   9644: 
1.243     albertel 9645: hashref2str($hashref) : convert a hashref into a string complete with
                   9646: escaping and '=' and '&' separators, supports elements that are
                   9647: arrayrefs and hashrefs
1.191     harris41 9648: 
                   9649: =item *
                   9650: 
1.243     albertel 9651: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9652: with escaping and '&' separators, supports elements that are arrayrefs
                   9653: and hashrefs
1.191     harris41 9654: 
                   9655: =item *
                   9656: 
1.243     albertel 9657: str2hash($string) : convert string to hash using unescaping and
                   9658: splitting on '=' and '&', supports elements that are arrayrefs and
                   9659: hashrefs
1.191     harris41 9660: 
                   9661: =item *
                   9662: 
1.243     albertel 9663: str2array($string) : convert string to hash using unescaping and
                   9664: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9665: 
                   9666: =back
                   9667: 
                   9668: =head2 Logging Routines
                   9669: 
                   9670: =over 4
                   9671: 
                   9672: These routines allow one to make log messages in the lonnet.log and
                   9673: lonnet.perm logfiles.
1.191     harris41 9674: 
                   9675: =item *
                   9676: 
1.243     albertel 9677: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9678: 
                   9679: =item *
                   9680: 
1.243     albertel 9681: logthis() : append message to the normal lonnet.log file, it gets
                   9682: preiodically rolled over and deleted.
1.191     harris41 9683: 
                   9684: =item *
                   9685: 
1.243     albertel 9686: logperm() : append a permanent message to lonnet.perm.log, this log
                   9687: file never gets deleted by any automated portion of the system, only
                   9688: messages of critical importance should go in here.
                   9689: 
                   9690: =back
                   9691: 
                   9692: =head2 General File Helper Routines
                   9693: 
                   9694: =over 4
1.191     harris41 9695: 
                   9696: =item *
                   9697: 
1.481     raeburn  9698: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9699: (a) files in /uploaded
                   9700:   (i) If a local copy of the file exists - 
                   9701:       compares modification date of local copy with last-modified date for 
                   9702:       definitive version stored on home server for course. If local copy is 
                   9703:       stale, requests a new version from the home server and stores it. 
                   9704:       If the original has been removed from the home server, then local copy 
                   9705:       is unlinked.
                   9706:   (ii) If local copy does not exist -
                   9707:       requests the file from the home server and stores it. 
                   9708:   
                   9709:   If $caller is 'uploadrep':  
                   9710:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9711:     for request for files originally uploaded via DOCS. 
                   9712:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9713:   
                   9714:   Otherwise:
                   9715:      This indicates a call from the content generation phase of the request.
                   9716:      -  returns the entire contents of the file or -1.
                   9717:      
                   9718: (b) files in /res
                   9719:    - returns the entire contents of a file or -1; 
                   9720:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9721: 
1.712     albertel 9722: 
                   9723: =item *
                   9724: 
                   9725: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9726:                   reference
                   9727: 
                   9728: returns either a stat() list of data about the file or an empty list
                   9729: if the file doesn't exist or couldn't find out about it (connection
                   9730: problems or user unknown)
                   9731: 
1.191     harris41 9732: =item *
                   9733: 
1.243     albertel 9734: filelocation($dir,$file) : returns file system location of a file
                   9735: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9736: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9737: and a file of ../bob will become /a/bob)
1.191     harris41 9738: 
                   9739: =item *
                   9740: 
                   9741: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9742: filelocation except for hrefs
                   9743: 
                   9744: =item *
                   9745: 
                   9746: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9747: 
1.243     albertel 9748: =back
                   9749: 
1.608     albertel 9750: =head2 Usererfile file routines (/uploaded*)
                   9751: 
                   9752: =over 4
                   9753: 
                   9754: =item *
                   9755: 
                   9756: userfileupload(): main rotine for putting a file in a user or course's
                   9757:                   filespace, arguments are,
                   9758: 
1.620     albertel 9759:  formname - required - this is the name of the element in $env where the
1.608     albertel 9760:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9761:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9762:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9763:  coursedoc - if true, store the file in the course of the active role
                   9764:              of the current user
                   9765:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9766:          if undefined, it will be placed in "unknown"
                   9767: 
                   9768:  (This routine calls clean_filename() to remove any dangerous
                   9769:  characters from the filename, and then calls finuserfileupload() to
                   9770:  complete the transaction)
                   9771: 
                   9772:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9773:  and /adm/notfound.html if unsuccessful
                   9774: 
                   9775: =item *
                   9776: 
                   9777: clean_filename(): routine for cleaing a filename up for storage in
                   9778:                  userfile space, argument is:
                   9779: 
                   9780:  filename - proposed filename
                   9781: 
                   9782: returns: the new clean filename
                   9783: 
                   9784: =item *
                   9785: 
                   9786: finishuserfileupload(): routine that creaes and sends the file to
                   9787: userspace, probably shouldn't be called directly
                   9788: 
                   9789:   docuname: username or courseid of destination for the file
                   9790:   docudom: domain of user/course of destination for the file
                   9791:   formname: same as for userfileupload()
                   9792:   fname: filename (inculding subdirectories) for the file
                   9793: 
                   9794:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9795:  and /adm/notfound.html if unsuccessful
                   9796: 
                   9797: =item *
                   9798: 
                   9799: renameuserfile(): renames an existing userfile to a new name
                   9800: 
                   9801:   Args:
                   9802:    docuname: username or courseid of destination for the file
                   9803:    docudom: domain of user/course of destination for the file
                   9804:    old: current file name (including any subdirs under userfiles)
                   9805:    new: desired file name (including any subdirs under userfiles)
                   9806: 
                   9807: =item *
                   9808: 
                   9809: mkdiruserfile(): creates a directory is a userfiles dir
                   9810: 
                   9811:   Args:
                   9812:    docuname: username or courseid of destination for the file
                   9813:    docudom: domain of user/course of destination for the file
                   9814:    dir: dir to create (including any subdirs under userfiles)
                   9815: 
                   9816: =item *
                   9817: 
                   9818: removeuserfile(): removes a file that exists in userfiles
                   9819: 
                   9820:   Args:
                   9821:    docuname: username or courseid of destination for the file
                   9822:    docudom: domain of user/course of destination for the file
                   9823:    fname: filname to delete (including any subdirs under userfiles)
                   9824: 
                   9825: =item *
                   9826: 
                   9827: removeuploadedurl(): convience function for removeuserfile()
                   9828: 
                   9829:   Args:
                   9830:    url:  a full /uploaded/... url to delete
                   9831: 
1.747     albertel 9832: =item * 
                   9833: 
                   9834: get_portfile_permissions():
                   9835:   Args:
                   9836:     domain: domain of user or course contain the portfolio files
                   9837:     user: name of user or num of course contain the portfolio files
                   9838:   Returns:
                   9839:     hashref of a dump of the proper file_permissions.db
                   9840:    
                   9841: 
                   9842: =item * 
                   9843: 
                   9844: get_access_controls():
                   9845: 
                   9846: Args:
                   9847:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9848:   group: (optional) the group you want the files associated with
                   9849:   file: (optional) the file you want access info on
                   9850: 
                   9851: Returns:
1.749     raeburn  9852:     a hash (keys are file names) of hashes containing
                   9853:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9854:         values are XML containing access control settings (see below) 
1.747     albertel 9855: 
                   9856: Internal notes:
                   9857: 
1.749     raeburn  9858:  access controls are stored in file_permissions.db as key=value pairs.
                   9859:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9860:         where scope -> public,guest,course,group,domains or users.
                   9861:               end -> UNIX time for end of access (0 -> no end date)
                   9862:               start -> UNIX time for start of access
                   9863: 
                   9864:     value -> XML description of access control
                   9865:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9866:             <start></start>
                   9867:             <end></end>
                   9868: 
                   9869:             <password></password>  for scope type = guest
                   9870: 
                   9871:             <domain></domain>     for scope type = course or group
                   9872:             <number></number>
                   9873:             <roles id="">
                   9874:              <role></role>
                   9875:              <access></access>
                   9876:              <section></section>
                   9877:              <group></group>
                   9878:             </roles>
                   9879: 
                   9880:             <dom></dom>         for scope type = domains
                   9881: 
                   9882:             <users>             for scope type = users
                   9883:              <user>
                   9884:               <uname></uname>
                   9885:               <udom></udom>
                   9886:              </user>
                   9887:             </users>
                   9888:            </scope> 
                   9889:               
                   9890:  Access data is also aggregated for each file in an additional key=value pair:
                   9891:  key -> path to file/file_name\0accesscontrol 
                   9892:  value -> reference to hash
                   9893:           hash contains key = value pairs
                   9894:           where key = uniqueID:scope_end_start
                   9895:                 value = UNIX time record was last updated
                   9896: 
                   9897:           Used to improve speed of look-ups of access controls for each file.  
                   9898:  
                   9899:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9900: 
                   9901: modify_access_controls():
                   9902: 
                   9903: Modifies access controls for a portfolio file
                   9904: Args
                   9905: 1. file name
                   9906: 2. reference to hash of required changes,
                   9907: 3. domain
                   9908: 4. username
                   9909:   where domain,username are the domain of the portfolio owner 
                   9910:   (either a user or a course) 
                   9911: 
                   9912: Returns:
                   9913: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9914: 2. result of deletions ('ok' or 'error', with error message).
                   9915: 3. reference to hash of any new or updated access controls.
                   9916: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9917:    key = integer (inbound ID)
                   9918:    value = uniqueID  
1.747     albertel 9919: 
1.608     albertel 9920: =back
                   9921: 
1.243     albertel 9922: =head2 HTTP Helper Routines
                   9923: 
                   9924: =over 4
                   9925: 
1.191     harris41 9926: =item *
                   9927: 
                   9928: escape() : unpack non-word characters into CGI-compatible hex codes
                   9929: 
                   9930: =item *
                   9931: 
                   9932: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9933: 
1.243     albertel 9934: =back
                   9935: 
                   9936: =head1 PRIVATE SUBROUTINES
                   9937: 
                   9938: =head2 Underlying communication routines (Shouldn't call)
                   9939: 
                   9940: =over 4
                   9941: 
                   9942: =item *
                   9943: 
                   9944: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9945: 
                   9946: =item *
                   9947: 
                   9948: reply() : uses subreply to send a message to remote machine, logs all failures
                   9949: 
                   9950: =item *
                   9951: 
                   9952: critical() : passes a critical message to another server; if cannot
                   9953: get through then place message in connection buffer directory and
                   9954: returns con_delayed, if incapable of saving message, returns
                   9955: con_failed
                   9956: 
                   9957: =item *
                   9958: 
                   9959: reconlonc() : tries to reconnect lonc client processes.
                   9960: 
                   9961: =back
                   9962: 
                   9963: =head2 Resource Access Logging
                   9964: 
                   9965: =over 4
                   9966: 
                   9967: =item *
                   9968: 
                   9969: flushcourselogs() : flush (save) buffer logs and access logs
                   9970: 
                   9971: =item *
                   9972: 
                   9973: courselog($what) : save message for course in hash
                   9974: 
                   9975: =item *
                   9976: 
                   9977: courseacclog($what) : save message for course using &courselog().  Perform
                   9978: special processing for specific resource types (problems, exams, quizzes, etc).
                   9979: 
1.191     harris41 9980: =item *
                   9981: 
                   9982: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9983: as a PerlChildExitHandler
1.243     albertel 9984: 
                   9985: =back
                   9986: 
                   9987: =head2 Other
                   9988: 
                   9989: =over 4
                   9990: 
                   9991: =item *
                   9992: 
                   9993: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9994: 
                   9995: =back
                   9996: 
                   9997: =cut
1.877     foxr     9998: 

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