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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.959   ! raeburn     4: # $Id: lonnet.pm,v 1.958 2008/05/12 20:59:15 www 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);
                    961:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    962:         my @pairs=split(/\&/,$hashitems);
                    963:         foreach my $item (@pairs) {
                    964:             my ($key,$value)=split(/=/,$item,2);
                    965:             $key = &unescape($key);
                    966:             next if ($key =~ /^error: 2 /);
                    967:             $returnhash{$key}=&thaw_unescape($value);
                    968:         }
                    969:         my @esc_order = split(/\&/,$orderitems);
                    970:         foreach my $item (@esc_order) {
                    971:             push(@order,&unescape($item));
                    972:         }
                    973:     } else {
                    974:         &logthis("get_dom failed - no primary domain server for $udom");
                    975:     }
                    976:     return (\%returnhash,\@order);
                    977: }
                    978: 
1.868     raeburn   979: sub is_domainimage {
                    980:     my ($url) = @_;
                    981:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    982:         if (&domain($1) ne '') {
                    983:             return '1';
                    984:         }
                    985:     }
                    986:     return;
                    987: }
                    988: 
1.899     raeburn   989: sub inst_directory_query {
                    990:     my ($srch) = @_;
                    991:     my $udom = $srch->{'srchdomain'};
                    992:     my %results;
                    993:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   994:     my $outcome;
1.899     raeburn   995:     if ($homeserver ne '') {
1.904     albertel  996: 	my $queryid=&reply("querysend:instdirsearch:".
                    997: 			   &escape($srch->{'srchby'}).':'.
                    998: 			   &escape($srch->{'srchterm'}).':'.
                    999: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1000: 	my $host=&hostname($homeserver);
                   1001: 	if ($queryid !~/^\Q$host\E\_/) {
                   1002: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1003: 	    return;
                   1004: 	}
                   1005: 	my $response = &get_query_reply($queryid);
                   1006: 	my $maxtries = 5;
                   1007: 	my $tries = 1;
                   1008: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1009: 	    $response = &get_query_reply($queryid);
                   1010: 	    $tries ++;
                   1011: 	}
                   1012: 
                   1013:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1014:             if ($response eq 'unavailable') {
                   1015:                 $outcome = $response;
                   1016:             } else {
                   1017:                 $outcome = 'ok';
                   1018:                 my @matches = split(/\n/,$response);
                   1019:                 foreach my $match (@matches) {
                   1020:                     my ($key,$value) = split(/=/,$match);
                   1021:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1022:                 }
1.899     raeburn  1023:             }
                   1024:         }
                   1025:     }
1.909     raeburn  1026:     return ($outcome,%results);
1.899     raeburn  1027: }
                   1028: 
                   1029: sub usersearch {
                   1030:     my ($srch) = @_;
                   1031:     my $dom = $srch->{'srchdomain'};
                   1032:     my %results;
                   1033:     my %libserv = &all_library();
                   1034:     my $query = 'usersearch';
                   1035:     foreach my $tryserver (keys(%libserv)) {
                   1036:         if (&host_domain($tryserver) eq $dom) {
                   1037:             my $host=&hostname($tryserver);
                   1038:             my $queryid=
1.911     raeburn  1039:                 &reply("querysend:".&escape($query).':'.
                   1040:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1041:                        &escape($srch->{'srchtype'}).':'.
                   1042:                        &escape($srch->{'srchterm'}),$tryserver);
                   1043:             if ($queryid !~/^\Q$host\E\_/) {
                   1044:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1045:                 next;
1.899     raeburn  1046:             }
                   1047:             my $reply = &get_query_reply($queryid);
                   1048:             my $maxtries = 1;
                   1049:             my $tries = 1;
                   1050:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1051:                 $reply = &get_query_reply($queryid);
                   1052:                 $tries ++;
                   1053:             }
                   1054:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1055:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1056:             } else {
1.911     raeburn  1057:                 my @matches;
                   1058:                 if ($reply =~ /\n/) {
                   1059:                     @matches = split(/\n/,$reply);
                   1060:                 } else {
                   1061:                     @matches = split(/\&/,$reply);
                   1062:                 }
1.899     raeburn  1063:                 foreach my $match (@matches) {
                   1064:                     my ($uname,$udom,%userhash);
1.911     raeburn  1065:                     foreach my $entry (split(/:/,$match)) {
                   1066:                         my ($key,$value) =
                   1067:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1068:                         $userhash{$key} = $value;
                   1069:                         if ($key eq 'username') {
                   1070:                             $uname = $value;
                   1071:                         } elsif ($key eq 'domain') {
                   1072:                             $udom = $value;
1.911     raeburn  1073:                         }
1.899     raeburn  1074:                     }
                   1075:                     $results{$uname.':'.$udom} = \%userhash;
                   1076:                 }
                   1077:             }
                   1078:         }
                   1079:     }
                   1080:     return %results;
                   1081: }
                   1082: 
1.912     raeburn  1083: sub get_instuser {
                   1084:     my ($udom,$uname,$id) = @_;
                   1085:     my $homeserver = &domain($udom,'primary');
                   1086:     my ($outcome,%results);
                   1087:     if ($homeserver ne '') {
                   1088:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1089:                            &escape($id).':'.&escape($udom),$homeserver);
                   1090:         my $host=&hostname($homeserver);
                   1091:         if ($queryid !~/^\Q$host\E\_/) {
                   1092:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1093:             return;
                   1094:         }
                   1095:         my $response = &get_query_reply($queryid);
                   1096:         my $maxtries = 5;
                   1097:         my $tries = 1;
                   1098:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1099:             $response = &get_query_reply($queryid);
                   1100:             $tries ++;
                   1101:         }
                   1102:         if (!&error($response) && $response ne 'refused') {
                   1103:             if ($response eq 'unavailable') {
                   1104:                 $outcome = $response;
                   1105:             } else {
                   1106:                 $outcome = 'ok';
                   1107:                 my @matches = split(/\n/,$response);
                   1108:                 foreach my $match (@matches) {
                   1109:                     my ($key,$value) = split(/=/,$match);
                   1110:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1111:                 }
                   1112:             }
                   1113:         }
                   1114:     }
                   1115:     my %userinfo;
                   1116:     if (ref($results{$uname}) eq 'HASH') {
                   1117:         %userinfo = %{$results{$uname}};
                   1118:     } 
                   1119:     return ($outcome,%userinfo);
                   1120: }
                   1121: 
                   1122: sub inst_rulecheck {
1.923     raeburn  1123:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1124:     my %returnhash;
                   1125:     if ($udom ne '') {
                   1126:         if (ref($rules) eq 'ARRAY') {
                   1127:             @{$rules} = map {&escape($_);} (@{$rules});
                   1128:             my $rulestr = join(':',@{$rules});
                   1129:             my $homeserver=&domain($udom,'primary');
                   1130:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1131:                 my $response;
                   1132:                 if ($item eq 'username') {                
                   1133:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1134:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1135:                                               $homeserver));
1.923     raeburn  1136:                 } elsif ($item eq 'id') {
                   1137:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1138:                                               ':'.&escape($id).':'.$rulestr,
                   1139:                                               $homeserver));
1.945     raeburn  1140:                 } elsif ($item eq 'selfcreate') {
                   1141:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1142:                                                &escape($udom).':'.&escape($uname).
                   1143:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1144:                 }
1.912     raeburn  1145:                 if ($response ne 'refused') {
                   1146:                     my @pairs=split(/\&/,$response);
                   1147:                     foreach my $item (@pairs) {
                   1148:                         my ($key,$value)=split(/=/,$item,2);
                   1149:                         $key = &unescape($key);
                   1150:                         next if ($key =~ /^error: 2 /);
                   1151:                         $returnhash{$key}=&thaw_unescape($value);
                   1152:                     }
                   1153:                 }
                   1154:             }
                   1155:         }
                   1156:     }
                   1157:     return %returnhash;
                   1158: }
                   1159: 
                   1160: sub inst_userrules {
1.923     raeburn  1161:     my ($udom,$check) = @_;
1.912     raeburn  1162:     my (%ruleshash,@ruleorder);
                   1163:     if ($udom ne '') {
                   1164:         my $homeserver=&domain($udom,'primary');
                   1165:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1166:             my $response;
                   1167:             if ($check eq 'id') {
                   1168:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1169:                                  $homeserver);
1.943     raeburn  1170:             } elsif ($check eq 'email') {
                   1171:                 $response=&reply('instemailrules:'.&escape($udom),
                   1172:                                  $homeserver);
1.923     raeburn  1173:             } else {
                   1174:                 $response=&reply('instuserrules:'.&escape($udom),
                   1175:                                  $homeserver);
                   1176:             }
1.912     raeburn  1177:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1178:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1179:                 ($response ne 'no_such_host')) {
                   1180:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1181:                 my @pairs=split(/\&/,$hashitems);
                   1182:                 foreach my $item (@pairs) {
                   1183:                     my ($key,$value)=split(/=/,$item,2);
                   1184:                     $key = &unescape($key);
                   1185:                     next if ($key =~ /^error: 2 /);
                   1186:                     $ruleshash{$key}=&thaw_unescape($value);
                   1187:                 }
                   1188:                 my @esc_order = split(/\&/,$orderitems);
                   1189:                 foreach my $item (@esc_order) {
                   1190:                     push(@ruleorder,&unescape($item));
                   1191:                 }
                   1192:             }
                   1193:         }
                   1194:     }
                   1195:     return (\%ruleshash,\@ruleorder);
                   1196: }
                   1197: 
1.943     raeburn  1198: # ------------------------- Get Authentication and Language Defaults for Domain
                   1199: 
                   1200: sub get_domain_defaults {
                   1201:     my ($domain) = @_;
                   1202:     my $cachetime = 60*60*24;
                   1203:     my ($defauthtype,$defautharg,$deflang);
                   1204:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1205:     if (defined($cached)) {
                   1206:         if (ref($result) eq 'HASH') {
                   1207:             return %{$result};
                   1208:         }
                   1209:     }
                   1210:     my %domdefaults;
                   1211:     my %domconfig =
                   1212:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1213:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1214:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1215:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1216:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1217:     } else {
                   1218:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1219:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1220:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1221:     }
                   1222:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1223:                                   $cachetime);
                   1224:     return %domdefaults;
                   1225: }
                   1226: 
1.344     www      1227: # --------------------------------------------------- Assign a key to a student
                   1228: 
                   1229: sub assign_access_key {
1.364     www      1230: #
                   1231: # a valid key looks like uname:udom#comments
                   1232: # comments are being appended
                   1233: #
1.498     www      1234:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1235:     $kdom=
1.620     albertel 1236:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1237:     $knum=
1.620     albertel 1238:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1239:     $cdom=
1.620     albertel 1240:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1241:     $cnum=
1.620     albertel 1242:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1243:     $udom=$env{'user.name'} unless (defined($udom));
                   1244:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1245:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1246:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1247:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1248:                                                   # assigned to this person
                   1249:                                                   # - this should not happen,
1.345     www      1250:                                                   # unless something went wrong
                   1251:                                                   # the first time around
                   1252: # ready to assign
1.364     www      1253:         $logentry=$1.'; '.$logentry;
1.496     www      1254:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1255:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1256: # key now belongs to user
1.346     www      1257: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1258:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1259:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1260:                 return 'ok';
                   1261:             } else {
                   1262:                 return 
                   1263:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1264: 	    }
                   1265:         } else {
                   1266:             return 'error: Could not assign key, try again later.';
                   1267:         }
1.364     www      1268:     } elsif (!$existing{$ckey}) {
1.345     www      1269: # the key does not exist
                   1270: 	return 'error: The key does not exist';
                   1271:     } else {
                   1272: # the key is somebody else's
                   1273: 	return 'error: The key is already in use';
                   1274:     }
1.344     www      1275: }
                   1276: 
1.364     www      1277: # ------------------------------------------ put an additional comment on a key
                   1278: 
                   1279: sub comment_access_key {
                   1280: #
                   1281: # a valid key looks like uname:udom#comments
                   1282: # comments are being appended
                   1283: #
                   1284:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1285:     $cdom=
1.620     albertel 1286:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1287:     $cnum=
1.620     albertel 1288:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1289:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1290:     if ($existing{$ckey}) {
                   1291:         $existing{$ckey}.='; '.$logentry;
                   1292: # ready to assign
1.367     www      1293:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1294:                                                  $cdom,$cnum) eq 'ok') {
                   1295: 	    return 'ok';
                   1296:         } else {
                   1297: 	    return 'error: Count not store comment.';
                   1298:         }
                   1299:     } else {
                   1300: # the key does not exist
                   1301: 	return 'error: The key does not exist';
                   1302:     }
                   1303: }
                   1304: 
1.344     www      1305: # ------------------------------------------------------ Generate a set of keys
                   1306: 
                   1307: sub generate_access_keys {
1.364     www      1308:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1309:     $cdom=
1.620     albertel 1310:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1311:     $cnum=
1.620     albertel 1312:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1313:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1314:     unless (($cdom) && ($cnum)) { return 0; }
                   1315:     if ($number>10000) { return 0; }
                   1316:     sleep(2); # make sure don't get same seed twice
                   1317:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1318:     my $total=0;
                   1319:     for (my $i=1;$i<=$number;$i++) {
                   1320:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1321:                   sprintf("%lx",int(100000*rand)).'-'.
                   1322:                   sprintf("%lx",int(100000*rand));
                   1323:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1324:        $newkey=~s/0/h/g; # and also 0 and O
                   1325:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1326:        if ($existing{$newkey}) {
                   1327:            $i--;
                   1328:        } else {
1.364     www      1329: 	  if (&put('accesskeys',
                   1330:               { $newkey => '# generated '.localtime().
1.620     albertel 1331:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1332:                            '; '.$logentry },
                   1333: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1334:               $total++;
                   1335: 	  }
                   1336:        }
                   1337:     }
1.620     albertel 1338:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1339:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1340:     return $total;
                   1341: }
                   1342: 
                   1343: # ------------------------------------------------------- Validate an accesskey
                   1344: 
                   1345: sub validate_access_key {
                   1346:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1347:     $cdom=
1.620     albertel 1348:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1349:     $cnum=
1.620     albertel 1350:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1351:     $udom=$env{'user.domain'} unless (defined($udom));
                   1352:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1353:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1354:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1355: }
                   1356: 
                   1357: # ------------------------------------- Find the section of student in a course
1.652     albertel 1358: sub devalidate_getsection_cache {
                   1359:     my ($udom,$unam,$courseid)=@_;
                   1360:     my $hashid="$udom:$unam:$courseid";
                   1361:     &devalidate_cache_new('getsection',$hashid);
                   1362: }
1.298     matthew  1363: 
1.815     albertel 1364: sub courseid_to_courseurl {
                   1365:     my ($courseid) = @_;
                   1366:     #already url style courseid
                   1367:     return $courseid if ($courseid =~ m{^/});
                   1368: 
                   1369:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1370: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1371: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1372: 	return "/$cdom/$cnum";
                   1373:     }
                   1374: 
                   1375:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1376:     if (exists($courseinfo{'num'})) {
                   1377: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1378:     }
                   1379: 
                   1380:     return undef;
                   1381: }
                   1382: 
1.298     matthew  1383: sub getsection {
                   1384:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1385:     my $cachetime=1800;
1.551     albertel 1386: 
                   1387:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1388:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1389:     if (defined($cached)) { return $result; }
                   1390: 
1.298     matthew  1391:     my %Pending; 
                   1392:     my %Expired;
                   1393:     #
                   1394:     # Each role can either have not started yet (pending), be active, 
                   1395:     #    or have expired.
                   1396:     #
                   1397:     # If there is an active role, we are done.
                   1398:     #
                   1399:     # If there is more than one role which has not started yet, 
                   1400:     #     choose the one which will start sooner
                   1401:     # If there is one role which has not started yet, return it.
                   1402:     #
                   1403:     # If there is more than one expired role, choose the one which ended last.
                   1404:     # If there is a role which has expired, return it.
                   1405:     #
1.815     albertel 1406:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1407:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1408:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1409:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1410:         my $section=$1;
                   1411:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1412:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1413:         my $now=time;
1.548     albertel 1414:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1415:             $Expired{$end}=$section;
                   1416:             next;
                   1417:         }
1.548     albertel 1418:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1419:             $Pending{$start}=$section;
                   1420:             next;
                   1421:         }
1.599     albertel 1422:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1423:     }
                   1424:     #
                   1425:     # Presumedly there will be few matching roles from the above
                   1426:     # loop and the sorting time will be negligible.
                   1427:     if (scalar(keys(%Pending))) {
                   1428:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1429:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1430:     } 
                   1431:     if (scalar(keys(%Expired))) {
                   1432:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1433:         my $time = pop(@sorted);
1.599     albertel 1434:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1435:     }
1.599     albertel 1436:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1437: }
1.70      www      1438: 
1.599     albertel 1439: sub save_cache {
                   1440:     &purge_remembered();
1.722     albertel 1441:     #&Apache::loncommon::validate_page();
1.620     albertel 1442:     undef(%env);
1.780     albertel 1443:     undef($env_loaded);
1.599     albertel 1444: }
1.452     albertel 1445: 
1.599     albertel 1446: my $to_remember=-1;
                   1447: my %remembered;
                   1448: my %accessed;
                   1449: my $kicks=0;
                   1450: my $hits=0;
1.849     albertel 1451: sub make_key {
                   1452:     my ($name,$id) = @_;
1.872     albertel 1453:     if (length($id) > 65 
                   1454: 	&& length(&escape($id)) > 200) {
                   1455: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1456:     }
1.849     albertel 1457:     return &escape($name.':'.$id);
                   1458: }
                   1459: 
1.599     albertel 1460: sub devalidate_cache_new {
                   1461:     my ($name,$id,$debug) = @_;
                   1462:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1463:     $id=&make_key($name,$id);
1.599     albertel 1464:     $memcache->delete($id);
                   1465:     delete($remembered{$id});
                   1466:     delete($accessed{$id});
                   1467: }
                   1468: 
                   1469: sub is_cached_new {
                   1470:     my ($name,$id,$debug) = @_;
1.849     albertel 1471:     $id=&make_key($name,$id);
1.599     albertel 1472:     if (exists($remembered{$id})) {
                   1473: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1474: 	$accessed{$id}=[&gettimeofday()];
                   1475: 	$hits++;
                   1476: 	return ($remembered{$id},1);
                   1477:     }
                   1478:     my $value = $memcache->get($id);
                   1479:     if (!(defined($value))) {
                   1480: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1481: 	return (undef,undef);
1.416     albertel 1482:     }
1.599     albertel 1483:     if ($value eq '__undef__') {
                   1484: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1485: 	$value=undef;
                   1486:     }
                   1487:     &make_room($id,$value,$debug);
                   1488:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1489:     return ($value,1);
                   1490: }
                   1491: 
                   1492: sub do_cache_new {
                   1493:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1494:     $id=&make_key($name,$id);
1.599     albertel 1495:     my $setvalue=$value;
                   1496:     if (!defined($setvalue)) {
                   1497: 	$setvalue='__undef__';
                   1498:     }
1.623     albertel 1499:     if (!defined($time) ) {
                   1500: 	$time=600;
                   1501:     }
1.599     albertel 1502:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1503:     my $result = $memcache->set($id,$setvalue,$time);
                   1504:     if (! $result) {
1.872     albertel 1505: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1506: 	$memcache->disconnect_all();
1.872     albertel 1507:     }
1.600     albertel 1508:     # need to make a copy of $value
1.919     albertel 1509:     &make_room($id,$value,$debug);
1.599     albertel 1510:     return $value;
                   1511: }
                   1512: 
                   1513: sub make_room {
                   1514:     my ($id,$value,$debug)=@_;
1.919     albertel 1515: 
                   1516:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1517:                                     : $value;
1.599     albertel 1518:     if ($to_remember<0) { return; }
                   1519:     $accessed{$id}=[&gettimeofday()];
                   1520:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1521:     my $to_kick;
                   1522:     my $max_time=0;
                   1523:     foreach my $other (keys(%accessed)) {
                   1524: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1525: 	    $to_kick=$other;
                   1526: 	    $max_time=&tv_interval($accessed{$other});
                   1527: 	}
                   1528:     }
                   1529:     delete($remembered{$to_kick});
                   1530:     delete($accessed{$to_kick});
                   1531:     $kicks++;
                   1532:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1533:     return;
                   1534: }
                   1535: 
1.599     albertel 1536: sub purge_remembered {
1.604     albertel 1537:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1538:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1539:     undef(%remembered);
                   1540:     undef(%accessed);
1.428     albertel 1541: }
1.70      www      1542: # ------------------------------------- Read an entry from a user's environment
                   1543: 
                   1544: sub userenvironment {
                   1545:     my ($udom,$unam,@what)=@_;
                   1546:     my %returnhash=();
                   1547:     my @answer=split(/\&/,
                   1548:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1549:                       &homeserver($unam,$udom)));
                   1550:     my $i;
                   1551:     for ($i=0;$i<=$#what;$i++) {
                   1552: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1553:     }
                   1554:     return %returnhash;
1.1       albertel 1555: }
                   1556: 
1.617     albertel 1557: # ---------------------------------------------------------- Get a studentphoto
                   1558: sub studentphoto {
                   1559:     my ($udom,$unam,$ext) = @_;
                   1560:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1561:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1562:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1563:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1564:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1565:             } else {
                   1566:                 my ($result,$perm_reqd)=
1.707     albertel 1567: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1568:                 if ($result eq 'ok') {
                   1569:                     if (!($perm_reqd eq 'yes')) {
                   1570:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1571:                     }
                   1572:                 }
                   1573:             }
                   1574:         }
                   1575:     } else {
                   1576:         my ($result,$perm_reqd) = 
1.707     albertel 1577: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1578:         if ($result eq 'ok') {
                   1579:             if (!($perm_reqd eq 'yes')) {
                   1580:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1581:             }
                   1582:         }
                   1583:     }
                   1584:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1585: }
                   1586: 
                   1587: sub retrievestudentphoto {
                   1588:     my ($udom,$unam,$ext,$type) = @_;
                   1589:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1590:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1591:     if ($ret eq 'ok') {
                   1592:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1593:         if ($type eq 'thumbnail') {
                   1594:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1595:         }
                   1596:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1597:         return $tokenurl;
                   1598:     } else {
                   1599:         if ($type eq 'thumbnail') {
                   1600:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1601:         } else { 
                   1602:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1603:         }
1.617     albertel 1604:     }
                   1605: }
                   1606: 
1.263     www      1607: # -------------------------------------------------------------------- New chat
                   1608: 
                   1609: sub chatsend {
1.724     raeburn  1610:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1611:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1612:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1613:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1614:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1615: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1616: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1617: }
                   1618: 
                   1619: # ------------------------------------------ Find current version of a resource
                   1620: 
                   1621: sub getversion {
                   1622:     my $fname=&clutter(shift);
                   1623:     unless ($fname=~/^\/res\//) { return -1; }
                   1624:     return &currentversion(&filelocation('',$fname));
                   1625: }
                   1626: 
                   1627: sub currentversion {
                   1628:     my $fname=shift;
1.599     albertel 1629:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1630:     if (defined($cached)) { return $result; }
1.292     www      1631:     my $author=$fname;
                   1632:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1633:     my ($udom,$uname)=split(/\//,$author);
                   1634:     my $home=homeserver($uname,$udom);
                   1635:     if ($home eq 'no_host') { 
                   1636:         return -1; 
                   1637:     }
                   1638:     my $answer=reply("currentversion:$fname",$home);
                   1639:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1640: 	return -1;
                   1641:     }
1.599     albertel 1642:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1643: }
                   1644: 
1.1       albertel 1645: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1646: 
1.1       albertel 1647: sub subscribe {
                   1648:     my $fname=shift;
1.761     raeburn  1649:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1650:     $fname=~s/[\n\r]//g;
1.1       albertel 1651:     my $author=$fname;
                   1652:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1653:     my ($udom,$uname)=split(/\//,$author);
                   1654:     my $home=homeserver($uname,$udom);
1.335     albertel 1655:     if ($home eq 'no_host') {
                   1656:         return 'not_found';
1.1       albertel 1657:     }
                   1658:     my $answer=reply("sub:$fname",$home);
1.64      www      1659:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1660: 	$answer.=' by '.$home;
                   1661:     }
1.1       albertel 1662:     return $answer;
                   1663: }
                   1664:     
1.8       www      1665: # -------------------------------------------------------------- Replicate file
                   1666: 
                   1667: sub repcopy {
                   1668:     my $filename=shift;
1.23      www      1669:     $filename=~s/\/+/\//g;
1.607     raeburn  1670:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1671:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1672:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1673: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1674: 	return &repcopy_userfile($filename);
                   1675:     }
1.532     albertel 1676:     $filename=~s/[\n\r]//g;
1.8       www      1677:     my $transname="$filename.in.transfer";
1.828     www      1678: # FIXME: this should flock
1.607     raeburn  1679:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1680:     my $remoteurl=subscribe($filename);
1.64      www      1681:     if ($remoteurl =~ /^con_lost by/) {
                   1682: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1683:            return 'unavailable';
1.8       www      1684:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1685: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1686: 	   return 'not_found';
1.64      www      1687:     } elsif ($remoteurl =~ /^rejected by/) {
                   1688: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1689:            return 'forbidden';
1.20      www      1690:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1691:            return 'ok';
1.8       www      1692:     } else {
1.290     www      1693:         my $author=$filename;
                   1694:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1695:         my ($udom,$uname)=split(/\//,$author);
                   1696:         my $home=homeserver($uname,$udom);
                   1697:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1698:            my @parts=split(/\//,$filename);
                   1699:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1700:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1701:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1702: 	       return 'bad_request';
1.8       www      1703:            }
                   1704:            my $count;
                   1705:            for ($count=5;$count<$#parts;$count++) {
                   1706:                $path.="/$parts[$count]";
                   1707:                if ((-e $path)!=1) {
                   1708: 		   mkdir($path,0777);
                   1709:                }
                   1710:            }
                   1711:            my $ua=new LWP::UserAgent;
                   1712:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1713:            my $response=$ua->request($request,$transname);
                   1714:            if ($response->is_error()) {
                   1715: 	       unlink($transname);
                   1716:                my $message=$response->status_line;
1.672     albertel 1717:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1718:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1719:                return 'unavailable';
1.8       www      1720:            } else {
1.16      www      1721: 	       if ($remoteurl!~/\.meta$/) {
                   1722:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1723:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1724:                   if ($mresponse->is_error()) {
                   1725: 		      unlink($filename.'.meta');
                   1726:                       &logthis(
1.672     albertel 1727:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1728:                   }
                   1729: 	       }
1.8       www      1730:                rename($transname,$filename);
1.607     raeburn  1731:                return 'ok';
1.8       www      1732:            }
1.290     www      1733:        }
1.8       www      1734:     }
1.330     www      1735: }
                   1736: 
                   1737: # ------------------------------------------------ Get server side include body
                   1738: sub ssi_body {
1.381     albertel 1739:     my ($filelink,%form)=@_;
1.606     matthew  1740:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1741:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1742:     }
1.953     www      1743:     my $output='';
                   1744:     my $response;
                   1745:     if ($filelink=~/^http\:/) {
1.954     raeburn  1746:        ($output,$response)=&externalssi($filelink);
1.953     www      1747:     } else {
                   1748:        ($output,$response)=&ssi($filelink,%form);
                   1749:     }
1.778     albertel 1750:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1751:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1752:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1753:     if (wantarray) {
                   1754:         return ($output, $response);
                   1755:     } else {
                   1756:         return $output;
                   1757:     }
1.8       www      1758: }
                   1759: 
1.15      www      1760: # --------------------------------------------------------- Server Side Include
                   1761: 
1.782     albertel 1762: sub absolute_url {
                   1763:     my ($host_name) = @_;
                   1764:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1765:     if ($host_name eq '') {
                   1766: 	$host_name = $ENV{'SERVER_NAME'};
                   1767:     }
                   1768:     return $protocol.$host_name;
                   1769: }
                   1770: 
1.942     foxr     1771: #
                   1772: #   Server side include.
                   1773: # Parameters:
                   1774: #  fn     Possibly encrypted resource name/id.
                   1775: #  form   Hash that describes how the rendering should be done
                   1776: #         and other things.
1.944     foxr     1777: # Returns:
1.950     raeburn  1778: #   Scalar context: The content of the response.
                   1779: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1780: #     
1.15      www      1781: sub ssi {
                   1782: 
1.944     foxr     1783:     my ($fn,%form)=@_;
1.15      www      1784:     my $ua=new LWP::UserAgent;
1.23      www      1785:     my $request;
1.711     albertel 1786: 
                   1787:     $form{'no_update_last_known'}=1;
1.895     albertel 1788:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1789:     if (%form) {
1.782     albertel 1790:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1791:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1792:     } else {
1.782     albertel 1793:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1794:     }
                   1795: 
1.15      www      1796:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1797:     my $response=$ua->request($request);
                   1798: 
1.944     foxr     1799:     if (wantarray) {
                   1800: 	return ($response->content, $response);
                   1801:     } else {
                   1802: 	return $response->content;
1.942     foxr     1803:     }
1.324     www      1804: }
                   1805: 
                   1806: sub externalssi {
                   1807:     my ($url)=@_;
                   1808:     my $ua=new LWP::UserAgent;
                   1809:     my $request=new HTTP::Request('GET',$url);
                   1810:     my $response=$ua->request($request);
1.954     raeburn  1811:     if (wantarray) {
                   1812:         return ($response->content, $response);
                   1813:     } else {
                   1814:         return $response->content;
                   1815:     }
1.15      www      1816: }
1.254     www      1817: 
1.492     albertel 1818: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1819: 
                   1820: sub allowuploaded {
                   1821:     my ($srcurl,$url)=@_;
                   1822:     $url=&clutter(&declutter($url));
                   1823:     my $dir=$url;
                   1824:     $dir=~s/\/[^\/]+$//;
                   1825:     my %httpref=();
                   1826:     my $httpurl=&hreflocation('',$url);
                   1827:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1828:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1829: }
1.477     raeburn  1830: 
1.478     albertel 1831: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1832: # input: action, courseID, current domain, intended
1.637     raeburn  1833: #        path to file, source of file, instruction to parse file for objects,
                   1834: #        ref to hash for embedded objects,
                   1835: #        ref to hash for codebase of java objects.
                   1836: #
1.485     raeburn  1837: # output: url to file (if action was uploaddoc), 
                   1838: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1839: #
1.478     albertel 1840: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1841: # course.
1.477     raeburn  1842: #
1.478     albertel 1843: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1844: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1845: #          course's home server.
1.477     raeburn  1846: #
1.478     albertel 1847: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1848: #          be copied from $source (current location) to 
                   1849: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1850: #         and will then be copied to
                   1851: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1852: #         course's home server.
1.485     raeburn  1853: #
1.481     raeburn  1854: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1855: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1856: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1857: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1858: #         in course's home server.
1.637     raeburn  1859: #
1.477     raeburn  1860: 
                   1861: sub process_coursefile {
1.638     albertel 1862:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1863:     my $fetchresult;
1.638     albertel 1864:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1865:     if ($action eq 'propagate') {
1.638     albertel 1866:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1867: 			     $home);
1.481     raeburn  1868:     } else {
1.477     raeburn  1869:         my $fpath = '';
                   1870:         my $fname = $file;
1.478     albertel 1871:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1872:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1873:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1874:         if ($action eq 'copy') {
                   1875:             if ($source eq '') {
                   1876:                 $fetchresult = 'no source file';
                   1877:                 return $fetchresult;
                   1878:             } else {
                   1879:                 my $destination = $filepath.'/'.$fname;
                   1880:                 rename($source,$destination);
                   1881:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1882:                                  $home);
1.481     raeburn  1883:             }
                   1884:         } elsif ($action eq 'uploaddoc') {
                   1885:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1886:             print $fh $env{'form.'.$source};
1.481     raeburn  1887:             close($fh);
1.637     raeburn  1888:             if ($parser eq 'parse') {
                   1889:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1890:                 unless ($parse_result eq 'ok') {
                   1891:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1892:                 }
                   1893:             }
1.477     raeburn  1894:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1895:                                  $home);
1.481     raeburn  1896:             if ($fetchresult eq 'ok') {
                   1897:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1898:             } else {
                   1899:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1900:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1901:                 return '/adm/notfound.html';
                   1902:             }
1.477     raeburn  1903:         }
                   1904:     }
1.485     raeburn  1905:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1906:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1907:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1908:     }
                   1909:     return $fetchresult;
                   1910: }
                   1911: 
1.637     raeburn  1912: sub build_filepath {
                   1913:     my ($fpath) = @_;
                   1914:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1915:     unless ($fpath eq '') {
                   1916:         my @parts=split('/',$fpath);
                   1917:         foreach my $part (@parts) {
                   1918:             $filepath.= '/'.$part;
                   1919:             if ((-e $filepath)!=1) {
                   1920:                 mkdir($filepath,0777);
                   1921:             }
                   1922:         }
                   1923:     }
                   1924:     return $filepath;
                   1925: }
                   1926: 
                   1927: sub store_edited_file {
1.638     albertel 1928:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1929:     my $file = $primary_url;
                   1930:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1931:     my $fpath = '';
                   1932:     my $fname = $file;
                   1933:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1934:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1935:     my $filepath = &build_filepath($fpath);
                   1936:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1937:     print $fh $content;
                   1938:     close($fh);
1.638     albertel 1939:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1940:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1941: 			  $home);
1.637     raeburn  1942:     if ($$fetchresult eq 'ok') {
                   1943:         return '/uploaded/'.$fpath.'/'.$fname;
                   1944:     } else {
1.638     albertel 1945:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1946: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1947:         return '/adm/notfound.html';
                   1948:     }
                   1949: }
                   1950: 
1.531     albertel 1951: sub clean_filename {
1.831     albertel 1952:     my ($fname,$args)=@_;
1.315     www      1953: # Replace Windows backslashes by forward slashes
1.257     www      1954:     $fname=~s/\\/\//g;
1.831     albertel 1955:     if (!$args->{'keep_path'}) {
                   1956:         # Get rid of everything but the actual filename
                   1957: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1958:     }
1.315     www      1959: # Replace spaces by underscores
                   1960:     $fname=~s/\s+/\_/g;
                   1961: # Replace all other weird characters by nothing
1.831     albertel 1962:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1963: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1964: # numbers
                   1965:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1966:     return $fname;
                   1967: }
                   1968: 
1.608     albertel 1969: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1970: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1971: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1972: #        $coursedoc - if true up to the current course
                   1973: #                     if false
                   1974: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1975: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1976: #        $allfiles - reference to hash for embedded objects
                   1977: #        $codebase - reference to hash for codebase of java objects
                   1978: #        $desuname - username for permanent storage of uploaded file
                   1979: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1980: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1981: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1982: # 
1.686     albertel 1983: # output: url of file in userspace, or error: <message> 
                   1984: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1985: 
                   1986: 
1.531     albertel 1987: sub userfileupload {
1.860     raeburn  1988:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1989:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1990:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1991:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1992:     $fname=&clean_filename($fname);
1.315     www      1993: # See if there is anything left
1.257     www      1994:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1995:     chop($env{'form.'.$formname});
1.523     raeburn  1996:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1997:         my $now = time;
                   1998:         my $filepath = 'tmp/helprequests/'.$now;
                   1999:         my @parts=split(/\//,$filepath);
                   2000:         my $fullpath = $perlvar{'lonDaemons'};
                   2001:         for (my $i=0;$i<@parts;$i++) {
                   2002:             $fullpath .= '/'.$parts[$i];
                   2003:             if ((-e $fullpath)!=1) {
                   2004:                 mkdir($fullpath,0777);
                   2005:             }
                   2006:         }
                   2007:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2008:         print $fh $env{'form.'.$formname};
1.523     raeburn  2009:         close($fh);
1.741     raeburn  2010:         return $fullpath.'/'.$fname;
                   2011:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2012:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2013:                        '_'.$env{'user.domain'}.'/pending';
                   2014:         my @parts=split(/\//,$filepath);
                   2015:         my $fullpath = $perlvar{'lonDaemons'};
                   2016:         for (my $i=0;$i<@parts;$i++) {
                   2017:             $fullpath .= '/'.$parts[$i];
                   2018:             if ((-e $fullpath)!=1) {
                   2019:                 mkdir($fullpath,0777);
                   2020:             }
                   2021:         }
                   2022:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2023:         print $fh $env{'form.'.$formname};
                   2024:         close($fh);
                   2025:         return $fullpath.'/'.$fname;
1.523     raeburn  2026:     }
1.719     banghart 2027:     
1.258     www      2028: # Create the directory if not present
1.493     albertel 2029:     $fname="$subdir/$fname";
1.259     www      2030:     if ($coursedoc) {
1.638     albertel 2031: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2032: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2033:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2034:             return &finishuserfileupload($docuname,$docudom,
                   2035: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2036: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2037:         } else {
1.620     albertel 2038:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2039:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2040: 				       $fname,$formname,$parser,
                   2041: 				       $allfiles,$codebase);
1.481     raeburn  2042:         }
1.719     banghart 2043:     } elsif (defined($destuname)) {
                   2044:         my $docuname=$destuname;
                   2045:         my $docudom=$destudom;
1.860     raeburn  2046: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2047: 				     $parser,$allfiles,$codebase,
                   2048:                                      $thumbwidth,$thumbheight);
1.719     banghart 2049:         
1.259     www      2050:     } else {
1.638     albertel 2051:         my $docuname=$env{'user.name'};
                   2052:         my $docudom=$env{'user.domain'};
1.714     raeburn  2053:         if (exists($env{'form.group'})) {
                   2054:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2055:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2056:         }
1.860     raeburn  2057: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2058: 				     $parser,$allfiles,$codebase,
                   2059:                                      $thumbwidth,$thumbheight);
1.259     www      2060:     }
1.271     www      2061: }
                   2062: 
                   2063: sub finishuserfileupload {
1.860     raeburn  2064:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2065:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2066:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2067:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2068:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2069:     $file=$fname;
                   2070:     if ($fname=~m|/|) {
                   2071:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2072: 	$path.=$fnamepath.'/';
                   2073:     }
1.259     www      2074:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2075:     my $count;
                   2076:     for ($count=4;$count<=$#parts;$count++) {
                   2077:         $filepath.="/$parts[$count]";
                   2078:         if ((-e $filepath)!=1) {
                   2079: 	    mkdir($filepath,0777);
                   2080:         }
                   2081:     }
                   2082: # Save the file
                   2083:     {
1.701     albertel 2084: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2085: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2086: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2087: 	    return '/adm/notfound.html';
                   2088: 	}
                   2089: 	if (!print FH ($env{'form.'.$formname})) {
                   2090: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2091: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2092: 	    return '/adm/notfound.html';
                   2093: 	}
1.570     albertel 2094: 	close(FH);
1.258     www      2095:     }
1.637     raeburn  2096:     if ($parser eq 'parse') {
1.638     albertel 2097:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2098: 						   $codebase);
1.637     raeburn  2099:         unless ($parse_result eq 'ok') {
1.638     albertel 2100:             &logthis('Failed to parse '.$filepath.$file.
                   2101: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2102:         }
                   2103:     }
1.860     raeburn  2104:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2105:         my $input = $filepath.'/'.$file;
                   2106:         my $output = $filepath.'/'.'tn-'.$file;
                   2107:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2108:         system("convert -sample $thumbsize $input $output");
                   2109:         if (-e $filepath.'/'.'tn-'.$file) {
                   2110:             $fetchthumb  = 1; 
                   2111:         }
                   2112:     }
1.858     raeburn  2113:  
1.259     www      2114: # Notify homeserver to grep it
                   2115: #
1.638     albertel 2116:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2117:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2118:     if ($fetchresult eq 'ok') {
1.860     raeburn  2119:         if ($fetchthumb) {
                   2120:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2121:             if ($thumbresult ne 'ok') {
                   2122:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2123:                          $docuhome.': '.$thumbresult);
                   2124:             }
                   2125:         }
1.259     www      2126: #
1.258     www      2127: # Return the URL to it
1.494     albertel 2128:         return '/uploaded/'.$path.$file;
1.263     www      2129:     } else {
1.494     albertel 2130:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2131: 		 ': '.$fetchresult);
1.263     www      2132:         return '/adm/notfound.html';
1.858     raeburn  2133:     }
1.493     albertel 2134: }
                   2135: 
1.637     raeburn  2136: sub extract_embedded_items {
1.648     raeburn  2137:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2138:     my @state = ();
                   2139:     my %javafiles = (
                   2140:                       codebase => '',
                   2141:                       code => '',
                   2142:                       archive => ''
                   2143:                     );
                   2144:     my %mediafiles = (
                   2145:                       src => '',
                   2146:                       movie => '',
                   2147:                      );
1.648     raeburn  2148:     my $p;
                   2149:     if ($content) {
                   2150:         $p = HTML::LCParser->new($content);
                   2151:     } else {
                   2152:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2153:     }
1.641     albertel 2154:     while (my $t=$p->get_token()) {
1.640     albertel 2155: 	if ($t->[0] eq 'S') {
                   2156: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2157: 	    push(@state, $tagname);
1.648     raeburn  2158:             if (lc($tagname) eq 'allow') {
                   2159:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2160:             }
1.640     albertel 2161: 	    if (lc($tagname) eq 'img') {
                   2162: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2163: 	    }
1.886     albertel 2164: 	    if (lc($tagname) eq 'a') {
                   2165: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2166: 	    }
1.645     raeburn  2167:             if (lc($tagname) eq 'script') {
                   2168:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2169:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2170:                 } else {
                   2171:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2172:                 }
                   2173:             }
                   2174:             if (lc($tagname) eq 'link') {
                   2175:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2176:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2177:                 }
                   2178:             }
1.640     albertel 2179: 	    if (lc($tagname) eq 'object' ||
                   2180: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2181: 		foreach my $item (keys(%javafiles)) {
                   2182: 		    $javafiles{$item} = '';
                   2183: 		}
                   2184: 	    }
                   2185: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2186: 		my $name = lc($attr->{'name'});
                   2187: 		foreach my $item (keys(%javafiles)) {
                   2188: 		    if ($name eq $item) {
                   2189: 			$javafiles{$item} = $attr->{'value'};
                   2190: 			last;
                   2191: 		    }
                   2192: 		}
                   2193: 		foreach my $item (keys(%mediafiles)) {
                   2194: 		    if ($name eq $item) {
                   2195: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2196: 			last;
                   2197: 		    }
                   2198: 		}
                   2199: 	    }
                   2200: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2201: 		foreach my $item (keys(%javafiles)) {
                   2202: 		    if ($attr->{$item}) {
                   2203: 			$javafiles{$item} = $attr->{$item};
                   2204: 			last;
                   2205: 		    }
                   2206: 		}
                   2207: 		foreach my $item (keys(%mediafiles)) {
                   2208: 		    if ($attr->{$item}) {
                   2209: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2210: 			last;
                   2211: 		    }
                   2212: 		}
                   2213: 	    }
                   2214: 	} elsif ($t->[0] eq 'E') {
                   2215: 	    my ($tagname) = ($t->[1]);
                   2216: 	    if ($javafiles{'codebase'} ne '') {
                   2217: 		$javafiles{'codebase'} .= '/';
                   2218: 	    }  
                   2219: 	    if (lc($tagname) eq 'applet' ||
                   2220: 		lc($tagname) eq 'object' ||
                   2221: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2222: 		) {
                   2223: 		foreach my $item (keys(%javafiles)) {
                   2224: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2225: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2226: 			&add_filetype($allfiles,$file,$item);
                   2227: 		    }
                   2228: 		}
                   2229: 	    } 
                   2230: 	    pop @state;
                   2231: 	}
                   2232:     }
1.637     raeburn  2233:     return 'ok';
                   2234: }
                   2235: 
1.639     albertel 2236: sub add_filetype {
                   2237:     my ($allfiles,$file,$type)=@_;
                   2238:     if (exists($allfiles->{$file})) {
                   2239: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2240: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2241: 	}
                   2242:     } else {
                   2243: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2244:     }
                   2245: }
                   2246: 
1.493     albertel 2247: sub removeuploadedurl {
                   2248:     my ($url)=@_;
                   2249:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2250:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2251: }
                   2252: 
                   2253: sub removeuserfile {
                   2254:     my ($docuname,$docudom,$fname)=@_;
                   2255:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2256:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2257:     if ($result eq 'ok') {
                   2258:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2259:             my $metafile = $fname.'.meta';
                   2260:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2261: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2262:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2263:             my $sqlresult = 
1.823     albertel 2264:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2265:                                         'portfolio_metadata',$group,
                   2266:                                         'delete');
1.798     raeburn  2267:         }
                   2268:     }
                   2269:     return $result;
1.257     www      2270: }
1.15      www      2271: 
1.530     albertel 2272: sub mkdiruserfile {
                   2273:     my ($docuname,$docudom,$dir)=@_;
                   2274:     my $home=&homeserver($docuname,$docudom);
                   2275:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2276: }
                   2277: 
1.531     albertel 2278: sub renameuserfile {
                   2279:     my ($docuname,$docudom,$old,$new)=@_;
                   2280:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2281:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2282:                         &escape("$old").':'.&escape("$new"),$home);
                   2283:     if ($result eq 'ok') {
                   2284:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2285:             my $oldmeta = $old.'.meta';
                   2286:             my $newmeta = $new.'.meta';
                   2287:             my $metaresult = 
                   2288:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2289: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2290:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2291:             my $sqlresult = 
1.823     albertel 2292:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2293:                                         'portfolio_metadata',$group,
                   2294:                                         'delete');
1.798     raeburn  2295:         }
                   2296:     }
                   2297:     return $result;
1.531     albertel 2298: }
                   2299: 
1.14      www      2300: # ------------------------------------------------------------------------- Log
                   2301: 
                   2302: sub log {
                   2303:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2304:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2305: }
                   2306: 
                   2307: # ------------------------------------------------------------------ Course Log
1.352     www      2308: #
                   2309: # This routine flushes several buffers of non-mission-critical nature
                   2310: #
1.157     www      2311: 
                   2312: sub flushcourselogs {
1.352     www      2313:     &logthis('Flushing log buffers');
                   2314: #
                   2315: # course logs
                   2316: # This is a log of all transactions in a course, which can be used
                   2317: # for data mining purposes
                   2318: #
                   2319: # It also collects the courseid database, which lists last transaction
                   2320: # times and course titles for all courseids
                   2321: #
                   2322:     my %courseidbuffer=();
1.921     raeburn  2323:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2324:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2325: 		          &escape($courselogs{$crsid}),
                   2326: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2327: 	    delete $courselogs{$crsid};
                   2328:         } else {
                   2329:             &logthis('Failed to flush log buffer for '.$crsid);
                   2330:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2331:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2332:                         " exceeded maximum size, deleting.</font>");
                   2333:                delete $courselogs{$crsid};
                   2334:             }
1.352     www      2335:         }
1.920     raeburn  2336:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2337:             'description' => $coursedescrbuf{$crsid},
                   2338:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2339:             'type'        => $coursetypebuf{$crsid},
                   2340:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2341:         };
1.191     harris41 2342:     }
1.352     www      2343: #
                   2344: # Write course id database (reverse lookup) to homeserver of courses 
                   2345: # Is used in pickcourse
                   2346: #
1.840     albertel 2347:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2348:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2349:                                     $courseidbuffer{$crs_home},
                   2350:                                     $crs_home,'timeonly');
1.352     www      2351:     }
                   2352: #
                   2353: # File accesses
                   2354: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2355: #
1.449     matthew  2356:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2357:         if ($entry =~ /___count$/) {
                   2358:             my ($dom,$name);
1.807     albertel 2359:             ($dom,$name,undef)=
1.811     albertel 2360: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2361:             if (! defined($dom) || $dom eq '' || 
                   2362:                 ! defined($name) || $name eq '') {
1.620     albertel 2363:                 my $cid = $env{'request.course.id'};
                   2364:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2365:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2366:             }
1.450     matthew  2367:             my $value = $accesshash{$entry};
                   2368:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2369:             my %temphash=($url => $value);
1.449     matthew  2370:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2371:             if ($result eq 'ok') {
                   2372:                 delete $accesshash{$entry};
                   2373:             } elsif ($result eq 'unknown_cmd') {
                   2374:                 # Target server has old code running on it.
1.450     matthew  2375:                 my %temphash=($entry => $value);
1.449     matthew  2376:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2377:                     delete $accesshash{$entry};
                   2378:                 }
                   2379:             }
                   2380:         } else {
1.811     albertel 2381:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2382:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2383:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2384:                 delete $accesshash{$entry};
                   2385:             }
1.185     www      2386:         }
1.191     harris41 2387:     }
1.352     www      2388: #
                   2389: # Roles
                   2390: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2391: #
1.800     albertel 2392:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2393:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2394: 	    split(/\:/,$entry);
                   2395:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2396:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2397:                 $rudom,$runame) eq 'ok') {
                   2398: 	    delete $userrolehash{$entry};
                   2399:         }
                   2400:     }
1.662     raeburn  2401: #
                   2402: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2403: #
                   2404:     my %domrolebuffer = ();
                   2405:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2406:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2407:         if ($domrolebuffer{$rudom}) {
                   2408:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2409:                       '='.&escape($domainrolehash{$entry});
                   2410:         } else {
                   2411:             $domrolebuffer{$rudom}.=&escape($entry).
                   2412:                       '='.&escape($domainrolehash{$entry});
                   2413:         }
                   2414:         delete $domainrolehash{$entry};
                   2415:     }
                   2416:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2417: 	my %servers = &get_servers($dom,'library');
                   2418: 	foreach my $tryserver (keys(%servers)) {
                   2419: 	    unless (&reply('domroleput:'.$dom.':'.
                   2420: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2421: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2422: 	    }
1.662     raeburn  2423:         }
                   2424:     }
1.186     www      2425:     $dumpcount++;
1.157     www      2426: }
                   2427: 
                   2428: sub courselog {
                   2429:     my $what=shift;
1.158     www      2430:     $what=time.':'.$what;
1.620     albertel 2431:     unless ($env{'request.course.id'}) { return ''; }
                   2432:     $coursedombuf{$env{'request.course.id'}}=
                   2433:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2434:     $coursenumbuf{$env{'request.course.id'}}=
                   2435:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2436:     $coursehombuf{$env{'request.course.id'}}=
                   2437:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2438:     $coursedescrbuf{$env{'request.course.id'}}=
                   2439:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2440:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2441:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2442:     $courseownerbuf{$env{'request.course.id'}}=
                   2443:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2444:     $coursetypebuf{$env{'request.course.id'}}=
                   2445:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2446:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2447: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2448:     } else {
1.620     albertel 2449: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2450:     }
1.620     albertel 2451:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2452: 	&flushcourselogs();
                   2453:     }
1.158     www      2454: }
                   2455: 
                   2456: sub courseacclog {
                   2457:     my $fnsymb=shift;
1.620     albertel 2458:     unless ($env{'request.course.id'}) { return ''; }
                   2459:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2460:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2461:         $what.=':POST';
1.583     matthew  2462:         # FIXME: Probably ought to escape things....
1.800     albertel 2463: 	foreach my $key (keys(%env)) {
                   2464:             if ($key=~/^form\.(.*)/) {
                   2465: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2466:             }
1.191     harris41 2467:         }
1.583     matthew  2468:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2469:         # FIXME: We should not be depending on a form parameter that someone
                   2470:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2471:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2472:             $what.= ':POST';
                   2473:             # FIXME: Probably ought to escape things....
                   2474:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2475:                                  'crsdiscuss') {
1.620     albertel 2476:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2477:             }
                   2478:         }
1.158     www      2479:     }
                   2480:     &courselog($what);
1.149     www      2481: }
                   2482: 
1.185     www      2483: sub countacc {
                   2484:     my $url=&declutter(shift);
1.458     matthew  2485:     return if (! defined($url) || $url eq '');
1.620     albertel 2486:     unless ($env{'request.course.id'}) { return ''; }
                   2487:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2488:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2489:     $accesshash{$key}++;
1.185     www      2490: }
1.349     www      2491: 
1.361     www      2492: sub linklog {
                   2493:     my ($from,$to)=@_;
                   2494:     $from=&declutter($from);
                   2495:     $to=&declutter($to);
                   2496:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2497:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2498: }
                   2499:   
1.349     www      2500: sub userrolelog {
                   2501:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2502:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2503:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2504:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2505:         ($trole=~/^ta/)) {
1.350     www      2506:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2507:        $userrolehash
                   2508:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2509:                     =$tend.':'.$tstart;
1.662     raeburn  2510:     }
1.898     albertel 2511:     if (($env{'request.role'} =~ /dc\./) &&
                   2512: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2513: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2514: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2515:        $userrolehash
                   2516:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2517:                     =$tend.':'.$tstart;
                   2518:     }
1.662     raeburn  2519:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2520:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2521:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2522:         ($trole=~/^sc/)) {
                   2523:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2524:        $domainrolehash
                   2525:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2526:                     = $tend.':'.$tstart;
                   2527:     }
1.351     www      2528: }
                   2529: 
1.957     raeburn  2530: sub courserolelog {
                   2531:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2532:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2533:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2534:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2535:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2536:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2537:             my $cdom = $1;
                   2538:             my $cnum = $2;
                   2539:             my $sec = $3;
                   2540:             my $namespace = 'rolelog';
                   2541:             my %storehash = (
                   2542:                                role    => $trole,
                   2543:                                start   => $tstart,
                   2544:                                end     => $tend,
                   2545:                                selfenroll => $selfenroll,
                   2546:                                context    => $context,
                   2547:                             );
                   2548:             if ($trole eq 'gr') {
                   2549:                 $namespace = 'groupslog';
                   2550:                 $storehash{'group'} = $sec;
                   2551:             } else {
                   2552:                 $storehash{'section'} = $sec;
                   2553:             }
                   2554:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2555:         }
                   2556:     }
                   2557:     return;
                   2558: }
                   2559: 
1.351     www      2560: sub get_course_adv_roles {
1.948     raeburn  2561:     my ($cid,$codes) = @_;
1.620     albertel 2562:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2563:     my %coursehash=&coursedescription($cid);
1.470     www      2564:     my %nothide=();
1.800     albertel 2565:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2566:         if ($user !~ /:/) {
                   2567: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2568:         } else {
                   2569:             $nothide{$user}=1;
                   2570:         }
1.470     www      2571:     }
1.351     www      2572:     my %returnhash=();
                   2573:     my %dumphash=
                   2574:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2575:     my $now=time;
1.800     albertel 2576:     foreach my $entry (keys %dumphash) {
                   2577: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2578:         if (($tstart) && ($tstart<0)) { next; }
                   2579:         if (($tend) && ($tend<$now)) { next; }
                   2580:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2581:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2582: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2583: 	if ((&privileged($username,$domain)) && 
                   2584: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2585: 	if ($role eq 'cr') { next; }
1.948     raeburn  2586:         if ($codes) {
                   2587:             if ($section) { $role .= ':'.$section; }
                   2588:             if ($returnhash{$role}) {
                   2589:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2590:             } else {
                   2591:                 $returnhash{$role}=$username.':'.$domain;
                   2592:             }
1.351     www      2593:         } else {
1.948     raeburn  2594:             my $key=&plaintext($role);
                   2595:             if ($section) { $key.=' (Section '.$section.')'; }
                   2596:             if ($returnhash{$key}) {
                   2597: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2598:             } else {
                   2599:                 $returnhash{$key}=$username.':'.$domain;
                   2600:             }
1.351     www      2601:         }
1.948     raeburn  2602:     }
1.400     www      2603:     return %returnhash;
                   2604: }
                   2605: 
                   2606: sub get_my_roles {
1.937     raeburn  2607:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2608:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2609:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2610:     my (%dumphash,%nothide);
1.858     raeburn  2611:     if ($context eq 'userroles') { 
                   2612:         %dumphash = &dump('roles',$udom,$uname);
                   2613:     } else {
                   2614:         %dumphash=
1.400     www      2615:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2616:         if ($hidepriv) {
                   2617:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2618:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2619:                 if ($user !~ /:/) {
                   2620:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2621:                 } else {
                   2622:                     $nothide{$user} = 1;
                   2623:                 }
                   2624:             }
                   2625:         }
1.858     raeburn  2626:     }
1.400     www      2627:     my %returnhash=();
                   2628:     my $now=time;
1.800     albertel 2629:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2630:         my ($role,$tend,$tstart);
                   2631:         if ($context eq 'userroles') {
                   2632: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2633:         } else {
                   2634:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2635:         }
1.400     www      2636:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2637:         my $status = 'active';
1.939     raeburn  2638:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2639:             $status = 'previous';
                   2640:         } 
                   2641:         if (($tstart) && ($now<$tstart)) {
                   2642:             $status = 'future';
                   2643:         }
                   2644:         if (ref($types) eq 'ARRAY') {
                   2645:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2646:                 next;
                   2647:             } 
                   2648:         } else {
                   2649:             if ($status ne 'active') {
                   2650:                 next;
                   2651:             }
                   2652:         }
1.867     raeburn  2653:         my ($rolecode,$username,$domain,$section,$area);
                   2654:         if ($context eq 'userroles') {
                   2655:             ($area,$rolecode) = split(/_/,$entry);
                   2656:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2657:         } else {
                   2658:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2659:         }
1.832     raeburn  2660:         if (ref($roledoms) eq 'ARRAY') {
                   2661:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2662:                 next;
                   2663:             }
                   2664:         }
                   2665:         if (ref($roles) eq 'ARRAY') {
                   2666:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2667:                 if ($role =~ /^cr\//) {
                   2668:                     if (!grep(/^cr$/,@{$roles})) {
                   2669:                         next;
                   2670:                     }
                   2671:                 } else {
                   2672:                     next;
                   2673:                 }
1.832     raeburn  2674:             }
1.867     raeburn  2675:         }
1.937     raeburn  2676:         if ($hidepriv) {
                   2677:             if ((&privileged($username,$domain)) &&
                   2678:                 (!$nothide{$username.':'.$domain})) { 
                   2679:                 next;
                   2680:             }
                   2681:         }
1.933     raeburn  2682:         if ($withsec) {
                   2683:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2684:                 $tstart.':'.$tend;
                   2685:         } else {
                   2686:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2687:         }
1.832     raeburn  2688:     }
1.373     www      2689:     return %returnhash;
1.399     www      2690: }
                   2691: 
                   2692: # ----------------------------------------------------- Frontpage Announcements
                   2693: #
                   2694: #
                   2695: 
                   2696: sub postannounce {
                   2697:     my ($server,$text)=@_;
1.844     albertel 2698:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2699:     unless ($text=~/\w/) { $text=''; }
                   2700:     return &reply('setannounce:'.&escape($text),$server);
                   2701: }
                   2702: 
                   2703: sub getannounce {
1.448     albertel 2704: 
                   2705:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2706: 	my $announcement='';
1.800     albertel 2707: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2708: 	close($fh);
1.399     www      2709: 	if ($announcement=~/\w/) { 
                   2710: 	    return 
                   2711:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2712:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2713: 	} else {
                   2714: 	    return '';
                   2715: 	}
                   2716:     } else {
                   2717: 	return '';
                   2718:     }
1.351     www      2719: }
1.353     www      2720: 
                   2721: # ---------------------------------------------------------- Course ID routines
                   2722: # Deal with domain's nohist_courseid.db files
                   2723: #
                   2724: 
                   2725: sub courseidput {
1.921     raeburn  2726:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2727:     my $outcome;
                   2728:     if ($caller eq 'timeonly') {
                   2729:         my $cids = '';
                   2730:         foreach my $item (keys(%$storehash)) {
                   2731:             $cids.=&escape($item).'&';
                   2732:         }
                   2733:         $cids=~s/\&$//;
                   2734:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2735:                           $coursehome);       
                   2736:     } else {
                   2737:         my $items = '';
                   2738:         foreach my $item (keys(%$storehash)) {
                   2739:             $items.= &escape($item).'='.
                   2740:                      &freeze_escape($$storehash{$item}).'&';
                   2741:         }
                   2742:         $items=~s/\&$//;
                   2743:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2744:                           $coursehome);
1.918     raeburn  2745:     }
                   2746:     if ($outcome eq 'unknown_cmd') {
                   2747:         my $what;
                   2748:         foreach my $cid (keys(%$storehash)) {
                   2749:             $what .= &escape($cid).'=';
1.921     raeburn  2750:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2751:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2752:             }
                   2753:             $what =~ s/\:$/&/;
                   2754:         }
                   2755:         $what =~ s/\&$//;  
                   2756:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2757:     } else {
                   2758:         return $outcome;
                   2759:     }
1.353     www      2760: }
                   2761: 
                   2762: sub courseiddump {
1.921     raeburn  2763:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2764:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.959   ! raeburn  2765:         $selfenrollonly,$catfilter)=@_;
1.918     raeburn  2766:     my $as_hash = 1;
                   2767:     my %returnhash;
                   2768:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2769:     my %libserv = &all_library();
                   2770:     foreach my $tryserver (keys(%libserv)) {
                   2771:         if ( (  $hostidflag == 1 
                   2772: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2773: 	     || (!defined($hostidflag)) ) {
                   2774: 
1.918     raeburn  2775: 	    if (($domfilter eq '') ||
                   2776: 		(&host_domain($tryserver) eq $domfilter)) {
                   2777:                 my $rep = 
                   2778:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2779:                          $sincefilter.':'.&escape($descfilter).':'.
                   2780:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2781:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2782:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.959   ! raeburn  2783:                          &escape($selfenrollonly).':'.&escape($catfilter),$tryserver);
1.918     raeburn  2784:                 my @pairs=split(/\&/,$rep);
                   2785:                 foreach my $item (@pairs) {
                   2786:                     my ($key,$value)=split(/\=/,$item,2);
                   2787:                     $key = &unescape($key);
                   2788:                     next if ($key =~ /^error: 2 /);
                   2789:                     my $result = &thaw_unescape($value);
                   2790:                     if (ref($result) eq 'HASH') {
                   2791:                         $returnhash{$key}=$result;
                   2792:                     } else {
1.921     raeburn  2793:                         my @responses = split(/:/,$value);
                   2794:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2795:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2796:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2797:                         }
                   2798:                     } 
1.353     www      2799:                 }
                   2800:             }
                   2801:         }
                   2802:     }
                   2803:     return %returnhash;
                   2804: }
                   2805: 
1.658     raeburn  2806: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2807: 
                   2808: sub dcmailput {
1.685     raeburn  2809:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2810:     my $status = &Apache::lonnet::critical(
1.740     www      2811:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2812:        &escape($message),$server);
1.662     raeburn  2813:     return $status;
                   2814: }
                   2815: 
1.658     raeburn  2816: sub dcmaildump {
                   2817:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2818:     my %returnhash=();
1.846     albertel 2819: 
                   2820:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2821:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2822:                                                          &escape($enddate).':';
                   2823: 	my @esc_senders=map { &escape($_)} @$senders;
                   2824: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2825: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2826:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2827:             if (($key) && ($value)) {
                   2828:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2829:             }
                   2830:         }
                   2831:     }
                   2832:     return %returnhash;
                   2833: }
1.662     raeburn  2834: # ---------------------------------------------------------- Domain roles
                   2835: 
                   2836: sub get_domain_roles {
                   2837:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2838:     if (undef($startdate) || $startdate eq '') {
                   2839:         $startdate = '.';
                   2840:     }
                   2841:     if (undef($enddate) || $enddate eq '') {
                   2842:         $enddate = '.';
                   2843:     }
1.922     raeburn  2844:     my $rolelist;
                   2845:     if (ref($roles) eq 'ARRAY') {
                   2846:         $rolelist = join(':',@{$roles});
                   2847:     }
1.662     raeburn  2848:     my %personnel = ();
1.841     albertel 2849: 
                   2850:     my %servers = &get_servers($dom,'library');
                   2851:     foreach my $tryserver (keys(%servers)) {
                   2852: 	%{$personnel{$tryserver}}=();
                   2853: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2854: 					    &escape($startdate).':'.
                   2855: 					    &escape($enddate).':'.
                   2856: 					    &escape($rolelist), $tryserver))) {
                   2857: 	    my ($key,$value) = split(/\=/,$line,2);
                   2858: 	    if (($key) && ($value)) {
                   2859: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2860: 	    }
                   2861: 	}
1.662     raeburn  2862:     }
                   2863:     return %personnel;
                   2864: }
1.658     raeburn  2865: 
1.149     www      2866: # ----------------------------------------------------------- Check out an item
                   2867: 
1.504     albertel 2868: sub get_first_access {
                   2869:     my ($type,$argsymb)=@_;
1.790     albertel 2870:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2871:     if ($argsymb) { $symb=$argsymb; }
                   2872:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2873:     if ($type eq 'course') {
                   2874: 	$res='course';
                   2875:     } elsif ($type eq 'map') {
1.588     albertel 2876: 	$res=&symbread($map);
                   2877:     } else {
                   2878: 	$res=$symb;
                   2879:     }
                   2880:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2881:     return $times{"$courseid\0$res"};
1.504     albertel 2882: }
                   2883: 
                   2884: sub set_first_access {
                   2885:     my ($type)=@_;
1.790     albertel 2886:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2887:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2888:     if ($type eq 'course') {
                   2889: 	$res='course';
                   2890:     } elsif ($type eq 'map') {
1.588     albertel 2891: 	$res=&symbread($map);
                   2892:     } else {
                   2893: 	$res=$symb;
                   2894:     }
                   2895:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2896:     if (!$firstaccess) {
1.588     albertel 2897: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2898:     }
                   2899:     return 'already_set';
1.504     albertel 2900: }
                   2901: 
1.149     www      2902: sub checkout {
                   2903:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2904:     my $now=time;
                   2905:     my $lonhost=$perlvar{'lonHostID'};
                   2906:     my $infostr=&escape(
1.234     www      2907:                  'CHECKOUTTOKEN&'.
1.149     www      2908:                  $tuname.'&'.
                   2909:                  $tudom.'&'.
                   2910:                  $tcrsid.'&'.
                   2911:                  $symb.'&'.
                   2912: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2913:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2914:     if ($token=~/^error\:/) { 
1.672     albertel 2915:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2916:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2917:                  "</font>");
                   2918:         return ''; 
                   2919:     }
                   2920: 
1.149     www      2921:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2922:     $token=~tr/a-z/A-Z/;
                   2923: 
1.153     www      2924:     my %infohash=('resource.0.outtoken' => $token,
                   2925:                   'resource.0.checkouttime' => $now,
                   2926:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2927: 
                   2928:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2929:        return '';
1.151     www      2930:     } else {
1.672     albertel 2931:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2932:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2933:                  "</font>");
1.149     www      2934:     }    
                   2935: 
                   2936:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2937:                          &escape('Checkout '.$infostr.' - '.
                   2938:                                                  $token)) ne 'ok') {
                   2939: 	return '';
1.151     www      2940:     } else {
1.672     albertel 2941:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2942:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2943:                  "</font>");
1.149     www      2944:     }
1.151     www      2945:     return $token;
1.149     www      2946: }
                   2947: 
                   2948: # ------------------------------------------------------------ Check in an item
                   2949: 
                   2950: sub checkin {
                   2951:     my $token=shift;
1.150     www      2952:     my $now=time;
                   2953:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2954:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2955:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2956:     $dtoken=~s/\W/\_/g;
1.234     www      2957:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2958:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2959: 
1.154     www      2960:     unless (($tuname) && ($tudom)) {
                   2961:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2962:         return '';
                   2963:     }
                   2964:     
                   2965:     unless (&allowed('mgr',$tcrsid)) {
                   2966:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2967:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2968:         return '';
                   2969:     }
                   2970: 
1.153     www      2971:     my %infohash=('resource.0.intoken' => $token,
                   2972:                   'resource.0.checkintime' => $now,
                   2973:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2974: 
                   2975:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2976:        return '';
                   2977:     }    
                   2978: 
                   2979:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2980:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2981: 	return '';
                   2982:     }
                   2983: 
                   2984:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2985: }
                   2986: 
                   2987: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2988: 
                   2989: sub expirespread {
                   2990:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2991:     my $cid=$env{'request.course.id'}; 
1.110     www      2992:     if ($cid) {
                   2993:        my $now=time;
                   2994:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2995:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2996:                             $env{'course.'.$cid.'.num'}.
1.110     www      2997: 	        	    ':nohist_expirationdates:'.
                   2998:                             &escape($key).'='.$now,
1.620     albertel 2999:                             $env{'course.'.$cid.'.home'})
1.110     www      3000:     }
                   3001:     return 'ok';
1.14      www      3002: }
                   3003: 
1.109     www      3004: # ----------------------------------------------------- Devalidate Spreadsheets
                   3005: 
                   3006: sub devalidate {
1.325     www      3007:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3008:     my $cid=$env{'request.course.id'}; 
1.109     www      3009:     if ($cid) {
1.391     matthew  3010:         # delete the stored spreadsheets for
                   3011:         # - the student level sheet of this user in course's homespace
                   3012:         # - the assessment level sheet for this resource 
                   3013:         #   for this user in user's homespace
1.553     albertel 3014: 	# - current conditional state info
1.325     www      3015: 	my $key=$uname.':'.$udom.':';
1.109     www      3016:         my $status=
1.299     matthew  3017: 	    &del('nohist_calculatedsheets',
1.391     matthew  3018: 		 [$key.'studentcalc:'],
1.620     albertel 3019: 		 $env{'course.'.$cid.'.domain'},
                   3020: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3021: 		.' '.
                   3022: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3023: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3024:         unless ($status eq 'ok ok') {
                   3025:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3026:                     $uname.' at '.$udom.' for '.
1.109     www      3027: 		    $symb.': '.$status);
1.133     albertel 3028:         }
1.553     albertel 3029: 	&delenv('user.state.'.$cid);
1.109     www      3030:     }
                   3031: }
                   3032: 
1.265     albertel 3033: sub get_scalar {
                   3034:     my ($string,$end) = @_;
                   3035:     my $value;
                   3036:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3037: 	$value = $1;
                   3038:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3039: 	$value = $1;
                   3040:     }
                   3041:     return &unescape($value);
                   3042: }
                   3043: 
                   3044: sub array2str {
                   3045:   my (@array) = @_;
                   3046:   my $result=&arrayref2str(\@array);
                   3047:   $result=~s/^__ARRAY_REF__//;
                   3048:   $result=~s/__END_ARRAY_REF__$//;
                   3049:   return $result;
                   3050: }
                   3051: 
1.204     albertel 3052: sub arrayref2str {
                   3053:   my ($arrayref) = @_;
1.265     albertel 3054:   my $result='__ARRAY_REF__';
1.204     albertel 3055:   foreach my $elem (@$arrayref) {
1.265     albertel 3056:     if(ref($elem) eq 'ARRAY') {
                   3057:       $result.=&arrayref2str($elem).'&';
                   3058:     } elsif(ref($elem) eq 'HASH') {
                   3059:       $result.=&hashref2str($elem).'&';
                   3060:     } elsif(ref($elem)) {
                   3061:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3062:     } else {
                   3063:       $result.=&escape($elem).'&';
                   3064:     }
                   3065:   }
                   3066:   $result=~s/\&$//;
1.265     albertel 3067:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3068:   return $result;
                   3069: }
                   3070: 
1.168     albertel 3071: sub hash2str {
1.204     albertel 3072:   my (%hash) = @_;
                   3073:   my $result=&hashref2str(\%hash);
1.265     albertel 3074:   $result=~s/^__HASH_REF__//;
                   3075:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3076:   return $result;
                   3077: }
                   3078: 
                   3079: sub hashref2str {
                   3080:   my ($hashref)=@_;
1.265     albertel 3081:   my $result='__HASH_REF__';
1.800     albertel 3082:   foreach my $key (sort(keys(%$hashref))) {
                   3083:     if (ref($key) eq 'ARRAY') {
                   3084:       $result.=&arrayref2str($key).'=';
                   3085:     } elsif (ref($key) eq 'HASH') {
                   3086:       $result.=&hashref2str($key).'=';
                   3087:     } elsif (ref($key)) {
1.265     albertel 3088:       $result.='=';
1.800     albertel 3089:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3090:     } else {
1.800     albertel 3091: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3092:     }
                   3093: 
1.800     albertel 3094:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3095:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3096:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3097:       $result.=&hashref2str($hashref->{$key}).'&';
                   3098:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3099:        $result.='&';
1.800     albertel 3100:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3101:     } else {
1.800     albertel 3102:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3103:     }
                   3104:   }
1.168     albertel 3105:   $result=~s/\&$//;
1.265     albertel 3106:   $result .= '__END_HASH_REF__';
1.168     albertel 3107:   return $result;
                   3108: }
                   3109: 
                   3110: sub str2hash {
1.265     albertel 3111:     my ($string)=@_;
                   3112:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3113:     return %$hash;
                   3114: }
                   3115: 
                   3116: sub str2hashref {
1.168     albertel 3117:   my ($string) = @_;
1.265     albertel 3118: 
                   3119:   my %hash;
                   3120: 
                   3121:   if($string !~ /^__HASH_REF__/) {
                   3122:       if (! ($string eq '' || !defined($string))) {
                   3123: 	  $hash{'error'}='Not hash reference';
                   3124:       }
                   3125:       return (\%hash, $string);
                   3126:   }
                   3127: 
                   3128:   $string =~ s/^__HASH_REF__//;
                   3129: 
                   3130:   while($string !~ /^__END_HASH_REF__/) {
                   3131:       #key
                   3132:       my $key='';
                   3133:       if($string =~ /^__HASH_REF__/) {
                   3134:           ($key, $string)=&str2hashref($string);
                   3135:           if(defined($key->{'error'})) {
                   3136:               $hash{'error'}='Bad data';
                   3137:               return (\%hash, $string);
                   3138:           }
                   3139:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3140:           ($key, $string)=&str2arrayref($string);
                   3141:           if($key->[0] eq 'Array reference error') {
                   3142:               $hash{'error'}='Bad data';
                   3143:               return (\%hash, $string);
                   3144:           }
                   3145:       } else {
                   3146:           $string =~ s/^(.*?)=//;
1.267     albertel 3147: 	  $key=&unescape($1);
1.265     albertel 3148:       }
                   3149:       $string =~ s/^=//;
                   3150: 
                   3151:       #value
                   3152:       my $value='';
                   3153:       if($string =~ /^__HASH_REF__/) {
                   3154:           ($value, $string)=&str2hashref($string);
                   3155:           if(defined($value->{'error'})) {
                   3156:               $hash{'error'}='Bad data';
                   3157:               return (\%hash, $string);
                   3158:           }
                   3159:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3160:           ($value, $string)=&str2arrayref($string);
                   3161:           if($value->[0] eq 'Array reference error') {
                   3162:               $hash{'error'}='Bad data';
                   3163:               return (\%hash, $string);
                   3164:           }
                   3165:       } else {
                   3166: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3167:       }
                   3168:       $string =~ s/^&//;
                   3169: 
                   3170:       $hash{$key}=$value;
1.204     albertel 3171:   }
1.265     albertel 3172: 
                   3173:   $string =~ s/^__END_HASH_REF__//;
                   3174: 
                   3175:   return (\%hash, $string);
1.204     albertel 3176: }
                   3177: 
                   3178: sub str2array {
1.265     albertel 3179:     my ($string)=@_;
                   3180:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3181:     return @$array;
                   3182: }
                   3183: 
                   3184: sub str2arrayref {
1.204     albertel 3185:   my ($string) = @_;
1.265     albertel 3186:   my @array;
                   3187: 
                   3188:   if($string !~ /^__ARRAY_REF__/) {
                   3189:       if (! ($string eq '' || !defined($string))) {
                   3190: 	  $array[0]='Array reference error';
                   3191:       }
                   3192:       return (\@array, $string);
                   3193:   }
                   3194: 
                   3195:   $string =~ s/^__ARRAY_REF__//;
                   3196: 
                   3197:   while($string !~ /^__END_ARRAY_REF__/) {
                   3198:       my $value='';
                   3199:       if($string =~ /^__HASH_REF__/) {
                   3200:           ($value, $string)=&str2hashref($string);
                   3201:           if(defined($value->{'error'})) {
                   3202:               $array[0] ='Array reference error';
                   3203:               return (\@array, $string);
                   3204:           }
                   3205:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3206:           ($value, $string)=&str2arrayref($string);
                   3207:           if($value->[0] eq 'Array reference error') {
                   3208:               $array[0] ='Array reference error';
                   3209:               return (\@array, $string);
                   3210:           }
                   3211:       } else {
                   3212: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3213:       }
                   3214:       $string =~ s/^&//;
                   3215: 
                   3216:       push(@array, $value);
1.191     harris41 3217:   }
1.265     albertel 3218: 
                   3219:   $string =~ s/^__END_ARRAY_REF__//;
                   3220: 
                   3221:   return (\@array, $string);
1.168     albertel 3222: }
                   3223: 
1.167     albertel 3224: # -------------------------------------------------------------------Temp Store
                   3225: 
1.168     albertel 3226: sub tmpreset {
                   3227:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3228:   if (!$symb) {
                   3229:     $symb=&symbread();
1.620     albertel 3230:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3231:   }
                   3232:   $symb=escape($symb);
                   3233: 
1.620     albertel 3234:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3235:   $namespace=~s/\//\_/g;
                   3236:   $namespace=~s/\W//g;
                   3237: 
1.620     albertel 3238:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3239:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3240:   if ($domain eq 'public' && $stuname eq 'public') {
                   3241:       $stuname=$ENV{'REMOTE_ADDR'};
                   3242:   }
1.168     albertel 3243:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3244:   my %hash;
                   3245:   if (tie(%hash,'GDBM_File',
                   3246: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3247: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3248:     foreach my $key (keys %hash) {
1.180     albertel 3249:       if ($key=~ /:$symb/) {
1.168     albertel 3250: 	delete($hash{$key});
                   3251:       }
                   3252:     }
                   3253:   }
                   3254: }
                   3255: 
1.167     albertel 3256: sub tmpstore {
1.168     albertel 3257:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3258: 
                   3259:   if (!$symb) {
                   3260:     $symb=&symbread();
1.620     albertel 3261:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3262:   }
                   3263:   $symb=escape($symb);
                   3264: 
                   3265:   if (!$namespace) {
                   3266:     # I don't think we would ever want to store this for a course.
                   3267:     # it seems this will only be used if we don't have a course.
1.620     albertel 3268:     #$namespace=$env{'request.course.id'};
1.168     albertel 3269:     #if (!$namespace) {
1.620     albertel 3270:       $namespace=$env{'request.state'};
1.168     albertel 3271:     #}
                   3272:   }
                   3273:   $namespace=~s/\//\_/g;
                   3274:   $namespace=~s/\W//g;
1.620     albertel 3275:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3276:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3277:   if ($domain eq 'public' && $stuname eq 'public') {
                   3278:       $stuname=$ENV{'REMOTE_ADDR'};
                   3279:   }
1.168     albertel 3280:   my $now=time;
                   3281:   my %hash;
                   3282:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3283:   if (tie(%hash,'GDBM_File',
                   3284: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3285: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3286:     $hash{"version:$symb"}++;
                   3287:     my $version=$hash{"version:$symb"};
                   3288:     my $allkeys=''; 
                   3289:     foreach my $key (keys(%$storehash)) {
                   3290:       $allkeys.=$key.':';
1.591     albertel 3291:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3292:     }
                   3293:     $hash{"$version:$symb:timestamp"}=$now;
                   3294:     $allkeys.='timestamp';
                   3295:     $hash{"$version:keys:$symb"}=$allkeys;
                   3296:     if (untie(%hash)) {
                   3297:       return 'ok';
                   3298:     } else {
                   3299:       return "error:$!";
                   3300:     }
                   3301:   } else {
                   3302:     return "error:$!";
                   3303:   }
                   3304: }
1.167     albertel 3305: 
1.168     albertel 3306: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3307: 
1.168     albertel 3308: sub tmprestore {
                   3309:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3310: 
1.168     albertel 3311:   if (!$symb) {
                   3312:     $symb=&symbread();
1.620     albertel 3313:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3314:   }
                   3315:   $symb=escape($symb);
                   3316: 
1.620     albertel 3317:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3318: 
1.620     albertel 3319:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3320:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3321:   if ($domain eq 'public' && $stuname eq 'public') {
                   3322:       $stuname=$ENV{'REMOTE_ADDR'};
                   3323:   }
1.168     albertel 3324:   my %returnhash;
                   3325:   $namespace=~s/\//\_/g;
                   3326:   $namespace=~s/\W//g;
                   3327:   my %hash;
                   3328:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3329:   if (tie(%hash,'GDBM_File',
                   3330: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3331: 	  &GDBM_READER(),0640)) {
1.168     albertel 3332:     my $version=$hash{"version:$symb"};
                   3333:     $returnhash{'version'}=$version;
                   3334:     my $scope;
                   3335:     for ($scope=1;$scope<=$version;$scope++) {
                   3336:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3337:       my @keys=split(/:/,$vkeys);
                   3338:       my $key;
                   3339:       $returnhash{"$scope:keys"}=$vkeys;
                   3340:       foreach $key (@keys) {
1.591     albertel 3341: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3342: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3343:       }
                   3344:     }
1.168     albertel 3345:     if (!(untie(%hash))) {
                   3346:       return "error:$!";
                   3347:     }
                   3348:   } else {
                   3349:     return "error:$!";
                   3350:   }
                   3351:   return %returnhash;
1.167     albertel 3352: }
                   3353: 
1.9       www      3354: # ----------------------------------------------------------------------- Store
                   3355: 
                   3356: sub store {
1.124     www      3357:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3358:     my $home='';
                   3359: 
1.168     albertel 3360:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3361: 
1.213     www      3362:     $symb=&symbclean($symb);
1.122     albertel 3363:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3364: 
1.620     albertel 3365:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3366:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3367: 
                   3368:     &devalidate($symb,$stuname,$domain);
1.109     www      3369: 
                   3370:     $symb=escape($symb);
1.187     www      3371:     if (!$namespace) { 
1.620     albertel 3372:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3373:           return ''; 
                   3374:        } 
                   3375:     }
1.620     albertel 3376:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3377: 
                   3378:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3379:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3380: 
1.12      www      3381:     my $namevalue='';
1.800     albertel 3382:     foreach my $key (keys(%$storehash)) {
                   3383:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3384:     }
1.12      www      3385:     $namevalue=~s/\&$//;
1.187     www      3386:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3387:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3388: }
                   3389: 
1.47      www      3390: # -------------------------------------------------------------- Critical Store
                   3391: 
                   3392: sub cstore {
1.124     www      3393:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3394:     my $home='';
                   3395: 
1.168     albertel 3396:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3397: 
1.213     www      3398:     $symb=&symbclean($symb);
1.122     albertel 3399:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3400: 
1.620     albertel 3401:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3402:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3403: 
                   3404:     &devalidate($symb,$stuname,$domain);
1.109     www      3405: 
                   3406:     $symb=escape($symb);
1.187     www      3407:     if (!$namespace) { 
1.620     albertel 3408:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3409:           return ''; 
                   3410:        } 
                   3411:     }
1.620     albertel 3412:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3413: 
                   3414:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3415:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3416: 
1.47      www      3417:     my $namevalue='';
1.800     albertel 3418:     foreach my $key (keys(%$storehash)) {
                   3419:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3420:     }
1.47      www      3421:     $namevalue=~s/\&$//;
1.187     www      3422:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3423:     return critical
                   3424:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3425: }
                   3426: 
1.9       www      3427: # --------------------------------------------------------------------- Restore
                   3428: 
                   3429: sub restore {
1.124     www      3430:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3431:     my $home='';
                   3432: 
1.168     albertel 3433:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3434: 
1.122     albertel 3435:     if (!$symb) {
                   3436:       unless ($symb=escape(&symbread())) { return ''; }
                   3437:     } else {
1.213     www      3438:       $symb=&escape(&symbclean($symb));
1.122     albertel 3439:     }
1.188     www      3440:     if (!$namespace) { 
1.620     albertel 3441:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3442:           return ''; 
                   3443:        } 
                   3444:     }
1.620     albertel 3445:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3446:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3447:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3448:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3449: 
1.12      www      3450:     my %returnhash=();
1.800     albertel 3451:     foreach my $line (split(/\&/,$answer)) {
                   3452: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3453:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3454:     }
1.75      www      3455:     my $version;
                   3456:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3457:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3458:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3459:        }
1.75      www      3460:     }
1.13      www      3461:     return %returnhash;
1.34      www      3462: }
                   3463: 
                   3464: # ---------------------------------------------------------- Course Description
                   3465: 
                   3466: sub coursedescription {
1.731     albertel 3467:     my ($courseid,$args)=@_;
1.34      www      3468:     $courseid=~s/^\///;
1.49      www      3469:     $courseid=~s/\_/\//g;
1.34      www      3470:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3471:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3472:     my $normalid=$cdomain.'_'.$cnum;
                   3473:     # need to always cache even if we get errors otherwise we keep 
                   3474:     # trying and trying and trying to get the course description.
                   3475:     my %envhash=();
                   3476:     my %returnhash=();
1.731     albertel 3477:     
                   3478:     my $expiretime=600;
                   3479:     if ($env{'request.course.id'} eq $normalid) {
                   3480: 	$expiretime=120;
                   3481:     }
                   3482: 
                   3483:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3484:     if (!$args->{'freshen_cache'}
                   3485: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3486: 	foreach my $key (keys(%env)) {
                   3487: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3488: 	    my ($setting) = $1;
                   3489: 	    $returnhash{$setting} = $env{$key};
                   3490: 	}
                   3491: 	return %returnhash;
                   3492:     }
                   3493: 
                   3494:     # get the data agin
                   3495:     if (!$args->{'one_time'}) {
                   3496: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3497:     }
1.811     albertel 3498: 
1.34      www      3499:     if ($chome ne 'no_host') {
1.302     albertel 3500:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3501:        if (!exists($returnhash{'con_lost'})) {
                   3502:            $returnhash{'home'}= $chome;
                   3503: 	   $returnhash{'domain'} = $cdomain;
                   3504: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3505:            if (!defined($returnhash{'type'})) {
                   3506:                $returnhash{'type'} = 'Course';
                   3507:            }
1.130     albertel 3508:            while (my ($name,$value) = each %returnhash) {
1.53      www      3509:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3510:            }
1.270     www      3511:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3512:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3513: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3514:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3515:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3516:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3517:        }
                   3518:     }
1.731     albertel 3519:     if (!$args->{'one_time'}) {
1.949     raeburn  3520: 	&appenv(\%envhash);
1.731     albertel 3521:     }
1.302     albertel 3522:     return %returnhash;
1.461     www      3523: }
                   3524: 
                   3525: # -------------------------------------------------See if a user is privileged
                   3526: 
                   3527: sub privileged {
                   3528:     my ($username,$domain)=@_;
                   3529:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3530: 			&homeserver($username,$domain));
                   3531:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3532:     my $now=time;
                   3533:     if ($rolesdump ne '') {
1.800     albertel 3534:         foreach my $entry (split(/&/,$rolesdump)) {
                   3535: 	    if ($entry!~/^rolesdef_/) {
                   3536: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3537: 		$area=~s/\_\w\w$//;
                   3538: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3539: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3540: 		    my $active=1;
                   3541: 		    if ($tend) {
                   3542: 			if ($tend<$now) { $active=0; }
                   3543: 		    }
                   3544: 		    if ($tstart) {
                   3545: 			if ($tstart>$now) { $active=0; }
                   3546: 		    }
                   3547: 		    if ($active) { return 1; }
                   3548: 		}
                   3549: 	    }
                   3550: 	}
                   3551:     }
                   3552:     return 0;
1.9       www      3553: }
1.1       albertel 3554: 
1.103     harris41 3555: # -------------------------------------------------------- Get user privileges
1.11      www      3556: 
                   3557: sub rolesinit {
                   3558:     my ($domain,$username,$authhost)=@_;
                   3559:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3560:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3561:     my %allroles=();
1.678     raeburn  3562:     my %allgroups=();   
1.11      www      3563:     my $now=time;
1.743     albertel 3564:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3565:     my $group_privs;
1.11      www      3566: 
                   3567:     if ($rolesdump ne '') {
1.800     albertel 3568:         foreach my $entry (split(/&/,$rolesdump)) {
                   3569: 	  if ($entry!~/^rolesdef_/) {
                   3570:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3571: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3572:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3573: 	    if ($role=~/^cr/) { 
1.807     albertel 3574: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3575: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3576: 		    ($tend,$tstart)=split('_',$trest);
                   3577: 		} else {
                   3578: 		    $trole=$role;
                   3579: 		}
1.678     raeburn  3580:             } elsif ($role =~ m|^gr/|) {
                   3581:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3582:                 ($trole,$group_privs) = split(/\//,$trole);
                   3583:                 $group_privs = &unescape($group_privs);
1.587     albertel 3584: 	    } else {
                   3585: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3586: 	    }
1.743     albertel 3587: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3588: 					 $username);
                   3589: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3590:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3591:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3592:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3593: 		my $spec=$trole.'.'.$area;
                   3594: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3595: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3596:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3597:                 } elsif ($trole eq 'gr') {
                   3598:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3599: 		} else {
1.567     raeburn  3600:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3601: 		}
1.12      www      3602:             }
1.662     raeburn  3603:           }
1.191     harris41 3604:         }
1.743     albertel 3605:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3606:         $userroles{'user.adv'}    = $adv;
                   3607: 	$userroles{'user.author'} = $author;
1.620     albertel 3608:         $env{'user.adv'}=$adv;
1.11      www      3609:     }
1.743     albertel 3610:     return \%userroles;  
1.11      www      3611: }
                   3612: 
1.567     raeburn  3613: sub set_arearole {
                   3614:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3615: # log the associated role with the area
                   3616:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3617:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3618: }
                   3619: 
                   3620: sub custom_roleprivs {
                   3621:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3622:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3623:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3624:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3625:         my ($rdummy,$roledef)=
                   3626:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3627:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3628:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3629:             if (defined($syspriv)) {
                   3630:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3631:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3632:             }
                   3633:             if ($tdomain ne '') {
                   3634:                 if (defined($dompriv)) {
                   3635:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3636:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3637:                 }
                   3638:                 if (($trest ne '') && (defined($coursepriv))) {
                   3639:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3640:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3641:                 }
                   3642:             }
                   3643:         }
                   3644:     }
                   3645: }
                   3646: 
1.678     raeburn  3647: sub group_roleprivs {
                   3648:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3649:     my $access = 1;
                   3650:     my $now = time;
                   3651:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3652:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3653:     if ($access) {
1.811     albertel 3654:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3655:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3656:     }
                   3657: }
1.567     raeburn  3658: 
                   3659: sub standard_roleprivs {
                   3660:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3661:     if (defined($pr{$trole.':s'})) {
                   3662:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3663:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3664:     }
                   3665:     if ($tdomain ne '') {
                   3666:         if (defined($pr{$trole.':d'})) {
                   3667:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3668:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3669:         }
                   3670:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3671:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3672:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3673:         }
                   3674:     }
                   3675: }
                   3676: 
                   3677: sub set_userprivs {
1.678     raeburn  3678:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3679:     my $author=0;
                   3680:     my $adv=0;
1.678     raeburn  3681:     my %grouproles = ();
                   3682:     if (keys(%{$allgroups}) > 0) {
                   3683:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3684:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3685:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3686:                 $trole = $1;
                   3687:                 $area = $2;
1.681     raeburn  3688:                 $sec = $3;
                   3689:                 $extendedarea = $area.$sec;
                   3690:                 if (exists($$allgroups{$area})) {
                   3691:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3692:                         my $spec = $trole.'.'.$extendedarea;
                   3693:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3694:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3695:                     }
                   3696:                 }
                   3697:             }
                   3698:         }
                   3699:     }
1.800     albertel 3700:     foreach my $group (keys(%grouproles)) {
                   3701:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3702:     }
1.800     albertel 3703:     foreach my $role (keys(%{$allroles})) {
                   3704:         my %thesepriv;
1.941     raeburn  3705:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3706:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3707:             if ($item ne '') {
                   3708:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3709:                 if ($restrictions eq '') {
                   3710:                     $thesepriv{$privilege}='F';
                   3711:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3712:                     $thesepriv{$privilege}.=$restrictions;
                   3713:                 }
                   3714:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3715:             }
                   3716:         }
                   3717:         my $thesestr='';
1.800     albertel 3718:         foreach my $priv (keys(%thesepriv)) {
                   3719: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3720: 	}
                   3721:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3722:     }
                   3723:     return ($author,$adv);
                   3724: }
                   3725: 
1.12      www      3726: # --------------------------------------------------------------- get interface
                   3727: 
                   3728: sub get {
1.131     albertel 3729:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3730:    my $items='';
1.800     albertel 3731:    foreach my $item (@$storearr) {
                   3732:        $items.=&escape($item).'&';
1.191     harris41 3733:    }
1.12      www      3734:    $items=~s/\&$//;
1.620     albertel 3735:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3736:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3737:    my $uhome=&homeserver($uname,$udomain);
                   3738: 
1.133     albertel 3739:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3740:    my @pairs=split(/\&/,$rep);
1.273     albertel 3741:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3742:      return @pairs;
                   3743:    }
1.15      www      3744:    my %returnhash=();
1.42      www      3745:    my $i=0;
1.800     albertel 3746:    foreach my $item (@$storearr) {
                   3747:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3748:       $i++;
1.191     harris41 3749:    }
1.15      www      3750:    return %returnhash;
1.27      www      3751: }
                   3752: 
                   3753: # --------------------------------------------------------------- del interface
                   3754: 
                   3755: sub del {
1.133     albertel 3756:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3757:    my $items='';
1.800     albertel 3758:    foreach my $item (@$storearr) {
                   3759:        $items.=&escape($item).'&';
1.191     harris41 3760:    }
1.27      www      3761:    $items=~s/\&$//;
1.620     albertel 3762:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3763:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3764:    my $uhome=&homeserver($uname,$udomain);
                   3765: 
                   3766:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3767: }
                   3768: 
                   3769: # -------------------------------------------------------------- dump interface
                   3770: 
                   3771: sub dump {
1.755     albertel 3772:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3773:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3774:     if (!$uname) { $uname=$env{'user.name'}; }
                   3775:     my $uhome=&homeserver($uname,$udomain);
                   3776:     if ($regexp) {
                   3777: 	$regexp=&escape($regexp);
                   3778:     } else {
                   3779: 	$regexp='.';
                   3780:     }
                   3781:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3782:     my @pairs=split(/\&/,$rep);
                   3783:     my %returnhash=();
                   3784:     foreach my $item (@pairs) {
                   3785: 	my ($key,$value)=split(/=/,$item,2);
                   3786: 	$key = &unescape($key);
                   3787: 	next if ($key =~ /^error: 2 /);
                   3788: 	$returnhash{$key}=&thaw_unescape($value);
                   3789:     }
                   3790:     return %returnhash;
1.407     www      3791: }
                   3792: 
1.717     albertel 3793: # --------------------------------------------------------- dumpstore interface
                   3794: 
                   3795: sub dumpstore {
                   3796:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3797:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3798:    if (!$uname) { $uname=$env{'user.name'}; }
                   3799:    my $uhome=&homeserver($uname,$udomain);
                   3800:    if ($regexp) {
                   3801:        $regexp=&escape($regexp);
                   3802:    } else {
                   3803:        $regexp='.';
                   3804:    }
                   3805:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3806:    my @pairs=split(/\&/,$rep);
                   3807:    my %returnhash=();
                   3808:    foreach my $item (@pairs) {
                   3809:        my ($key,$value)=split(/=/,$item,2);
                   3810:        next if ($key =~ /^error: 2 /);
                   3811:        $returnhash{$key}=&thaw_unescape($value);
                   3812:    }
                   3813:    return %returnhash;
1.717     albertel 3814: }
                   3815: 
1.407     www      3816: # -------------------------------------------------------------- keys interface
                   3817: 
                   3818: sub getkeys {
                   3819:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3820:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3821:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3822:    my $uhome=&homeserver($uname,$udomain);
                   3823:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3824:    my @keyarray=();
1.800     albertel 3825:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3826:       next if ($key =~ /^error: 2 /);
1.800     albertel 3827:       push(@keyarray,&unescape($key));
1.407     www      3828:    }
                   3829:    return @keyarray;
1.318     matthew  3830: }
                   3831: 
1.319     matthew  3832: # --------------------------------------------------------------- currentdump
                   3833: sub currentdump {
1.328     matthew  3834:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3835:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3836:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3837:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3838:    my $uhome = &homeserver($sname,$sdom);
                   3839:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3840:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3841:    #
1.318     matthew  3842:    my %returnhash=();
1.319     matthew  3843:    #
                   3844:    if ($rep eq "unknown_cmd") { 
                   3845:        # an old lond will not know currentdump
                   3846:        # Do a dump and make it look like a currentdump
1.822     albertel 3847:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3848:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3849:        my %hash = @tmp;
                   3850:        @tmp=();
1.424     matthew  3851:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3852:    } else {
                   3853:        my @pairs=split(/\&/,$rep);
1.800     albertel 3854:        foreach my $pair (@pairs) {
                   3855:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3856:            my ($symb,$param) = split(/:/,$key);
                   3857:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3858:                                                         &thaw_unescape($value);
1.319     matthew  3859:        }
1.191     harris41 3860:    }
1.12      www      3861:    return %returnhash;
1.424     matthew  3862: }
                   3863: 
                   3864: sub convert_dump_to_currentdump{
                   3865:     my %hash = %{shift()};
                   3866:     my %returnhash;
                   3867:     # Code ripped from lond, essentially.  The only difference
                   3868:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3869:     # we might run in to problems with parameter names =~ /^v\./
                   3870:     while (my ($key,$value) = each(%hash)) {
                   3871:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3872: 	$symb  = &unescape($symb);
                   3873: 	$param = &unescape($param);
1.424     matthew  3874:         next if ($v eq 'version' || $symb eq 'keys');
                   3875:         next if (exists($returnhash{$symb}) &&
                   3876:                  exists($returnhash{$symb}->{$param}) &&
                   3877:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3878:         $returnhash{$symb}->{$param}=$value;
                   3879:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3880:     }
                   3881:     #
                   3882:     # Remove all of the keys in the hashes which keep track of
                   3883:     # the version of the parameter.
                   3884:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3885:         # use a foreach because we are going to delete from the hash.
                   3886:         foreach my $key (keys(%$param_hash)) {
                   3887:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3888:         }
                   3889:     }
                   3890:     return \%returnhash;
1.12      www      3891: }
                   3892: 
1.627     albertel 3893: # ------------------------------------------------------ critical inc interface
                   3894: 
                   3895: sub cinc {
                   3896:     return &inc(@_,'critical');
                   3897: }
                   3898: 
1.449     matthew  3899: # --------------------------------------------------------------- inc interface
                   3900: 
                   3901: sub inc {
1.627     albertel 3902:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3904:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3905:     my $uhome=&homeserver($uname,$udomain);
                   3906:     my $items='';
                   3907:     if (! ref($store)) {
                   3908:         # got a single value, so use that instead
                   3909:         $items = &escape($store).'=&';
                   3910:     } elsif (ref($store) eq 'SCALAR') {
                   3911:         $items = &escape($$store).'=&';        
                   3912:     } elsif (ref($store) eq 'ARRAY') {
                   3913:         $items = join('=&',map {&escape($_);} @{$store});
                   3914:     } elsif (ref($store) eq 'HASH') {
                   3915:         while (my($key,$value) = each(%{$store})) {
                   3916:             $items.= &escape($key).'='.&escape($value).'&';
                   3917:         }
                   3918:     }
                   3919:     $items=~s/\&$//;
1.627     albertel 3920:     if ($critical) {
                   3921: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3922:     } else {
                   3923: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3924:     }
1.449     matthew  3925: }
                   3926: 
1.12      www      3927: # --------------------------------------------------------------- put interface
                   3928: 
                   3929: sub put {
1.134     albertel 3930:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3931:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3932:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3933:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3934:    my $items='';
1.800     albertel 3935:    foreach my $item (keys(%$storehash)) {
                   3936:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3937:    }
1.12      www      3938:    $items=~s/\&$//;
1.134     albertel 3939:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3940: }
                   3941: 
1.631     albertel 3942: # ------------------------------------------------------------ newput interface
                   3943: 
                   3944: sub newput {
                   3945:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3946:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3947:    if (!$uname) { $uname=$env{'user.name'}; }
                   3948:    my $uhome=&homeserver($uname,$udomain);
                   3949:    my $items='';
                   3950:    foreach my $key (keys(%$storehash)) {
                   3951:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3952:    }
                   3953:    $items=~s/\&$//;
                   3954:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3955: }
                   3956: 
                   3957: # ---------------------------------------------------------  putstore interface
                   3958: 
1.524     raeburn  3959: sub putstore {
1.715     albertel 3960:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3961:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3962:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3963:    my $uhome=&homeserver($uname,$udomain);
                   3964:    my $items='';
1.715     albertel 3965:    foreach my $key (keys(%$storehash)) {
                   3966:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3967:    }
1.715     albertel 3968:    $items=~s/\&$//;
1.716     albertel 3969:    my $esc_symb=&escape($symb);
                   3970:    my $esc_v=&escape($version);
1.715     albertel 3971:    my $reply =
1.716     albertel 3972:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3973: 	      $uhome);
                   3974:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3975:        # gfall back to way things use to be done
1.715     albertel 3976:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3977: 			    $uname);
1.524     raeburn  3978:    }
1.715     albertel 3979:    return $reply;
                   3980: }
                   3981: 
                   3982: sub old_putstore {
1.716     albertel 3983:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3984:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3985:     if (!$uname) { $uname=$env{'user.name'}; }
                   3986:     my $uhome=&homeserver($uname,$udomain);
                   3987:     my %newstorehash;
1.800     albertel 3988:     foreach my $item (keys(%$storehash)) {
                   3989: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3990: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3991:     }
                   3992:     my $items='';
                   3993:     my %allitems = ();
1.800     albertel 3994:     foreach my $item (keys(%newstorehash)) {
                   3995: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3996: 	    my $key = $1.':keys:'.$2;
                   3997: 	    $allitems{$key} .= $3.':';
                   3998: 	}
1.800     albertel 3999: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4000:     }
1.800     albertel 4001:     foreach my $item (keys(%allitems)) {
                   4002: 	$allitems{$item} =~ s/\:$//;
                   4003: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4004:     }
                   4005:     $items=~s/\&$//;
                   4006:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4007: }
                   4008: 
1.47      www      4009: # ------------------------------------------------------ critical put interface
                   4010: 
                   4011: sub cput {
1.134     albertel 4012:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4014:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4015:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4016:    my $items='';
1.800     albertel 4017:    foreach my $item (keys(%$storehash)) {
                   4018:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4019:    }
1.47      www      4020:    $items=~s/\&$//;
1.134     albertel 4021:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4022: }
                   4023: 
                   4024: # -------------------------------------------------------------- eget interface
                   4025: 
                   4026: sub eget {
1.133     albertel 4027:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4028:    my $items='';
1.800     albertel 4029:    foreach my $item (@$storearr) {
                   4030:        $items.=&escape($item).'&';
1.191     harris41 4031:    }
1.12      www      4032:    $items=~s/\&$//;
1.620     albertel 4033:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4034:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4035:    my $uhome=&homeserver($uname,$udomain);
                   4036:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4037:    my @pairs=split(/\&/,$rep);
                   4038:    my %returnhash=();
1.42      www      4039:    my $i=0;
1.800     albertel 4040:    foreach my $item (@$storearr) {
                   4041:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4042:       $i++;
1.191     harris41 4043:    }
1.12      www      4044:    return %returnhash;
                   4045: }
                   4046: 
1.667     albertel 4047: # ------------------------------------------------------------ tmpput interface
                   4048: sub tmpput {
1.802     raeburn  4049:     my ($storehash,$server,$context)=@_;
1.667     albertel 4050:     my $items='';
1.800     albertel 4051:     foreach my $item (keys(%$storehash)) {
                   4052: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4053:     }
                   4054:     $items=~s/\&$//;
1.802     raeburn  4055:     if (defined($context)) {
                   4056:         $items .= ':'.&escape($context);
                   4057:     }
1.667     albertel 4058:     return &reply("tmpput:$items",$server);
                   4059: }
                   4060: 
                   4061: # ------------------------------------------------------------ tmpget interface
                   4062: sub tmpget {
1.688     albertel 4063:     my ($token,$server)=@_;
                   4064:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4065:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4066:     my %returnhash;
                   4067:     foreach my $item (split(/\&/,$rep)) {
                   4068: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4069:         next if ($key =~ /^error: 2 /);
1.667     albertel 4070: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4071:     }
                   4072:     return %returnhash;
                   4073: }
                   4074: 
1.688     albertel 4075: # ------------------------------------------------------------ tmpget interface
                   4076: sub tmpdel {
                   4077:     my ($token,$server)=@_;
                   4078:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4079:     return &reply("tmpdel:$token",$server);
                   4080: }
                   4081: 
1.765     albertel 4082: # -------------------------------------------------- portfolio access checking
                   4083: 
                   4084: sub portfolio_access {
1.766     albertel 4085:     my ($requrl) = @_;
1.765     albertel 4086:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4087:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4088:     if ($result) {
                   4089:         my %setters;
                   4090:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4091:             my ($startblock,$endblock) =
                   4092:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4093:             if ($startblock && $endblock) {
                   4094:                 return 'B';
                   4095:             }
                   4096:         } else {
                   4097:             my ($startblock,$endblock) =
                   4098:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4099:             if ($startblock && $endblock) {
                   4100:                 return 'B';
                   4101:             }
                   4102:         }
                   4103:     }
1.765     albertel 4104:     if ($result eq 'ok') {
1.766     albertel 4105:        return 'F';
1.765     albertel 4106:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4107:        return 'A';
1.765     albertel 4108:     }
1.766     albertel 4109:     return '';
1.765     albertel 4110: }
                   4111: 
                   4112: sub get_portfolio_access {
1.767     albertel 4113:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4114: 
                   4115:     if (!ref($access_hash)) {
                   4116: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4117: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4118: 						   $file_name);
                   4119: 	$access_hash = $access_controls{$file_name};
                   4120:     }
                   4121: 
1.765     albertel 4122:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4123:     my $now = time;
                   4124:     if (ref($access_hash) eq 'HASH') {
                   4125:         foreach my $key (keys(%{$access_hash})) {
                   4126:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4127:             if ($start > $now) {
                   4128:                 next;
                   4129:             }
                   4130:             if ($end && $end<$now) {
                   4131:                 next;
                   4132:             }
                   4133:             if ($scope eq 'public') {
                   4134:                 $public = $key;
                   4135:                 last;
                   4136:             } elsif ($scope eq 'guest') {
                   4137:                 $guest = $key;
                   4138:             } elsif ($scope eq 'domains') {
                   4139:                 push(@domains,$key);
                   4140:             } elsif ($scope eq 'users') {
                   4141:                 push(@users,$key);
                   4142:             } elsif ($scope eq 'course') {
                   4143:                 push(@courses,$key);
                   4144:             } elsif ($scope eq 'group') {
                   4145:                 push(@groups,$key);
                   4146:             }
                   4147:         }
                   4148:         if ($public) {
                   4149:             return 'ok';
                   4150:         }
                   4151:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4152:             if ($guest) {
                   4153:                 return $guest;
                   4154:             }
                   4155:         } else {
                   4156:             if (@domains > 0) {
                   4157:                 foreach my $domkey (@domains) {
                   4158:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4159:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4160:                             return 'ok';
                   4161:                         }
                   4162:                     }
                   4163:                 }
                   4164:             }
                   4165:             if (@users > 0) {
                   4166:                 foreach my $userkey (@users) {
1.865     raeburn  4167:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4168:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4169:                             if (ref($item) eq 'HASH') {
                   4170:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4171:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4172:                                     return 'ok';
                   4173:                                 }
                   4174:                             }
                   4175:                         }
                   4176:                     } 
1.765     albertel 4177:                 }
                   4178:             }
                   4179:             my %roleshash;
                   4180:             my @courses_and_groups = @courses;
                   4181:             push(@courses_and_groups,@groups); 
                   4182:             if (@courses_and_groups > 0) {
                   4183:                 my (%allgroups,%allroles); 
                   4184:                 my ($start,$end,$role,$sec,$group);
                   4185:                 foreach my $envkey (%env) {
1.811     albertel 4186:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4187:                         my $cid = $2.'_'.$3; 
                   4188:                         if ($1 eq 'gr') {
                   4189:                             $group = $4;
                   4190:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4191:                         } else {
                   4192:                             if ($4 eq '') {
                   4193:                                 $sec = 'none';
                   4194:                             } else {
                   4195:                                 $sec = $4;
                   4196:                             }
                   4197:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4198:                         }
1.811     albertel 4199:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4200:                         my $cid = $2.'_'.$3;
                   4201:                         if ($4 eq '') {
                   4202:                             $sec = 'none';
                   4203:                         } else {
                   4204:                             $sec = $4;
                   4205:                         }
                   4206:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4207:                     }
                   4208:                 }
                   4209:                 if (keys(%allroles) == 0) {
                   4210:                     return;
                   4211:                 }
                   4212:                 foreach my $key (@courses_and_groups) {
                   4213:                     my %content = %{$$access_hash{$key}};
                   4214:                     my $cnum = $content{'number'};
                   4215:                     my $cdom = $content{'domain'};
                   4216:                     my $cid = $cdom.'_'.$cnum;
                   4217:                     if (!exists($allroles{$cid})) {
                   4218:                         next;
                   4219:                     }    
                   4220:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4221:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4222:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4223:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4224:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4225:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4226:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4227:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4228:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4229:                                         if (grep/^all$/,@sections) {
                   4230:                                             return 'ok';
                   4231:                                         } else {
                   4232:                                             if (grep/^$sec$/,@sections) {
                   4233:                                                 return 'ok';
                   4234:                                             }
                   4235:                                         }
                   4236:                                     }
                   4237:                                 }
                   4238:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4239:                                     if (grep/^none$/,@groups) {
                   4240:                                         return 'ok';
                   4241:                                     }
                   4242:                                 } else {
                   4243:                                     if (grep/^all$/,@groups) {
                   4244:                                         return 'ok';
                   4245:                                     } 
                   4246:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4247:                                         if (grep/^$group$/,@groups) {
                   4248:                                             return 'ok';
                   4249:                                         }
                   4250:                                     }
                   4251:                                 } 
                   4252:                             }
                   4253:                         }
                   4254:                     }
                   4255:                 }
                   4256:             }
                   4257:             if ($guest) {
                   4258:                 return $guest;
                   4259:             }
                   4260:         }
                   4261:     }
                   4262:     return;
                   4263: }
                   4264: 
                   4265: sub course_group_datechecker {
                   4266:     my ($dates,$now,$status) = @_;
                   4267:     my ($start,$end) = split(/\./,$dates);
                   4268:     if (!$start && !$end) {
                   4269:         return 'ok';
                   4270:     }
                   4271:     if (grep/^active$/,@{$status}) {
                   4272:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4273:             return 'ok';
                   4274:         }
                   4275:     }
                   4276:     if (grep/^previous$/,@{$status}) {
                   4277:         if ($end > $now ) {
                   4278:             return 'ok';
                   4279:         }
                   4280:     }
                   4281:     if (grep/^future$/,@{$status}) {
                   4282:         if ($start > $now) {
                   4283:             return 'ok';
                   4284:         }
                   4285:     }
                   4286:     return; 
                   4287: }
                   4288: 
                   4289: sub parse_portfolio_url {
                   4290:     my ($url) = @_;
                   4291: 
                   4292:     my ($type,$udom,$unum,$group,$file_name);
                   4293:     
1.823     albertel 4294:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4295: 	$type = 1;
                   4296:         $udom = $1;
                   4297:         $unum = $2;
                   4298:         $file_name = $3;
1.823     albertel 4299:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4300: 	$type = 2;
                   4301:         $udom = $1;
                   4302:         $unum = $2;
                   4303:         $group = $3;
                   4304:         $file_name = $3.'/'.$4;
                   4305:     }
                   4306:     if (wantarray) {
                   4307: 	return ($type,$udom,$unum,$file_name,$group);
                   4308:     }
                   4309:     return $type;
                   4310: }
                   4311: 
                   4312: sub is_portfolio_url {
                   4313:     my ($url) = @_;
                   4314:     return scalar(&parse_portfolio_url($url));
                   4315: }
                   4316: 
1.798     raeburn  4317: sub is_portfolio_file {
                   4318:     my ($file) = @_;
1.820     raeburn  4319:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4320:         return 1;
                   4321:     }
                   4322:     return;
                   4323: }
                   4324: 
                   4325: 
1.341     www      4326: # ---------------------------------------------- Custom access rule evaluation
                   4327: 
                   4328: sub customaccess {
                   4329:     my ($priv,$uri)=@_;
1.807     albertel 4330:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4331:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4332:     $udom = &LONCAPA::clean_domain($udom);
                   4333:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4334:     my $access=0;
1.800     albertel 4335:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4336: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4337: 	if ($type eq 'user') {
                   4338: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4339: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4340: 		if ($tdom) {
                   4341: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4342: 		}
1.896     albertel 4343: 		if ($tuname) {
                   4344: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4345: 		}
                   4346: 		$access=($effect eq 'allow');
                   4347: 		last;
                   4348: 	    }
                   4349: 	} else {
                   4350: 	    if ($role) {
                   4351: 		if ($role ne $urole) { next; }
                   4352: 	    }
                   4353: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4354: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4355: 		if ($tdom) {
                   4356: 		    if ($tdom ne $udom) { next; }
                   4357: 		}
                   4358: 		if ($tcrs) {
                   4359: 		    if ($tcrs ne $ucrs) { next; }
                   4360: 		}
                   4361: 		if ($tsec) {
                   4362: 		    if ($tsec ne $usec) { next; }
                   4363: 		}
                   4364: 		$access=($effect eq 'allow');
                   4365: 		last;
                   4366: 	    }
                   4367: 	    if ($realm eq '' && $role eq '') {
                   4368: 		$access=($effect eq 'allow');
                   4369: 	    }
1.402     bowersj2 4370: 	}
1.341     www      4371:     }
                   4372:     return $access;
                   4373: }
                   4374: 
1.103     harris41 4375: # ------------------------------------------------- Check for a user privilege
1.12      www      4376: 
                   4377: sub allowed {
1.810     raeburn  4378:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4379:     my $ver_orguri=$uri;
1.439     www      4380:     $uri=&deversion($uri);
1.152     www      4381:     my $orguri=$uri;
1.52      www      4382:     $uri=&declutter($uri);
1.809     raeburn  4383: 
1.810     raeburn  4384:     if ($priv eq 'evb') {
                   4385: # Evade communication block restrictions for specified role in a course
                   4386:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4387:             return $1;
                   4388:         } else {
                   4389:             return;
                   4390:         }
                   4391:     }
                   4392: 
1.620     albertel 4393:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4394: # Free bre access to adm and meta resources
1.775     albertel 4395:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4396: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4397: 	&& ($priv eq 'bre')) {
1.14      www      4398: 	return 'F';
1.159     www      4399:     }
                   4400: 
1.545     banghart 4401: # Free bre access to user's own portfolio contents
1.714     raeburn  4402:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4403:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4404: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4405:         my %setters;
                   4406:         my ($startblock,$endblock) = 
                   4407:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4408:         if ($startblock && $endblock) {
                   4409:             return 'B';
                   4410:         } else {
                   4411:             return 'F';
                   4412:         }
1.545     banghart 4413:     }
                   4414: 
1.762     raeburn  4415: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4416:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4417:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4418:         if (exists($env{'request.course.id'})) {
                   4419:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4420:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4421:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4422:                 my $courseprivid=$env{'request.course.id'};
                   4423:                 $courseprivid=~s/\_/\//;
                   4424:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4425:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4426:                     return $1; 
1.762     raeburn  4427:                 } else {
                   4428:                     if ($env{'request.course.sec'}) {
                   4429:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4430:                     }
                   4431:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4432:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4433:                         return $2;
                   4434:                     }
1.714     raeburn  4435:                 }
                   4436:             }
                   4437:         }
                   4438:     }
                   4439: 
1.159     www      4440: # Free bre to public access
                   4441: 
                   4442:     if ($priv eq 'bre') {
1.238     www      4443:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4444: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4445:            return 'F'; 
                   4446:         }
1.238     www      4447:         if ($copyright eq 'priv') {
                   4448:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4449: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4450: 		return '';
                   4451:             }
                   4452:         }
                   4453:         if ($copyright eq 'domain') {
                   4454:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4455: 	    unless (($env{'user.domain'} eq $1) ||
                   4456:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4457: 		return '';
                   4458:             }
1.262     matthew  4459:         }
1.620     albertel 4460:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4461:             # Library role, so allow browsing of resources in this domain.
                   4462:             return 'F';
1.238     www      4463:         }
1.341     www      4464:         if ($copyright eq 'custom') {
                   4465: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4466:         }
1.14      www      4467:     }
1.264     matthew  4468:     # Domain coordinator is trying to create a course
1.620     albertel 4469:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4470:         # uri is the requested domain in this case.
                   4471:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4472:         # a role of dc for the domain in question.
1.620     albertel 4473:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4474:     }
1.29      www      4475: 
1.52      www      4476:     my $thisallowed='';
                   4477:     my $statecond=0;
                   4478:     my $courseprivid='';
                   4479: 
                   4480: # Course
                   4481: 
1.620     albertel 4482:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4483:        $thisallowed.=$1;
                   4484:     }
1.29      www      4485: 
1.52      www      4486: # Domain
                   4487: 
1.620     albertel 4488:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4489:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4490:        $thisallowed.=$1;
                   4491:     }
1.52      www      4492: 
                   4493: # Course: uri itself is a course
1.66      www      4494:     my $courseuri=$uri;
                   4495:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4496:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4497: 
1.620     albertel 4498:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4499:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4500:        $thisallowed.=$1;
                   4501:     }
1.29      www      4502: 
1.665     albertel 4503: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4504: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4505:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4506: 	$thisallowed='';
1.671     raeburn  4507:         my ($match)=&is_on_map($uri);
                   4508:         if ($match) {
                   4509:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4510:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4511:                 $thisallowed.=$1;
                   4512:             }
                   4513:         } else {
1.705     albertel 4514:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4515:             if ($refuri) {
                   4516:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4517:                     $thisallowed='F';
1.671     raeburn  4518:                 } else {
                   4519:                     $refuri=&declutter($refuri);
                   4520:                     my ($match) = &is_on_map($refuri);
                   4521:                     if ($match) {
                   4522:                         $thisallowed='F';
                   4523:                     }
1.669     raeburn  4524:                 }
1.671     raeburn  4525:             }
                   4526:         }
1.314     www      4527:     }
1.492     albertel 4528: 
1.766     albertel 4529:     if ($priv eq 'bre'
                   4530: 	&& $thisallowed ne 'F' 
                   4531: 	&& $thisallowed ne '2'
                   4532: 	&& &is_portfolio_url($uri)) {
                   4533: 	$thisallowed = &portfolio_access($uri);
                   4534:     }
                   4535:     
1.52      www      4536: # Full access at system, domain or course-wide level? Exit.
1.29      www      4537: 
                   4538:     if ($thisallowed=~/F/) {
                   4539: 	return 'F';
                   4540:     }
                   4541: 
1.52      www      4542: # If this is generating or modifying users, exit with special codes
1.29      www      4543: 
1.643     www      4544:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4545: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4546: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4547: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4548: 	    unless ($auname) { return $thisallowed; }
                   4549: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4550: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4551: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4552: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4553: 	}
1.52      www      4554: 	return $thisallowed;
                   4555:     }
                   4556: #
1.103     harris41 4557: # Gathered so far: system, domain and course wide privileges
1.52      www      4558: #
                   4559: # Course: See if uri or referer is an individual resource that is part of 
                   4560: # the course
                   4561: 
1.620     albertel 4562:     if ($env{'request.course.id'}) {
1.232     www      4563: 
1.620     albertel 4564:        $courseprivid=$env{'request.course.id'};
                   4565:        if ($env{'request.course.sec'}) {
                   4566:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4567:        }
                   4568:        $courseprivid=~s/\_/\//;
                   4569:        my $checkreferer=1;
1.232     www      4570:        my ($match,$cond)=&is_on_map($uri);
                   4571:        if ($match) {
                   4572:            $statecond=$cond;
1.620     albertel 4573:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4574:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4575:                $thisallowed.=$1;
                   4576:                $checkreferer=0;
                   4577:            }
1.29      www      4578:        }
1.83      www      4579:        
1.148     www      4580:        if ($checkreferer) {
1.620     albertel 4581: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4582:             unless ($refuri) {
1.800     albertel 4583:                 foreach my $key (keys(%env)) {
                   4584: 		    if ($key=~/^httpref\..*\*/) {
                   4585: 			my $pattern=$key;
1.156     www      4586:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4587:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4588:                         $pattern=~s/\//\\\//g;
1.152     www      4589:                         if ($orguri=~/$pattern/) {
1.800     albertel 4590: 			    $refuri=$env{$key};
1.148     www      4591:                         }
                   4592:                     }
1.191     harris41 4593:                 }
1.148     www      4594:             }
1.232     www      4595: 
1.148     www      4596:          if ($refuri) { 
1.152     www      4597: 	  $refuri=&declutter($refuri);
1.232     www      4598:           my ($match,$cond)=&is_on_map($refuri);
                   4599:             if ($match) {
                   4600:               my $refstatecond=$cond;
1.620     albertel 4601:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4602:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4603:                   $thisallowed.=$1;
1.53      www      4604:                   $uri=$refuri;
                   4605:                   $statecond=$refstatecond;
1.52      www      4606:               }
                   4607:           }
1.148     www      4608:         }
1.29      www      4609:        }
1.52      www      4610:    }
1.29      www      4611: 
1.52      www      4612: #
1.103     harris41 4613: # Gathered now: all privileges that could apply, and condition number
1.52      www      4614: # 
                   4615: #
                   4616: # Full or no access?
                   4617: #
1.29      www      4618: 
1.52      www      4619:     if ($thisallowed=~/F/) {
                   4620: 	return 'F';
                   4621:     }
1.29      www      4622: 
1.52      www      4623:     unless ($thisallowed) {
                   4624:         return '';
                   4625:     }
1.29      www      4626: 
1.52      www      4627: # Restrictions exist, deal with them
                   4628: #
                   4629: #   C:according to course preferences
                   4630: #   R:according to resource settings
                   4631: #   L:unless locked
                   4632: #   X:according to user session state
                   4633: #
                   4634: 
                   4635: # Possibly locked functionality, check all courses
1.54      www      4636: # Locks might take effect only after 10 minutes cache expiration for other
                   4637: # courses, and 2 minutes for current course
1.52      www      4638: 
                   4639:     my $envkey;
                   4640:     if ($thisallowed=~/L/) {
1.620     albertel 4641:         foreach $envkey (keys %env) {
1.54      www      4642:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4643:                my $courseid=$2;
                   4644:                my $roleid=$1.'.'.$2;
1.92      www      4645:                $courseid=~s/^\///;
1.54      www      4646:                my $expiretime=600;
1.620     albertel 4647:                if ($env{'request.role'} eq $roleid) {
1.54      www      4648: 		  $expiretime=120;
                   4649:                }
                   4650: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4651:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4652:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4653: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4654:                }
1.620     albertel 4655:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4656:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4657: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4658:                        &log($env{'user.domain'},$env{'user.name'},
                   4659:                             $env{'user.home'},
1.57      www      4660:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4661:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4662:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4663: 		       return '';
                   4664:                    }
                   4665:                }
1.620     albertel 4666:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4667:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4668: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4669:                        &log($env{'user.domain'},$env{'user.name'},
                   4670:                             $env{'user.home'},
1.57      www      4671:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4672:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4673:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4674: 		       return '';
                   4675:                    }
                   4676:                }
                   4677: 	   }
1.29      www      4678:        }
1.52      www      4679:     }
                   4680:    
                   4681: #
                   4682: # Rest of the restrictions depend on selected course
                   4683: #
                   4684: 
1.620     albertel 4685:     unless ($env{'request.course.id'}) {
1.766     albertel 4686: 	if ($thisallowed eq 'A') {
                   4687: 	    return 'A';
1.814     raeburn  4688:         } elsif ($thisallowed eq 'B') {
                   4689:             return 'B';
1.766     albertel 4690: 	} else {
                   4691: 	    return '1';
                   4692: 	}
1.52      www      4693:     }
1.29      www      4694: 
1.52      www      4695: #
                   4696: # Now user is definitely in a course
                   4697: #
1.53      www      4698: 
                   4699: 
                   4700: # Course preferences
                   4701: 
                   4702:    if ($thisallowed=~/C/) {
1.620     albertel 4703:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4704:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4705:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4706: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4707: 	   if ($priv ne 'pch') { 
                   4708: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4709: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4710: 			$env{'request.course.id'});
                   4711: 	   }
1.237     www      4712:            return '';
                   4713:        }
                   4714: 
1.620     albertel 4715:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4716: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4717: 	   if ($priv ne 'pch') { 
                   4718: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4719: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4720: 			$env{'request.course.id'});
                   4721: 	   }
1.54      www      4722:            return '';
                   4723:        }
1.53      www      4724:    }
                   4725: 
                   4726: # Resource preferences
                   4727: 
                   4728:    if ($thisallowed=~/R/) {
1.620     albertel 4729:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4730:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4731: 	   if ($priv ne 'pch') { 
                   4732: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4733: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4734: 	   }
                   4735: 	   return '';
1.54      www      4736:        }
1.53      www      4737:    }
1.30      www      4738: 
1.246     www      4739: # Restricted by state or randomout?
1.30      www      4740: 
1.52      www      4741:    if ($thisallowed=~/X/) {
1.620     albertel 4742:       if ($env{'acc.randomout'}) {
1.579     albertel 4743: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4744:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4745:             return ''; 
                   4746:          }
1.247     www      4747:       }
                   4748:       if (&condval($statecond)) {
1.52      www      4749: 	 return '2';
                   4750:       } else {
                   4751:          return '';
                   4752:       }
                   4753:    }
1.30      www      4754: 
1.766     albertel 4755:     if ($thisallowed eq 'A') {
                   4756: 	return 'A';
1.814     raeburn  4757:     } elsif ($thisallowed eq 'B') {
                   4758:         return 'B';
1.766     albertel 4759:     }
1.52      www      4760:    return 'F';
1.232     www      4761: }
                   4762: 
1.710     albertel 4763: sub split_uri_for_cond {
                   4764:     my $uri=&deversion(&declutter(shift));
                   4765:     my @uriparts=split(/\//,$uri);
                   4766:     my $filename=pop(@uriparts);
                   4767:     my $pathname=join('/',@uriparts);
                   4768:     return ($pathname,$filename);
                   4769: }
1.232     www      4770: # --------------------------------------------------- Is a resource on the map?
                   4771: 
                   4772: sub is_on_map {
1.710     albertel 4773:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4774:     #Trying to find the conditional for the file
1.620     albertel 4775:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4776: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4777:     if ($match) {
1.289     bowersj2 4778: 	return (1,$1);
                   4779:     } else {
1.434     www      4780: 	return (0,0);
1.289     bowersj2 4781:     }
1.12      www      4782: }
                   4783: 
1.427     www      4784: # --------------------------------------------------------- Get symb from alias
                   4785: 
                   4786: sub get_symb_from_alias {
                   4787:     my $symb=shift;
                   4788:     my ($map,$resid,$url)=&decode_symb($symb);
                   4789: # Already is a symb
                   4790:     if ($url) { return $symb; }
                   4791: # Must be an alias
                   4792:     my $aliassymb='';
                   4793:     my %bighash;
1.620     albertel 4794:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4795:                             &GDBM_READER(),0640)) {
                   4796:         my $rid=$bighash{'mapalias_'.$symb};
                   4797: 	if ($rid) {
                   4798: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4799: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4800: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4801: 	}
                   4802:         untie %bighash;
                   4803:     }
                   4804:     return $aliassymb;
                   4805: }
                   4806: 
1.12      www      4807: # ----------------------------------------------------------------- Define Role
                   4808: 
                   4809: sub definerole {
                   4810:   if (allowed('mcr','/')) {
                   4811:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4812:     foreach my $role (split(':',$sysrole)) {
                   4813: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4814:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4815:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4816: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4817:                return "refused:s:$crole&$cqual"; 
                   4818:             }
                   4819:         }
1.191     harris41 4820:     }
1.800     albertel 4821:     foreach my $role (split(':',$domrole)) {
                   4822: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4823:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4824:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4825: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4826:                return "refused:d:$crole&$cqual"; 
                   4827:             }
                   4828:         }
1.191     harris41 4829:     }
1.800     albertel 4830:     foreach my $role (split(':',$courole)) {
                   4831: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4832:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4833:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4834: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4835:                return "refused:c:$crole&$cqual"; 
                   4836:             }
                   4837:         }
1.191     harris41 4838:     }
1.620     albertel 4839:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4840:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4841: 	        "rolesdef_$rolename=".
                   4842:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4843:     return reply($command,$env{'user.home'});
1.12      www      4844:   } else {
                   4845:     return 'refused';
                   4846:   }
1.105     harris41 4847: }
                   4848: 
                   4849: # ---------------- Make a metadata query against the network of library servers
                   4850: 
                   4851: sub metadata_query {
1.244     matthew  4852:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4853:     my %rhash;
1.845     albertel 4854:     my %libserv = &all_library();
1.244     matthew  4855:     my @server_list = (defined($server_array) ? @$server_array
                   4856:                                               : keys(%libserv) );
                   4857:     for my $server (@server_list) {
1.118     harris41 4858: 	unless ($custom or $customshow) {
                   4859: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4860: 	    $rhash{$server}=$reply;
                   4861: 	}
                   4862: 	else {
                   4863: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4864: 			     &escape($custom).':'.&escape($customshow),
                   4865: 			     $server);
                   4866: 	    $rhash{$server}=$reply;
                   4867: 	}
1.112     harris41 4868:     }
1.118     harris41 4869:     return \%rhash;
1.240     www      4870: }
                   4871: 
                   4872: # ----------------------------------------- Send log queries and wait for reply
                   4873: 
                   4874: sub log_query {
                   4875:     my ($uname,$udom,$query,%filters)=@_;
                   4876:     my $uhome=&homeserver($uname,$udom);
                   4877:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4878:     my $uhost=&hostname($uhome);
1.800     albertel 4879:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4880:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4881:                        $uhome);
1.479     albertel 4882:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4883:     return get_query_reply($queryid);
                   4884: }
                   4885: 
1.818     raeburn  4886: # -------------------------- Update MySQL table for portfolio file
                   4887: 
                   4888: sub update_portfolio_table {
1.821     raeburn  4889:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4890:     my $homeserver = &homeserver($uname,$udom);
                   4891:     my $queryid=
1.821     raeburn  4892:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4893:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4894:     my $reply = &get_query_reply($queryid);
                   4895:     return $reply;
                   4896: }
                   4897: 
1.899     raeburn  4898: # -------------------------- Update MySQL allusers table
                   4899: 
                   4900: sub update_allusers_table {
                   4901:     my ($uname,$udom,$names) = @_;
                   4902:     my $homeserver = &homeserver($uname,$udom);
                   4903:     my $queryid=
                   4904:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4905:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4906:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4907:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4908:                'generation='.&escape($names->{'generation'}).'%%'.
                   4909:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4910:                'id='.&escape($names->{'id'}),$homeserver);
                   4911:     my $reply = &get_query_reply($queryid);
                   4912:     return $reply;
                   4913: }
                   4914: 
1.508     raeburn  4915: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4916: 
                   4917: sub fetch_enrollment_query {
1.511     raeburn  4918:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4919:     my $homeserver;
1.547     raeburn  4920:     my $maxtries = 1;
1.508     raeburn  4921:     if ($context eq 'automated') {
                   4922:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4923:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4924:     } else {
                   4925:         $homeserver = &homeserver($cnum,$dom);
                   4926:     }
1.838     albertel 4927:     my $host=&hostname($homeserver);
1.506     raeburn  4928:     my $cmd = '';
1.800     albertel 4929:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4930:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4931:     }
                   4932:     $cmd =~ s/%%$//;
                   4933:     $cmd = &escape($cmd);
                   4934:     my $query = 'fetchenrollment';
1.620     albertel 4935:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4936:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4937:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4938:         return 'error: '.$queryid;
                   4939:     }
1.506     raeburn  4940:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4941:     my $tries = 1;
                   4942:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4943:         $reply = &get_query_reply($queryid);
                   4944:         $tries ++;
                   4945:     }
1.526     raeburn  4946:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4947:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4948:     } else {
1.901     albertel 4949:         my @responses = split(/:/,$reply);
1.515     raeburn  4950:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4951:             foreach my $line (@responses) {
                   4952:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4953:                 $$replyref{$key} = $value;
                   4954:             }
                   4955:         } else {
1.506     raeburn  4956:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4957:             foreach my $line (@responses) {
                   4958:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4959:                 $$replyref{$key} = $value;
                   4960:                 if ($value > 0) {
1.800     albertel 4961:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4962:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4963:                         my $destname = $pathname.'/'.$filename;
                   4964:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4965:                         if ($xml_classlist =~ /^error/) {
                   4966:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4967:                         } else {
1.506     raeburn  4968:                             if ( open(FILE,">$destname") ) {
                   4969:                                 print FILE &unescape($xml_classlist);
                   4970:                                 close(FILE);
1.526     raeburn  4971:                             } else {
                   4972:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4973:                             }
                   4974:                         }
                   4975:                     }
                   4976:                 }
                   4977:             }
                   4978:         }
                   4979:         return 'ok';
                   4980:     }
                   4981:     return 'error';
                   4982: }
                   4983: 
1.242     www      4984: sub get_query_reply {
                   4985:     my $queryid=shift;
1.240     www      4986:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4987:     my $reply='';
                   4988:     for (1..100) {
                   4989: 	sleep 2;
                   4990:         if (-e $replyfile.'.end') {
1.448     albertel 4991: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4992: 		$reply = join('',<$fh>);
                   4993: 		close($fh);
1.240     www      4994: 	   } else { return 'error: reply_file_error'; }
1.242     www      4995:            return &unescape($reply);
                   4996: 	}
1.240     www      4997:     }
1.242     www      4998:     return 'timeout:'.$queryid;
1.240     www      4999: }
                   5000: 
                   5001: sub courselog_query {
1.241     www      5002: #
                   5003: # possible filters:
                   5004: # url: url or symb
                   5005: # username
                   5006: # domain
                   5007: # action: view, submit, grade
                   5008: # start: timestamp
                   5009: # end: timestamp
                   5010: #
1.240     www      5011:     my (%filters)=@_;
1.620     albertel 5012:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5013:     if ($filters{'url'}) {
                   5014: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5015:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5016:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5017:     }
1.620     albertel 5018:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5019:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5020:     return &log_query($cname,$cdom,'courselog',%filters);
                   5021: }
                   5022: 
                   5023: sub userlog_query {
1.858     raeburn  5024: #
                   5025: # possible filters:
                   5026: # action: log check role
                   5027: # start: timestamp
                   5028: # end: timestamp
                   5029: #
1.240     www      5030:     my ($uname,$udom,%filters)=@_;
                   5031:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5032: }
                   5033: 
1.506     raeburn  5034: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5035: 
                   5036: sub auto_run {
1.508     raeburn  5037:     my ($cnum,$cdom) = @_;
1.876     raeburn  5038:     my $response = 0;
                   5039:     my $settings;
                   5040:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5041:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5042:         $settings = $domconfig{'autoenroll'};
                   5043:         if ($settings->{'run'} eq '1') {
                   5044:             $response = 1;
                   5045:         }
                   5046:     } else {
1.934     raeburn  5047:         my $homeserver;
                   5048:         if (&is_course($cdom,$cnum)) {
                   5049:             $homeserver = &homeserver($cnum,$cdom);
                   5050:         } else {
                   5051:             $homeserver = &domain($cdom,'primary');
                   5052:         }
                   5053:         if ($homeserver ne 'no_host') {
                   5054:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5055:         }
1.876     raeburn  5056:     }
1.506     raeburn  5057:     return $response;
                   5058: }
1.776     albertel 5059: 
1.506     raeburn  5060: sub auto_get_sections {
1.508     raeburn  5061:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5062:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5063:     my @secs = ();
1.511     raeburn  5064:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5065:     unless ($response eq 'refused') {
1.901     albertel 5066:         @secs = split(/:/,$response);
1.506     raeburn  5067:     }
                   5068:     return @secs;
                   5069: }
1.776     albertel 5070: 
1.506     raeburn  5071: sub auto_new_course {
1.508     raeburn  5072:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5073:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5074:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5075:     return $response;
                   5076: }
1.776     albertel 5077: 
1.506     raeburn  5078: sub auto_validate_courseID {
1.508     raeburn  5079:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5080:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5081:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5082:     return $response;
                   5083: }
1.776     albertel 5084: 
1.506     raeburn  5085: sub auto_create_password {
1.873     raeburn  5086:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5087:     my ($homeserver,$response);
1.506     raeburn  5088:     my $create_passwd = 0;
                   5089:     my $authchk = '';
1.873     raeburn  5090:     if ($udom =~ /^$match_domain$/) {
                   5091:         $homeserver = &domain($udom,'primary');
                   5092:     }
                   5093:     if ($homeserver eq '') {
                   5094:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5095:             $homeserver = &homeserver($cnum,$cdom);
                   5096:         }
                   5097:     }
                   5098:     if ($homeserver eq '') {
                   5099:         $authchk = 'nodomain';
1.506     raeburn  5100:     } else {
1.873     raeburn  5101:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5102:         if ($response eq 'refused') {
                   5103:             $authchk = 'refused';
                   5104:         } else {
1.901     albertel 5105:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5106:         }
1.506     raeburn  5107:     }
                   5108:     return ($authparam,$create_passwd,$authchk);
                   5109: }
                   5110: 
1.706     raeburn  5111: sub auto_photo_permission {
                   5112:     my ($cnum,$cdom,$students) = @_;
                   5113:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5114:     my ($outcome,$perm_reqd,$conditions) = 
                   5115: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5116:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5117: 	return (undef,undef);
                   5118:     }
1.706     raeburn  5119:     return ($outcome,$perm_reqd,$conditions);
                   5120: }
                   5121: 
                   5122: sub auto_checkphotos {
                   5123:     my ($uname,$udom,$pid) = @_;
                   5124:     my $homeserver = &homeserver($uname,$udom);
                   5125:     my ($result,$resulttype);
                   5126:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5127: 				   &escape($uname).':'.&escape($pid),
                   5128: 				   $homeserver));
1.709     albertel 5129:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5130: 	return (undef,undef);
                   5131:     }
1.706     raeburn  5132:     if ($outcome) {
                   5133:         ($result,$resulttype) = split(/:/,$outcome);
                   5134:     } 
                   5135:     return ($result,$resulttype);
                   5136: }
                   5137: 
                   5138: sub auto_photochoice {
                   5139:     my ($cnum,$cdom) = @_;
                   5140:     my $homeserver = &homeserver($cnum,$cdom);
                   5141:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5142: 						       &escape($cdom),
                   5143: 						       $homeserver)));
1.709     albertel 5144:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5145: 	return (undef,undef);
                   5146:     }
1.706     raeburn  5147:     return ($update,$comment);
                   5148: }
                   5149: 
                   5150: sub auto_photoupdate {
                   5151:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5152:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5153:     my $host=&hostname($homeserver);
1.706     raeburn  5154:     my $cmd = '';
                   5155:     my $maxtries = 1;
1.800     albertel 5156:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5157:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5158:     }
                   5159:     $cmd =~ s/%%$//;
                   5160:     $cmd = &escape($cmd);
                   5161:     my $query = 'institutionalphotos';
                   5162:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5163:     unless ($queryid=~/^\Q$host\E\_/) {
                   5164:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5165:         return 'error: '.$queryid;
                   5166:     }
                   5167:     my $reply = &get_query_reply($queryid);
                   5168:     my $tries = 1;
                   5169:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5170:         $reply = &get_query_reply($queryid);
                   5171:         $tries ++;
                   5172:     }
                   5173:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5174:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5175:     } else {
                   5176:         my @responses = split(/:/,$reply);
                   5177:         my $outcome = shift(@responses); 
                   5178:         foreach my $item (@responses) {
                   5179:             my ($key,$value) = split(/=/,$item);
                   5180:             $$photo{$key} = $value;
                   5181:         }
                   5182:         return $outcome;
                   5183:     }
                   5184:     return 'error';
                   5185: }
                   5186: 
1.521     raeburn  5187: sub auto_instcode_format {
1.793     albertel 5188:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5189: 	$cat_order) = @_;
1.521     raeburn  5190:     my $courses = '';
1.772     raeburn  5191:     my @homeservers;
1.521     raeburn  5192:     if ($caller eq 'global') {
1.841     albertel 5193: 	my %servers = &get_servers($codedom,'library');
                   5194: 	foreach my $tryserver (keys(%servers)) {
                   5195: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5196: 		push(@homeservers,$tryserver);
                   5197: 	    }
1.584     raeburn  5198:         }
1.521     raeburn  5199:     } else {
1.772     raeburn  5200:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5201:     }
1.793     albertel 5202:     foreach my $code (keys(%{$instcodes})) {
                   5203:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5204:     }
                   5205:     chop($courses);
1.772     raeburn  5206:     my $ok_response = 0;
                   5207:     my $response;
                   5208:     while (@homeservers > 0 && $ok_response == 0) {
                   5209:         my $server = shift(@homeservers); 
                   5210:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5211:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5212:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5213: 		split(/:/,$response);
1.772     raeburn  5214:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5215:             push(@{$codetitles},&str2array($codetitles_str));
                   5216:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5217:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5218:             $ok_response = 1;
                   5219:         }
                   5220:     }
                   5221:     if ($ok_response) {
1.521     raeburn  5222:         return 'ok';
1.772     raeburn  5223:     } else {
                   5224:         return $response;
1.521     raeburn  5225:     }
                   5226: }
                   5227: 
1.792     raeburn  5228: sub auto_instcode_defaults {
                   5229:     my ($domain,$returnhash,$code_order) = @_;
                   5230:     my @homeservers;
1.841     albertel 5231: 
                   5232:     my %servers = &get_servers($domain,'library');
                   5233:     foreach my $tryserver (keys(%servers)) {
                   5234: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5235: 	    push(@homeservers,$tryserver);
                   5236: 	}
1.792     raeburn  5237:     }
1.841     albertel 5238: 
1.792     raeburn  5239:     my $response;
1.841     albertel 5240:     foreach my $server (@homeservers) {
1.792     raeburn  5241:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5242:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5243: 	
                   5244: 	foreach my $pair (split(/\&/,$response)) {
                   5245: 	    my ($name,$value)=split(/\=/,$pair);
                   5246: 	    if ($name eq 'code_order') {
                   5247: 		@{$code_order} = split(/\&/,&unescape($value));
                   5248: 	    } else {
                   5249: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5250: 	    }
                   5251: 	}
                   5252: 	return 'ok';
1.792     raeburn  5253:     }
1.841     albertel 5254: 
                   5255:     return $response;
1.792     raeburn  5256: } 
                   5257: 
1.777     albertel 5258: sub auto_validate_class_sec {
1.918     raeburn  5259:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5260:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5261:     my $ownerlist;
                   5262:     if (ref($owners) eq 'ARRAY') {
                   5263:         $ownerlist = join(',',@{$owners});
                   5264:     } else {
                   5265:         $ownerlist = $owners;
                   5266:     }
1.773     raeburn  5267:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5268:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5269:     return $response;
                   5270: }
                   5271: 
1.679     raeburn  5272: # ------------------------------------------------------- Course Group routines
                   5273: 
                   5274: sub get_coursegroups {
1.809     raeburn  5275:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5276:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5277: }
                   5278: 
1.679     raeburn  5279: sub modify_coursegroup {
                   5280:     my ($cdom,$cnum,$groupsettings) = @_;
                   5281:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5282: }
                   5283: 
1.809     raeburn  5284: sub toggle_coursegroup_status {
                   5285:     my ($cdom,$cnum,$group,$action) = @_;
                   5286:     my ($from_namespace,$to_namespace);
                   5287:     if ($action eq 'delete') {
                   5288:         $from_namespace = 'coursegroups';
                   5289:         $to_namespace = 'deleted_groups';
                   5290:     } else {
                   5291:         $from_namespace = 'deleted_groups';
                   5292:         $to_namespace = 'coursegroups';
                   5293:     }
                   5294:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5295:     if (my $tmp = &error(%curr_group)) {
                   5296:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5297:         return ('read error',$tmp);
                   5298:     } else {
                   5299:         my %savedsettings = %curr_group; 
1.809     raeburn  5300:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5301:         my $deloutcome;
                   5302:         if ($result eq 'ok') {
1.809     raeburn  5303:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5304:         } else {
                   5305:             return ('write error',$result);
                   5306:         }
                   5307:         if ($deloutcome eq 'ok') {
                   5308:             return 'ok';
                   5309:         } else {
                   5310:             return ('delete error',$deloutcome);
                   5311:         }
                   5312:     }
                   5313: }
                   5314: 
1.679     raeburn  5315: sub modify_group_roles {
1.957     raeburn  5316:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5317:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5318:     my $role = 'gr/'.&escape($userprivs);
                   5319:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5320:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5321:     if ($result eq 'ok') {
                   5322:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5323:     }
1.679     raeburn  5324:     return $result;
                   5325: }
                   5326: 
                   5327: sub modify_coursegroup_membership {
                   5328:     my ($cdom,$cnum,$membership) = @_;
                   5329:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5330:     return $result;
                   5331: }
                   5332: 
1.682     raeburn  5333: sub get_active_groups {
                   5334:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5335:     my $now = time;
                   5336:     my %groups = ();
                   5337:     foreach my $key (keys(%env)) {
1.811     albertel 5338:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5339:             my ($start,$end) = split(/\./,$env{$key});
                   5340:             if (($end!=0) && ($end<$now)) { next; }
                   5341:             if (($start!=0) && ($start>$now)) { next; }
                   5342:             if ($1 eq $cdom && $2 eq $cnum) {
                   5343:                 $groups{$3} = $env{$key} ;
                   5344:             }
                   5345:         }
                   5346:     }
                   5347:     return %groups;
                   5348: }
                   5349: 
1.683     raeburn  5350: sub get_group_membership {
                   5351:     my ($cdom,$cnum,$group) = @_;
                   5352:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5353: }
                   5354: 
                   5355: sub get_users_groups {
                   5356:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5357:     my @usersgroups;
1.683     raeburn  5358:     my $cachetime=1800;
                   5359: 
                   5360:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5361:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5362:     if (defined($cached)) {
1.734     albertel 5363:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5364:     } else {  
                   5365:         $grouplist = '';
1.816     raeburn  5366:         my $courseurl = &courseid_to_courseurl($courseid);
                   5367:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5368:         my $access_end = $env{'course.'.$courseid.
                   5369:                               '.default_enrollment_end_date'};
                   5370:         my $now = time;
                   5371:         foreach my $key (keys(%roleshash)) {
                   5372:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5373:                 my $group = $1;
                   5374:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5375:                     my $start = $2;
                   5376:                     my $end = $1;
                   5377:                     if ($start == -1) { next; } # deleted from group
                   5378:                     if (($start!=0) && ($start>$now)) { next; }
                   5379:                     if (($end!=0) && ($end<$now)) {
                   5380:                         if ($access_end && $access_end < $now) {
                   5381:                             if ($access_end - $end < 86400) {
                   5382:                                 push(@usersgroups,$group);
1.733     raeburn  5383:                             }
                   5384:                         }
1.817     raeburn  5385:                         next;
1.733     raeburn  5386:                     }
1.817     raeburn  5387:                     push(@usersgroups,$group);
1.683     raeburn  5388:                 }
                   5389:             }
                   5390:         }
1.817     raeburn  5391:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5392:         $grouplist = join(':',@usersgroups);
                   5393:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5394:     }
1.733     raeburn  5395:     return @usersgroups;
1.683     raeburn  5396: }
                   5397: 
                   5398: sub devalidate_getgroups_cache {
                   5399:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5400:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5401: 
1.683     raeburn  5402:     my $hashid="$udom:$uname:$courseid";
                   5403:     &devalidate_cache_new('getgroups',$hashid);
                   5404: }
                   5405: 
1.12      www      5406: # ------------------------------------------------------------------ Plain Text
                   5407: 
                   5408: sub plaintext {
1.742     raeburn  5409:     my ($short,$type,$cid) = @_;
1.758     albertel 5410:     if ($short =~ /^cr/) {
                   5411: 	return (split('/',$short))[-1];
                   5412:     }
1.742     raeburn  5413:     if (!defined($cid)) {
                   5414:         $cid = $env{'request.course.id'};
                   5415:     }
                   5416:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5417:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5418:                                           '.plaintext'});
                   5419:     }
                   5420:     my %rolenames = (
                   5421:                       Course => 'std',
                   5422:                       Group => 'alt1',
                   5423:                     );
                   5424:     if (defined($type) && 
                   5425:          defined($rolenames{$type}) && 
                   5426:          defined($prp{$short}{$rolenames{$type}})) {
                   5427:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5428:     } else {
                   5429:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5430:     }
1.12      www      5431: }
                   5432: 
                   5433: # ----------------------------------------------------------------- Assign Role
                   5434: 
                   5435: sub assignrole {
1.957     raeburn  5436:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5437:         $context)=@_;
1.21      www      5438:     my $mrole;
                   5439:     if ($role =~ /^cr\//) {
1.393     www      5440:         my $cwosec=$url;
1.811     albertel 5441:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5442: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5443:            &logthis('Refused custom assignrole: '.
                   5444:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5445: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5446:            return 'refused'; 
                   5447:         }
1.21      www      5448:         $mrole='cr';
1.678     raeburn  5449:     } elsif ($role =~ /^gr\//) {
                   5450:         my $cwogrp=$url;
1.811     albertel 5451:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5452:         unless (&allowed('mdg',$cwogrp)) {
                   5453:             &logthis('Refused group assignrole: '.
                   5454:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5455:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5456:             return 'refused';
                   5457:         }
                   5458:         $mrole='gr';
1.21      www      5459:     } else {
1.82      www      5460:         my $cwosec=$url;
1.811     albertel 5461:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5462:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5463:             my $refused;
                   5464:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5465:                 if (!(&allowed('c'.$role,$url))) {
                   5466:                     $refused = 1;
                   5467:                 }
                   5468:             } else {
                   5469:                 $refused = 1;
                   5470:             }
1.947     raeburn  5471:             if ($refused) {
                   5472:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5473:                     $refused = '';
                   5474:                 } else {
                   5475:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5476:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5477: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5478:                     return 'refused';
                   5479:                 }
1.932     raeburn  5480:             }
1.104     www      5481:         }
1.21      www      5482:         $mrole=$role;
                   5483:     }
1.620     albertel 5484:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5485:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5486:     if ($end) { $command.='_'.$end; }
1.21      www      5487:     if ($start) {
                   5488: 	if ($end) { 
1.81      www      5489:            $command.='_'.$start; 
1.21      www      5490:         } else {
1.81      www      5491:            $command.='_0_'.$start;
1.21      www      5492:         }
                   5493:     }
1.739     raeburn  5494:     my $origstart = $start;
                   5495:     my $origend = $end;
1.957     raeburn  5496:     my $delflag;
1.357     www      5497: # actually delete
                   5498:     if ($deleteflag) {
1.373     www      5499: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5500: # modify command to delete the role
1.620     albertel 5501:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5502:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5503: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5504: # set start and finish to negative values for userrolelog
                   5505:            $start=-1;
                   5506:            $end=-1;
1.957     raeburn  5507:            $delflag = 1;
1.357     www      5508:         }
                   5509:     }
                   5510: # send command
1.349     www      5511:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5512: # log new user role if status is ok
1.349     www      5513:     if ($answer eq 'ok') {
1.663     raeburn  5514: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5515: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5516:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5517:         unless ($role =~ /^gr/) {
                   5518:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5519:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5520:         }
1.349     www      5521:     }
                   5522:     return $answer;
1.169     harris41 5523: }
                   5524: 
                   5525: # -------------------------------------------------- Modify user authentication
1.197     www      5526: # Overrides without validation
                   5527: 
1.169     harris41 5528: sub modifyuserauth {
                   5529:     my ($udom,$uname,$umode,$upass)=@_;
                   5530:     my $uhome=&homeserver($uname,$udom);
1.197     www      5531:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5532:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5533:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5534:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5535:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5536: 		     &escape($upass),$uhome);
1.620     albertel 5537:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5538:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5539:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5540:     &log($udom,,$uname,$uhome,
1.620     albertel 5541:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5542:                                      $env{'user.name'}.', '.$umode.
1.197     www      5543:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5544:     unless ($reply eq 'ok') {
1.197     www      5545:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5546: 	return 'error: '.$reply;
                   5547:     }   
1.170     harris41 5548:     return 'ok';
1.80      www      5549: }
                   5550: 
1.81      www      5551: # --------------------------------------------------------------- Modify a user
1.80      www      5552: 
1.81      www      5553: sub modifyuser {
1.206     matthew  5554:     my ($udom,    $uname, $uid,
                   5555:         $umode,   $upass, $first,
                   5556:         $middle,  $last,  $gene,
1.387     www      5557:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5558:     $udom= &LONCAPA::clean_domain($udom);
                   5559:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5560:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5561:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5562: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5563:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5564:                                      ' desiredhome not specified'). 
1.620     albertel 5565:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5566:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5567:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5568: # ----------------------------------------------------------------- Create User
1.406     albertel 5569:     if (($uhome eq 'no_host') && 
                   5570: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5571:         my $unhome='';
1.844     albertel 5572:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5573:             $unhome = $desiredhome;
1.620     albertel 5574: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5575: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5576:         } else { # load balancing routine for determining $unhome
1.81      www      5577:             my $loadm=10000000;
1.841     albertel 5578: 	    my %servers = &get_servers($udom,'library');
                   5579: 	    foreach my $tryserver (keys(%servers)) {
                   5580: 		my $answer=reply('load',$tryserver);
                   5581: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5582: 		    $loadm=$answer;
                   5583: 		    $unhome=$tryserver;
                   5584: 		}
1.80      www      5585: 	    }
                   5586:         }
                   5587:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5588: 	    return 'error: unable to find a home server for '.$uname.
                   5589:                    ' in domain '.$udom;
1.80      www      5590:         }
                   5591:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5592:                          &escape($upass),$unhome);
                   5593: 	unless ($reply eq 'ok') {
                   5594:             return 'error: '.$reply;
                   5595:         }   
1.230     stredwic 5596:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5597:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5598: 	    return 'error: unable verify users home machine.';
1.80      www      5599:         }
1.209     matthew  5600:     }   # End of creation of new user
1.80      www      5601: # ---------------------------------------------------------------------- Add ID
                   5602:     if ($uid) {
                   5603:        $uid=~tr/A-Z/a-z/;
                   5604:        my %uidhash=&idrget($udom,$uname);
1.196     www      5605:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5606:          && (!$forceid)) {
1.80      www      5607: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5608: 	      return 'error: user id "'.$uid.'" does not match '.
                   5609:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5610:           }
                   5611:        } else {
                   5612: 	  &idput($udom,($uname => $uid));
                   5613:        }
                   5614:     }
                   5615: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5616:     my @tmp=&get('environment',
1.899     raeburn  5617: 		   ['firstname','middlename','lastname','generation','id',
                   5618:                     'permanentemail'],
1.134     albertel 5619: 		   $udom,$uname);
1.313     matthew  5620:     my %names;
                   5621:     if ($tmp[0] =~ m/^error:.*/) { 
                   5622:         %names=(); 
                   5623:     } else {
                   5624:         %names = @tmp;
                   5625:     }
1.388     www      5626: #
                   5627: # Make sure to not trash student environment if instructor does not bother
                   5628: # to supply name and email information
                   5629: #
                   5630:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5631:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5632:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5633:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5634:     if ($email) {
                   5635:        $email=~s/[^\w\@\.\-\,]//gs;
                   5636:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5637: 			   $names{'critnotification'} = $email;
                   5638: 			   $names{'permanentemail'} = $email; }
                   5639:     }
1.899     raeburn  5640:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5641:     my $reply = &put('environment', \%names, $udom,$uname);
                   5642:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5643:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5644:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5645:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5646:              $umode.', '.$first.', '.$middle.', '.
                   5647: 	     $last.', '.$gene.' by '.
1.620     albertel 5648:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5649:     return 'ok';
1.80      www      5650: }
                   5651: 
1.81      www      5652: # -------------------------------------------------------------- Modify student
1.80      www      5653: 
1.81      www      5654: sub modifystudent {
                   5655:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5656:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5657:         $selfenroll,$context)=@_;
1.455     albertel 5658:     if (!$cid) {
1.620     albertel 5659: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5660: 	    return 'not_in_class';
                   5661: 	}
1.80      www      5662:     }
                   5663: # --------------------------------------------------------------- Make the user
1.81      www      5664:     my $reply=&modifyuser
1.209     matthew  5665: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5666:          $desiredhome,$email);
1.80      www      5667:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5668:     # This will cause &modify_student_enrollment to get the uid from the
                   5669:     # students environment
                   5670:     $uid = undef if (!$forceid);
1.455     albertel 5671:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5672: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5673:     return $reply;
                   5674: }
                   5675: 
                   5676: sub modify_student_enrollment {
1.957     raeburn  5677:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5678:     my ($cdom,$cnum,$chome);
                   5679:     if (!$cid) {
1.620     albertel 5680: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5681: 	    return 'not_in_class';
                   5682: 	}
1.620     albertel 5683: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5684: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5685:     } else {
                   5686: 	($cdom,$cnum)=split(/_/,$cid);
                   5687:     }
1.620     albertel 5688:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5689:     if (!$chome) {
1.457     raeburn  5690: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5691:     }
1.455     albertel 5692:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5693:     # Make sure the user exists
1.81      www      5694:     my $uhome=&homeserver($uname,$udom);
                   5695:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5696: 	return 'error: no such user';
                   5697:     }
1.297     matthew  5698:     # Get student data if we were not given enough information
                   5699:     if (!defined($first)  || $first  eq '' || 
                   5700:         !defined($last)   || $last   eq '' || 
                   5701:         !defined($uid)    || $uid    eq '' || 
                   5702:         !defined($middle) || $middle eq '' || 
                   5703:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5704:         # They did not supply us with enough data to enroll the student, so
                   5705:         # we need to pick up more information.
1.297     matthew  5706:         my %tmp = &get('environment',
1.294     matthew  5707:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5708:                        ,$udom,$uname);
                   5709: 
1.800     albertel 5710:         #foreach my $key (keys(%tmp)) {
                   5711:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5712:         #}
1.294     matthew  5713:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5714:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5715:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5716:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5717:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5718:     }
1.556     albertel 5719:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5720:     my $reply=cput('classlist',
                   5721: 		   {"$uname:$udom" => 
1.515     raeburn  5722: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5723: 		   $cdom,$cnum);
1.81      www      5724:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5725: 	return 'error: '.$reply;
1.652     albertel 5726:     } else {
                   5727: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5728:     }
1.297     matthew  5729:     # Add student role to user
1.83      www      5730:     my $uurl='/'.$cid;
1.81      www      5731:     $uurl=~s/\_/\//g;
                   5732:     if ($usec) {
                   5733: 	$uurl.='/'.$usec;
                   5734:     }
1.957     raeburn  5735:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5736: }
                   5737: 
1.556     albertel 5738: sub format_name {
                   5739:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5740:     my $name;
                   5741:     if ($first ne 'lastname') {
                   5742: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5743:     } else {
                   5744: 	if ($lastname=~/\S/) {
                   5745: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5746: 	    $name=~s/\s+,/,/;
                   5747: 	} else {
                   5748: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5749: 	}
                   5750:     }
                   5751:     $name=~s/^\s+//;
                   5752:     $name=~s/\s+$//;
                   5753:     $name=~s/\s+/ /g;
                   5754:     return $name;
                   5755: }
                   5756: 
1.84      www      5757: # ------------------------------------------------- Write to course preferences
                   5758: 
                   5759: sub writecoursepref {
                   5760:     my ($courseid,%prefs)=@_;
                   5761:     $courseid=~s/^\///;
                   5762:     $courseid=~s/\_/\//g;
                   5763:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5764:     my $chome=homeserver($cnum,$cdomain);
                   5765:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5766: 	return 'error: no such course';
                   5767:     }
                   5768:     my $cstring='';
1.800     albertel 5769:     foreach my $pref (keys(%prefs)) {
                   5770: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5771:     }
1.84      www      5772:     $cstring=~s/\&$//;
                   5773:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5774: }
                   5775: 
                   5776: # ---------------------------------------------------------- Make/modify course
                   5777: 
                   5778: sub createcourse {
1.741     raeburn  5779:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5780:         $course_owner,$crstype)=@_;
1.84      www      5781:     $url=&declutter($url);
                   5782:     my $cid='';
1.264     matthew  5783:     unless (&allowed('ccc',$udom)) {
1.84      www      5784:         return 'refused';
                   5785:     }
                   5786: # ------------------------------------------------------------------- Create ID
1.674     www      5787:    my $uname=int(1+rand(9)).
                   5788:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5789:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5790:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5791: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5792:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5793:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5794:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5795:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5796:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5797:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5798:            return 'error: unable to generate unique course-ID';
                   5799:        } 
                   5800:    }
1.264     matthew  5801: # ------------------------------------------------ Check supplied server name
1.620     albertel 5802:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5803:     if (! &is_library($course_server)) {
1.264     matthew  5804:         return 'error:bad server name '.$course_server;
                   5805:     }
1.84      www      5806: # ------------------------------------------------------------- Make the course
                   5807:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5808:                       $course_server);
1.84      www      5809:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5810:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5811:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5812: 	return 'error: no such course';
                   5813:     }
1.271     www      5814: # ----------------------------------------------------------------- Course made
1.516     raeburn  5815: # log existence
1.918     raeburn  5816:     my $newcourse = {
                   5817:                     $udom.'_'.$uname => {
1.921     raeburn  5818:                                      description => $description,
                   5819:                                      inst_code   => $inst_code,
                   5820:                                      owner       => $course_owner,
                   5821:                                      type        => $crstype,
1.918     raeburn  5822:                                                 },
                   5823:                     };
1.921     raeburn  5824:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5825: # set toplevel url
1.271     www      5826:     my $topurl=$url;
                   5827:     unless ($nonstandard) {
                   5828: # ------------------------------------------ For standard courses, make top url
                   5829:         my $mapurl=&clutter($url);
1.278     www      5830:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5831:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5832: <map>
                   5833: <resource id="1" type="start"></resource>
                   5834: <resource id="2" src="$mapurl"></resource>
                   5835: <resource id="3" type="finish"></resource>
                   5836: <link index="1" from="1" to="2"></link>
                   5837: <link index="2" from="2" to="3"></link>
                   5838: </map>
                   5839: ENDINITMAP
                   5840:         $topurl=&declutter(
1.638     albertel 5841:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5842:                           );
                   5843:     }
                   5844: # ----------------------------------------------------------- Write preferences
1.84      www      5845:     &writecoursepref($udom.'_'.$uname,
                   5846:                      ('description' => $description,
1.271     www      5847:                       'url'         => $topurl));
1.84      www      5848:     return '/'.$udom.'/'.$uname;
                   5849: }
                   5850: 
1.813     albertel 5851: sub is_course {
                   5852:     my ($cdom,$cnum) = @_;
                   5853:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5854: 				undef,'.');
1.813     albertel 5855:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5856:         return 1;
                   5857:     }
                   5858:     return 0;
                   5859: }
                   5860: 
1.21      www      5861: # ---------------------------------------------------------- Assign Custom Role
                   5862: 
                   5863: sub assigncustomrole {
1.957     raeburn  5864:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5865:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  5866:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      5867: }
                   5868: 
                   5869: # ----------------------------------------------------------------- Revoke Role
                   5870: 
                   5871: sub revokerole {
1.957     raeburn  5872:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5873:     my $now=time;
1.957     raeburn  5874:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag,$selfenroll,$context);
1.21      www      5875: }
                   5876: 
                   5877: # ---------------------------------------------------------- Revoke Custom Role
                   5878: 
                   5879: sub revokecustomrole {
1.957     raeburn  5880:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5881:     my $now=time;
1.357     www      5882:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  5883:            $deleteflag,$selfenroll,$context);
1.17      www      5884: }
                   5885: 
1.533     banghart 5886: # ------------------------------------------------------------ Disk usage
1.535     albertel 5887: sub diskusage {
1.955     raeburn  5888:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   5889:     $directorypath =~ s/\/$//;
                   5890:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   5891:                        .&escape($getpropath).':'.&escape($uname).':'
                   5892:                        .&escape($udom),homeserver($uname,$udom));
                   5893:     if ($listing eq 'unknown_cmd') {
                   5894:         if ($getpropath) {
                   5895:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   5896:         }
                   5897:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   5898:     }
1.514     albertel 5899:     return $listing;
1.512     banghart 5900: }
                   5901: 
1.566     banghart 5902: sub is_locked {
                   5903:     my ($file_name, $domain, $user) = @_;
                   5904:     my @check;
                   5905:     my $is_locked;
                   5906:     push @check, $file_name;
1.613     albertel 5907:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5908: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5909:     my ($tmp)=keys(%locked);
                   5910:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5911:     
1.566     banghart 5912:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5913:         $is_locked = 'false';
                   5914:         foreach my $entry (@{$locked{$file_name}}) {
                   5915:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5916:                $is_locked = 'true';
                   5917:                last;
1.745     raeburn  5918:            }
                   5919:        }
1.566     banghart 5920:     } else {
                   5921:         $is_locked = 'false';
                   5922:     }
                   5923: }
                   5924: 
1.759     albertel 5925: sub declutter_portfile {
                   5926:     my ($file) = @_;
1.833     albertel 5927:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5928:     return $file;
                   5929: }
                   5930: 
1.559     banghart 5931: # ------------------------------------------------------------- Mark as Read Only
                   5932: 
                   5933: sub mark_as_readonly {
                   5934:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5935:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5936:     my ($tmp)=keys(%current_permissions);
                   5937:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5938:     foreach my $file (@{$files}) {
1.759     albertel 5939: 	$file = &declutter_portfile($file);
1.561     banghart 5940:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5941:     }
1.613     albertel 5942:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5943:     return;
                   5944: }
                   5945: 
1.572     banghart 5946: # ------------------------------------------------------------Save Selected Files
                   5947: 
                   5948: sub save_selected_files {
                   5949:     my ($user, $path, @files) = @_;
                   5950:     my $filename = $user."savedfiles";
1.573     banghart 5951:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5952:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5953:     foreach my $file (@files) {
1.620     albertel 5954:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5955:     }
                   5956:     foreach my $file (@other_files) {
1.574     banghart 5957:         print (OUT $file."\n");
1.572     banghart 5958:     }
1.574     banghart 5959:     close (OUT);
1.572     banghart 5960:     return 'ok';
                   5961: }
                   5962: 
1.574     banghart 5963: sub clear_selected_files {
                   5964:     my ($user) = @_;
                   5965:     my $filename = $user."savedfiles";
                   5966:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5967:     print (OUT undef);
                   5968:     close (OUT);
                   5969:     return ("ok");    
                   5970: }
                   5971: 
1.572     banghart 5972: sub files_in_path {
                   5973:     my ($user, $path) = @_;
                   5974:     my $filename = $user."savedfiles";
                   5975:     my %return_files;
1.574     banghart 5976:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5977:     while (my $line_in = <IN>) {
1.574     banghart 5978:         chomp ($line_in);
                   5979:         my @paths_and_file = split (m!/!, $line_in);
                   5980:         my $file_part = pop (@paths_and_file);
                   5981:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5982:         $path_part.='/';
                   5983:         my $path_and_file = $path_part.$file_part;
                   5984:         if ($path_part eq $path) {
                   5985:             $return_files{$file_part}= 'selected';
                   5986:         }
                   5987:     }
1.574     banghart 5988:     close (IN);
                   5989:     return (\%return_files);
1.572     banghart 5990: }
                   5991: 
                   5992: # called in portfolio select mode, to show files selected NOT in current directory
                   5993: sub files_not_in_path {
                   5994:     my ($user, $path) = @_;
                   5995:     my $filename = $user."savedfiles";
                   5996:     my @return_files;
                   5997:     my $path_part;
1.800     albertel 5998:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5999:     while (my $line = <IN>) {
1.572     banghart 6000:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6001:         my @paths_and_file = split(m|/|, $line);
                   6002:         my $file_part = pop(@paths_and_file);
                   6003:         chomp($file_part);
                   6004:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6005:         $path_part .= '/';
                   6006:         my $path_and_file = $path_part.$file_part;
                   6007:         if ($path_part ne $path) {
1.800     albertel 6008:             push(@return_files, ($path_and_file));
1.572     banghart 6009:         }
                   6010:     }
1.800     albertel 6011:     close(OUT);
1.574     banghart 6012:     return (@return_files);
1.572     banghart 6013: }
                   6014: 
1.745     raeburn  6015: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6016: 
1.745     raeburn  6017: sub get_portfile_permissions {
                   6018:     my ($domain,$user) = @_;
1.613     albertel 6019:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6020:     my ($tmp)=keys(%current_permissions);
                   6021:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6022:     return \%current_permissions;
                   6023: }
                   6024: 
                   6025: #---------------------------------------------Get portfolio file access controls
                   6026: 
1.749     raeburn  6027: sub get_access_controls {
1.745     raeburn  6028:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6029:     my %access;
                   6030:     my $real_file = $file;
                   6031:     $file =~ s/\.meta$//;
1.745     raeburn  6032:     if (defined($file)) {
1.749     raeburn  6033:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6034:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6035:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6036:             }
                   6037:         }
1.745     raeburn  6038:     } else {
1.749     raeburn  6039:         foreach my $key (keys(%{$current_permissions})) {
                   6040:             if ($key =~ /\0accesscontrol$/) {
                   6041:                 if (defined($group)) {
                   6042:                     if ($key !~ m-^\Q$group\E/-) {
                   6043:                         next;
                   6044:                     }
                   6045:                 }
                   6046:                 my ($fullpath) = split(/\0/,$key);
                   6047:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6048:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6049:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6050:                     }
                   6051:                 }
                   6052:             }
                   6053:         }
                   6054:     }
                   6055:     return %access;
                   6056: }
                   6057: 
                   6058: sub modify_access_controls {
                   6059:     my ($file_name,$changes,$domain,$user)=@_;
                   6060:     my ($outcome,$deloutcome);
                   6061:     my %store_permissions;
                   6062:     my %new_values;
                   6063:     my %new_control;
                   6064:     my %translation;
                   6065:     my @deletions = ();
                   6066:     my $now = time;
                   6067:     if (exists($$changes{'activate'})) {
                   6068:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6069:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6070:             my $numnew = scalar(@newitems);
                   6071:             for (my $i=0; $i<$numnew; $i++) {
                   6072:                 my $newkey = $newitems[$i];
                   6073:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6074:                 if ($newkey =~ /^\d+:/) { 
                   6075:                     $newkey =~ s/^(\d+)/$newid/;
                   6076:                     $translation{$1} = $newid;
                   6077:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6078:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6079:                     $translation{$1} = $newid;
                   6080:                 }
1.749     raeburn  6081:                 $new_values{$file_name."\0".$newkey} = 
                   6082:                                           $$changes{'activate'}{$newitems[$i]};
                   6083:                 $new_control{$newkey} = $now;
                   6084:             }
                   6085:         }
                   6086:     }
                   6087:     my %todelete;
                   6088:     my %changed_items;
                   6089:     foreach my $action ('delete','update') {
                   6090:         if (exists($$changes{$action})) {
                   6091:             if (ref($$changes{$action}) eq 'HASH') {
                   6092:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6093:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6094:                     if ($action eq 'delete') { 
                   6095:                         $todelete{$itemnum} = 1;
                   6096:                     } else {
                   6097:                         $changed_items{$itemnum} = $key;
                   6098:                     }
                   6099:                 }
1.745     raeburn  6100:             }
                   6101:         }
1.749     raeburn  6102:     }
                   6103:     # get lock on access controls for file.
                   6104:     my $lockhash = {
                   6105:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6106:                                                        ':'.$env{'user.domain'},
                   6107:                    }; 
                   6108:     my $tries = 0;
                   6109:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6110:    
                   6111:     while (($gotlock ne 'ok') && $tries <3) {
                   6112:         $tries ++;
                   6113:         sleep 1;
                   6114:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6115:     }
                   6116:     if ($gotlock eq 'ok') {
                   6117:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6118:         my ($tmp)=keys(%curr_permissions);
                   6119:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6120:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6121:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6122:             if (ref($curr_controls) eq 'HASH') {
                   6123:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6124:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6125:                     if (defined($todelete{$itemnum})) {
                   6126:                         push(@deletions,$file_name."\0".$control_item);
                   6127:                     } else {
                   6128:                         if (defined($changed_items{$itemnum})) {
                   6129:                             $new_control{$changed_items{$itemnum}} = $now;
                   6130:                             push(@deletions,$file_name."\0".$control_item);
                   6131:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6132:                         } else {
                   6133:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6134:                         }
                   6135:                     }
1.745     raeburn  6136:                 }
                   6137:             }
                   6138:         }
1.749     raeburn  6139:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6140:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6141:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6142:         #  remove lock
                   6143:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6144:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6145:         my ($file,$group);
                   6146:         if (&is_course($domain,$user)) {
                   6147:             ($group,$file) = split(/\//,$file_name,2);
                   6148:         } else {
                   6149:             $file = $file_name;
                   6150:         }
                   6151:         my $sqlresult =
                   6152:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6153:                                     $group);
1.749     raeburn  6154:     } else {
                   6155:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6156:     }
1.749     raeburn  6157:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6158: }
                   6159: 
1.827     raeburn  6160: sub make_public_indefinitely {
                   6161:     my ($requrl) = @_;
                   6162:     my $now = time;
                   6163:     my $action = 'activate';
                   6164:     my $aclnum = 0;
                   6165:     if (&is_portfolio_url($requrl)) {
                   6166:         my (undef,$udom,$unum,$file_name,$group) =
                   6167:             &parse_portfolio_url($requrl);
                   6168:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6169:         my %access_controls = &get_access_controls($current_perms,
                   6170:                                                    $group,$file_name);
                   6171:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6172:             my ($num,$scope,$end,$start) = 
                   6173:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6174:             if ($scope eq 'public') {
                   6175:                 if ($start <= $now && $end == 0) {
                   6176:                     $action = 'none';
                   6177:                 } else {
                   6178:                     $action = 'update';
                   6179:                     $aclnum = $num;
                   6180:                 }
                   6181:                 last;
                   6182:             }
                   6183:         }
                   6184:         if ($action eq 'none') {
                   6185:              return 'ok';
                   6186:         } else {
                   6187:             my %changes;
                   6188:             my $newend = 0;
                   6189:             my $newstart = $now;
                   6190:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6191:             $changes{$action}{$newkey} = {
                   6192:                 type => 'public',
                   6193:                 time => {
                   6194:                     start => $newstart,
                   6195:                     end   => $newend,
                   6196:                 },
                   6197:             };
                   6198:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6199:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6200:             return $outcome;
                   6201:         }
                   6202:     } else {
                   6203:         return 'invalid';
                   6204:     }
                   6205: }
                   6206: 
1.745     raeburn  6207: #------------------------------------------------------Get Marked as Read Only
                   6208: 
                   6209: sub get_marked_as_readonly {
                   6210:     my ($domain,$user,$what,$group) = @_;
                   6211:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6212:     my @readonly_files;
1.629     banghart 6213:     my $cmp1=$what;
                   6214:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6215:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6216:         if (defined($group)) {
                   6217:             if ($file_name !~ m-^\Q$group\E/-) {
                   6218:                 next;
                   6219:             }
                   6220:         }
1.561     banghart 6221:         if (ref($value) eq "ARRAY"){
                   6222:             foreach my $stored_what (@{$value}) {
1.629     banghart 6223:                 my $cmp2=$stored_what;
1.759     albertel 6224:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6225:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6226:                 }
1.629     banghart 6227:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6228:                     push(@readonly_files, $file_name);
1.745     raeburn  6229:                     last;
1.563     banghart 6230:                 } elsif (!defined($what)) {
                   6231:                     push(@readonly_files, $file_name);
1.745     raeburn  6232:                     last;
1.561     banghart 6233:                 }
                   6234:             }
1.745     raeburn  6235:         }
1.561     banghart 6236:     }
                   6237:     return @readonly_files;
                   6238: }
1.577     banghart 6239: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6240: 
1.577     banghart 6241: sub get_marked_as_readonly_hash {
1.745     raeburn  6242:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6243:     my %readonly_files;
1.745     raeburn  6244:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6245:         if (defined($group)) {
                   6246:             if ($file_name !~ m-^\Q$group\E/-) {
                   6247:                 next;
                   6248:             }
                   6249:         }
1.577     banghart 6250:         if (ref($value) eq "ARRAY"){
                   6251:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6252:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6253:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6254:                         if ($lock_descriptor eq 'graded') {
                   6255:                             $readonly_files{$file_name} = 'graded';
                   6256:                         } elsif ($lock_descriptor eq 'handback') {
                   6257:                             $readonly_files{$file_name} = 'handback';
                   6258:                         } else {
                   6259:                             if (!exists($readonly_files{$file_name})) {
                   6260:                                 $readonly_files{$file_name} = 'locked';
                   6261:                             }
                   6262:                         }
1.745     raeburn  6263:                     }
1.750     banghart 6264:                 } 
1.577     banghart 6265:             }
                   6266:         } 
                   6267:     }
                   6268:     return %readonly_files;
                   6269: }
1.559     banghart 6270: # ------------------------------------------------------------ Unmark as Read Only
                   6271: 
                   6272: sub unmark_as_readonly {
1.629     banghart 6273:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6274:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6275:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6276:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6277:     my $symb_crs = $what;
                   6278:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6279:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6280:     my ($tmp)=keys(%current_permissions);
                   6281:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6282:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6283:     foreach my $file (@readonly_files) {
1.759     albertel 6284: 	my $clean_file = &declutter_portfile($file);
                   6285: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6286: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6287:         my @new_locks;
                   6288:         my @del_keys;
                   6289:         if (ref($current_locks) eq "ARRAY"){
                   6290:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6291:                 my $compare=$locker;
1.749     raeburn  6292:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6293:                     $compare=join('',@{$locker});
1.746     raeburn  6294:                     if ($compare ne $symb_crs) {
                   6295:                         push(@new_locks, $locker);
                   6296:                     }
1.563     banghart 6297:                 }
                   6298:             }
1.650     albertel 6299:             if (scalar(@new_locks) > 0) {
1.563     banghart 6300:                 $current_permissions{$file} = \@new_locks;
                   6301:             } else {
                   6302:                 push(@del_keys, $file);
1.613     albertel 6303:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6304:                 delete($current_permissions{$file});
1.563     banghart 6305:             }
                   6306:         }
1.561     banghart 6307:     }
1.613     albertel 6308:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6309:     return;
                   6310: }
1.512     banghart 6311: 
1.17      www      6312: # ------------------------------------------------------------ Directory lister
                   6313: 
                   6314: sub dirlist {
1.955     raeburn  6315:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6316:     $uri=~s/^\///;
                   6317:     $uri=~s/\/$//;
1.253     stredwic 6318:     my ($udom, $uname);
1.955     raeburn  6319:     if ($getuserdir) {
1.253     stredwic 6320:         $udom = $userdomain;
                   6321:         $uname = $username;
1.955     raeburn  6322:     } else {
                   6323:         (undef,$udom,$uname)=split(/\//,$uri);
                   6324:         if(defined($userdomain)) {
                   6325:             $udom = $userdomain;
                   6326:         }
                   6327:         if(defined($username)) {
                   6328:             $uname = $username;
                   6329:         }
1.253     stredwic 6330:     }
1.955     raeburn  6331:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6332: 
1.955     raeburn  6333:     $dirRoot = $perlvar{'lonDocRoot'};
                   6334:     if (defined($getpropath)) {
                   6335:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6336:         $dirRoot =~ s/\/$//;
1.955     raeburn  6337:     } elsif (defined($getuserdir)) {
                   6338:         my $subdir=$uname.'__';
                   6339:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6340:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6341:                    ."/$udom/$subdir/$uname";
                   6342:     } elsif (defined($alternateRoot)) {
                   6343:         $dirRoot = $alternateRoot;
1.751     banghart 6344:     }
1.253     stredwic 6345: 
                   6346:     if($udom) {
                   6347:         if($uname) {
1.955     raeburn  6348:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6349:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6350:                               .':'.&escape($uname).':'.&escape($udom),
                   6351:                               &homeserver($uname,$udom));
                   6352:             if ($listing eq 'unknown_cmd') {
                   6353:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6354:                                   &homeserver($uname,$udom));
                   6355:             } else {
                   6356:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6357:             }
1.605     matthew  6358:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6359:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6360: 				  &homeserver($uname,$udom));
1.605     matthew  6361:                 @listing_results = split(/:/,$listing);
                   6362:             } else {
                   6363:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6364:             }
                   6365:             return @listing_results;
1.955     raeburn  6366:         } elsif(!$alternateRoot) {
1.800     albertel 6367:             my %allusers;
1.841     albertel 6368: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6369:  	    foreach my $tryserver (keys(%servers)) {
                   6370:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6371:                                   &escape($udom),$tryserver);
                   6372:                 if ($listing eq 'unknown_cmd') {
                   6373: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6374: 				      $udom, $tryserver);
                   6375:                 } else {
                   6376:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6377:                 }
1.841     albertel 6378: 		if ($listing eq 'unknown_cmd') {
                   6379: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6380: 				      $udom, $tryserver);
                   6381: 		    @listing_results = split(/:/,$listing);
                   6382: 		} else {
                   6383: 		    @listing_results =
                   6384: 			map { &unescape($_); } split(/:/,$listing);
                   6385: 		}
                   6386: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6387: 		    $listing_results[0] ne 'empty'       &&
                   6388: 		    $listing_results[0] ne 'con_lost') {
                   6389: 		    foreach my $line (@listing_results) {
                   6390: 			my ($entry) = split(/&/,$line,2);
                   6391: 			$allusers{$entry} = 1;
                   6392: 		    }
                   6393: 		}
1.253     stredwic 6394:             }
                   6395:             my $alluserstr='';
1.800     albertel 6396:             foreach my $user (sort(keys(%allusers))) {
                   6397:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6398:             }
                   6399:             $alluserstr=~s/:$//;
                   6400:             return split(/:/,$alluserstr);
                   6401:         } else {
1.800     albertel 6402:             return ('missing user name');
1.253     stredwic 6403:         }
1.955     raeburn  6404:     } elsif(!defined($getpropath)) {
1.841     albertel 6405:         my @all_domains = sort(&all_domains());
1.955     raeburn  6406:         foreach my $domain (@all_domains) {
                   6407:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6408:         }
                   6409:         return @all_domains;
                   6410:     } else {
1.800     albertel 6411:         return ('missing domain');
1.275     stredwic 6412:     }
                   6413: }
                   6414: 
                   6415: # --------------------------------------------- GetFileTimestamp
                   6416: # This function utilizes dirlist and returns the date stamp for
                   6417: # when it was last modified.  It will also return an error of -1
                   6418: # if an error occurs
                   6419: 
                   6420: sub GetFileTimestamp {
1.955     raeburn  6421:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6422:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6423:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6424:     my ($fileStat) = 
                   6425:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6426:                                  undef,$getuserdir);
1.275     stredwic 6427:     my @stats = split('&', $fileStat);
                   6428:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6429:         # @stats contains first the filename, then the stat output
                   6430:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6431:     } else {
                   6432:         return -1;
1.253     stredwic 6433:     }
1.26      www      6434: }
                   6435: 
1.712     albertel 6436: sub stat_file {
                   6437:     my ($uri) = @_;
1.787     albertel 6438:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6439: 
1.955     raeburn  6440:     my ($udom,$uname,$file);
1.712     albertel 6441:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6442: 	($udom,$uname,$file) =
1.811     albertel 6443: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6444: 	$file = 'userfiles/'.$file;
                   6445:     }
                   6446:     if ($uri =~ m-^/res/-) {
                   6447: 	($udom,$uname) = 
1.807     albertel 6448: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6449: 	$file = $uri;
                   6450:     }
                   6451: 
                   6452:     if (!$udom || !$uname || !$file) {
                   6453: 	# unable to handle the uri
                   6454: 	return ();
                   6455:     }
1.956     raeburn  6456:     my $getpropath;
                   6457:     if ($file =~ /^userfiles\//) {
                   6458:         $getpropath = 1;
                   6459:     }
1.955     raeburn  6460:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6461:     my @stats = split('&', $result);
1.721     banghart 6462:     
1.712     albertel 6463:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6464: 	shift(@stats); #filename is first
                   6465: 	return @stats;
                   6466:     }
                   6467:     return ();
                   6468: }
                   6469: 
1.26      www      6470: # -------------------------------------------------------- Value of a Condition
                   6471: 
1.713     albertel 6472: # gets the value of a specific preevaluated condition
                   6473: #    stored in the string  $env{user.state.<cid>}
                   6474: # or looks up a condition reference in the bighash and if if hasn't
                   6475: # already been evaluated recurses into docondval to get the value of
                   6476: # the condition, then memoizing it to 
                   6477: #   $env{user.state.<cid>.<condition>}
1.40      www      6478: sub directcondval {
                   6479:     my $number=shift;
1.620     albertel 6480:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6481: 	&Apache::lonuserstate::evalstate();
                   6482:     }
1.713     albertel 6483:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6484: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6485:     } elsif ($number =~ /^_/) {
                   6486: 	my $sub_condition;
                   6487: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6488: 		&GDBM_READER(),0640)) {
                   6489: 	    $sub_condition=$bighash{'conditions'.$number};
                   6490: 	    untie(%bighash);
                   6491: 	}
                   6492: 	my $value = &docondval($sub_condition);
1.949     raeburn  6493: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6494: 	return $value;
                   6495:     }
1.620     albertel 6496:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6497:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6498:     } else {
                   6499:        return 2;
                   6500:     }
                   6501: }
                   6502: 
1.713     albertel 6503: # get the collection of conditions for this resource
1.26      www      6504: sub condval {
                   6505:     my $condidx=shift;
1.54      www      6506:     my $allpathcond='';
1.713     albertel 6507:     foreach my $cond (split(/\|/,$condidx)) {
                   6508: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6509: 	    $allpathcond.=
                   6510: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6511: 	}
1.191     harris41 6512:     }
1.54      www      6513:     $allpathcond=~s/\|$//;
1.713     albertel 6514:     return &docondval($allpathcond);
                   6515: }
                   6516: 
                   6517: #evaluates an expression of conditions
                   6518: sub docondval {
                   6519:     my ($allpathcond) = @_;
                   6520:     my $result=0;
                   6521:     if ($env{'request.course.id'}
                   6522: 	&& defined($allpathcond)) {
                   6523: 	my $operand='|';
                   6524: 	my @stack;
                   6525: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6526: 	    if ($chunk eq '(') {
                   6527: 		push @stack,($operand,$result);
                   6528: 	    } elsif ($chunk eq ')') {
                   6529: 		my $before=pop @stack;
                   6530: 		if (pop @stack eq '&') {
                   6531: 		    $result=$result>$before?$before:$result;
                   6532: 		} else {
                   6533: 		    $result=$result>$before?$result:$before;
                   6534: 		}
                   6535: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6536: 		$operand=$chunk;
                   6537: 	    } else {
                   6538: 		my $new=directcondval($chunk);
                   6539: 		if ($operand eq '&') {
                   6540: 		    $result=$result>$new?$new:$result;
                   6541: 		} else {
                   6542: 		    $result=$result>$new?$result:$new;
                   6543: 		}
                   6544: 	    }
                   6545: 	}
1.26      www      6546:     }
                   6547:     return $result;
1.421     albertel 6548: }
                   6549: 
                   6550: # ---------------------------------------------------- Devalidate courseresdata
                   6551: 
                   6552: sub devalidatecourseresdata {
                   6553:     my ($coursenum,$coursedomain)=@_;
                   6554:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6555:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6556: }
                   6557: 
1.763     www      6558: 
1.200     www      6559: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6560: #
                   6561: #  Parameters:
                   6562: #      $coursenum    - Number of the course.
                   6563: #      $coursedomain - Domain at which the course was created.
                   6564: #  Returns:
                   6565: #     A hash of the course parameters along (I think) with timestamps
                   6566: #     and version info.
1.877     foxr     6567: 
1.624     albertel 6568: sub get_courseresdata {
                   6569:     my ($coursenum,$coursedomain)=@_;
1.200     www      6570:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6571:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6572:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6573:     my %dumpreply;
1.417     albertel 6574:     unless (defined($cached)) {
1.624     albertel 6575: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6576: 	$result=\%dumpreply;
1.251     albertel 6577: 	my ($tmp) = keys(%dumpreply);
                   6578: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6579: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6580: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6581: 	    return $tmp;
1.416     albertel 6582: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6583: 	    $result=undef;
1.599     albertel 6584: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6585: 	}
                   6586:     }
1.624     albertel 6587:     return $result;
                   6588: }
                   6589: 
1.633     albertel 6590: sub devalidateuserresdata {
                   6591:     my ($uname,$udom)=@_;
                   6592:     my $hashid="$udom:$uname";
                   6593:     &devalidate_cache_new('userres',$hashid);
                   6594: }
                   6595: 
1.624     albertel 6596: sub get_userresdata {
                   6597:     my ($uname,$udom)=@_;
                   6598:     #most student don\'t have any data set, check if there is some data
                   6599:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6600: 
                   6601:     my $hashid="$udom:$uname";
                   6602:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6603:     if (!defined($cached)) {
                   6604: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6605: 	$result=\%resourcedata;
                   6606: 	&do_cache_new('userres',$hashid,$result,600);
                   6607:     }
                   6608:     my ($tmp)=keys(%$result);
                   6609:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6610: 	return $result;
                   6611:     }
                   6612:     #error 2 occurs when the .db doesn't exist
                   6613:     if ($tmp!~/error: 2 /) {
1.672     albertel 6614: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6615: 		 " Trying to get resource data for ".
                   6616: 		 $uname." at ".$udom.": ".
                   6617: 		 $tmp."</font>");
                   6618:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6619: 	#&EXT_cache_set($udom,$uname);
                   6620: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6621: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6622:     }
                   6623:     return $tmp;
                   6624: }
1.879     foxr     6625: #----------------------------------------------- resdata - return resource data
                   6626: #  Purpose:
                   6627: #    Return resource data for either users or for a course.
                   6628: #  Parameters:
                   6629: #     $name      - Course/user name.
                   6630: #     $domain    - Name of the domain the user/course is registered on.
                   6631: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6632: #     @which     - Array of names of resources desired.
                   6633: #  Returns:
                   6634: #     The value of the first reasource in @which that is found in the
                   6635: #     resource hash.
                   6636: #  Exceptional Conditions:
                   6637: #     If the $type passed in is not valid (not the string 'course' or 
                   6638: #     'user', an undefined  reference is returned.
                   6639: #     If none of the resources are found, an undef is returned
1.624     albertel 6640: sub resdata {
                   6641:     my ($name,$domain,$type,@which)=@_;
                   6642:     my $result;
                   6643:     if ($type eq 'course') {
                   6644: 	$result=&get_courseresdata($name,$domain);
                   6645:     } elsif ($type eq 'user') {
                   6646: 	$result=&get_userresdata($name,$domain);
                   6647:     }
                   6648:     if (!ref($result)) { return $result; }    
1.251     albertel 6649:     foreach my $item (@which) {
1.927     albertel 6650: 	if (defined($result->{$item->[0]})) {
                   6651: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6652: 	}
1.250     albertel 6653:     }
1.291     albertel 6654:     return undef;
1.200     www      6655: }
                   6656: 
1.379     matthew  6657: #
                   6658: # EXT resource caching routines
                   6659: #
                   6660: 
                   6661: sub clear_EXT_cache_status {
1.383     albertel 6662:     &delenv('cache.EXT.');
1.379     matthew  6663: }
                   6664: 
                   6665: sub EXT_cache_status {
                   6666:     my ($target_domain,$target_user) = @_;
1.383     albertel 6667:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6668:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6669:         # We know already the user has no data
                   6670:         return 1;
                   6671:     } else {
                   6672:         return 0;
                   6673:     }
                   6674: }
                   6675: 
                   6676: sub EXT_cache_set {
                   6677:     my ($target_domain,$target_user) = @_;
1.383     albertel 6678:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6679:     #&appenv({$cachename => time});
1.379     matthew  6680: }
                   6681: 
1.28      www      6682: # --------------------------------------------------------- Value of a Variable
1.58      www      6683: sub EXT {
1.715     albertel 6684: 
1.395     albertel 6685:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6686:     unless ($varname) { return ''; }
1.218     albertel 6687:     #get real user name/domain, courseid and symb
                   6688:     my $courseid;
1.359     albertel 6689:     my $publicuser;
1.427     www      6690:     if ($symbparm) {
                   6691: 	$symbparm=&get_symb_from_alias($symbparm);
                   6692:     }
1.218     albertel 6693:     if (!($uname && $udom)) {
1.790     albertel 6694:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6695:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6696:     } else {
1.620     albertel 6697: 	$courseid=$env{'request.course.id'};
1.218     albertel 6698:     }
1.48      www      6699:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6700:     my $rest;
1.320     albertel 6701:     if (defined($therest[0])) {
1.48      www      6702:        $rest=join('.',@therest);
                   6703:     } else {
                   6704:        $rest='';
                   6705:     }
1.320     albertel 6706: 
1.57      www      6707:     my $qualifierrest=$qualifier;
                   6708:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6709:     my $spacequalifierrest=$space;
                   6710:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6711:     if ($realm eq 'user') {
1.48      www      6712: # --------------------------------------------------------------- user.resource
                   6713: 	if ($space eq 'resource') {
1.651     albertel 6714: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6715: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6716: 		 &&
1.744     albertel 6717: 		 ($symbparm eq &symbread()) ) {	
                   6718: 		# if we are in the middle of processing the resource the
                   6719: 		# get the value we are planning on committing
                   6720:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6721:                     return $Apache::lonhomework::results{$qualifierrest};
                   6722:                 } else {
                   6723:                     return $Apache::lonhomework::history{$qualifierrest};
                   6724:                 }
1.335     albertel 6725: 	    } else {
1.359     albertel 6726: 		my %restored;
1.620     albertel 6727: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6728: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6729: 		} else {
                   6730: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6731: 		}
1.335     albertel 6732: 		return $restored{$qualifierrest};
                   6733: 	    }
1.48      www      6734: # ----------------------------------------------------------------- user.access
                   6735:         } elsif ($space eq 'access') {
1.218     albertel 6736: 	    # FIXME - not supporting calls for a specific user
1.48      www      6737:             return &allowed($qualifier,$rest);
                   6738: # ------------------------------------------ user.preferences, user.environment
                   6739:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6740: 	    if (($uname eq $env{'user.name'}) &&
                   6741: 		($udom eq $env{'user.domain'})) {
                   6742: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6743: 	    } else {
1.359     albertel 6744: 		my %returnhash;
                   6745: 		if (!$publicuser) {
                   6746: 		    %returnhash=&userenvironment($udom,$uname,
                   6747: 						 $qualifierrest);
                   6748: 		}
1.218     albertel 6749: 		return $returnhash{$qualifierrest};
                   6750: 	    }
1.48      www      6751: # ----------------------------------------------------------------- user.course
                   6752:         } elsif ($space eq 'course') {
1.218     albertel 6753: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6754:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6755: # ------------------------------------------------------------------- user.role
                   6756:         } elsif ($space eq 'role') {
1.218     albertel 6757: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6758:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6759:             if ($qualifier eq 'value') {
                   6760: 		return $role;
                   6761:             } elsif ($qualifier eq 'extent') {
                   6762:                 return $where;
                   6763:             }
                   6764: # ----------------------------------------------------------------- user.domain
                   6765:         } elsif ($space eq 'domain') {
1.218     albertel 6766:             return $udom;
1.48      www      6767: # ------------------------------------------------------------------- user.name
                   6768:         } elsif ($space eq 'name') {
1.218     albertel 6769:             return $uname;
1.48      www      6770: # ---------------------------------------------------- Any other user namespace
1.29      www      6771:         } else {
1.359     albertel 6772: 	    my %reply;
                   6773: 	    if (!$publicuser) {
                   6774: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6775: 	    }
                   6776: 	    return $reply{$qualifierrest};
1.48      www      6777:         }
1.236     www      6778:     } elsif ($realm eq 'query') {
                   6779: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6780:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6781: 						[$spacequalifierrest]);
1.620     albertel 6782: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6783:    } elsif ($realm eq 'request') {
1.48      www      6784: # ------------------------------------------------------------- request.browser
                   6785:         if ($space eq 'browser') {
1.430     www      6786: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6787: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6788: 		    return 1;
                   6789: 		} else {
                   6790: 		    return 0;
                   6791: 		}
                   6792: 	    } else {
1.620     albertel 6793: 		return $env{'browser.'.$qualifier};
1.430     www      6794: 	    }
1.57      www      6795: # ------------------------------------------------------------ request.filename
                   6796:         } else {
1.620     albertel 6797:             return $env{'request.'.$spacequalifierrest};
1.29      www      6798:         }
1.28      www      6799:     } elsif ($realm eq 'course') {
1.48      www      6800: # ---------------------------------------------------------- course.description
1.620     albertel 6801:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6802:     } elsif ($realm eq 'resource') {
1.165     www      6803: 
1.620     albertel 6804: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6805: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6806: 	}
1.693     albertel 6807: 
                   6808: 	if ($space eq 'title') {
                   6809: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6810: 	    return &gettitle($symbparm);
                   6811: 	}
                   6812: 	
                   6813: 	if ($space eq 'map') {
                   6814: 	    my ($map) = &decode_symb($symbparm);
                   6815: 	    return &symbread($map);
                   6816: 	}
1.905     albertel 6817: 	if ($space eq 'filename') {
                   6818: 	    if ($symbparm) {
                   6819: 		return &clutter((&decode_symb($symbparm))[2]);
                   6820: 	    }
                   6821: 	    return &hreflocation('',$env{'request.filename'});
                   6822: 	}
1.693     albertel 6823: 
                   6824: 	my ($section, $group, @groups);
1.593     albertel 6825: 	my ($courselevelm,$courselevel);
1.539     albertel 6826: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6827: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6828: 
1.218     albertel 6829: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6830: 
1.60      www      6831: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6832: 	    my $symbp=$symbparm;
1.735     albertel 6833: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6834: 
                   6835: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6836: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6837: 
1.620     albertel 6838: 	    if (($env{'user.name'} eq $uname) &&
                   6839: 		($env{'user.domain'} eq $udom)) {
                   6840: 		$section=$env{'request.course.sec'};
1.733     raeburn  6841:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6842:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6843: 	    } else {
1.539     albertel 6844: 		if (! defined($usection)) {
1.551     albertel 6845: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6846: 		} else {
                   6847: 		    $section = $usection;
                   6848: 		}
1.733     raeburn  6849:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6850: 	    }
                   6851: 
                   6852: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6853: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6854: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6855: 
1.593     albertel 6856: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6857: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6858: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6859: 
1.60      www      6860: # ----------------------------------------------------------- first, check user
1.624     albertel 6861: 
                   6862: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6863: 				       ([$courselevelr,'resource'],
                   6864: 					[$courselevelm,'map'     ],
                   6865: 					[$courselevel, 'course'  ]));
1.931     albertel 6866: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6867: 
1.594     albertel 6868: # ------------------------------------------------ second, check some of course
1.684     raeburn  6869:             my $coursereply;
1.691     raeburn  6870:             if (@groups > 0) {
                   6871:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6872:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6873:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6874:             }
1.96      www      6875: 
1.684     raeburn  6876: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6877: 				  $env{'course.'.$courseid.'.domain'},
                   6878: 				  'course',
                   6879: 				  ([$seclevelr,   'resource'],
                   6880: 				   [$seclevelm,   'map'     ],
                   6881: 				   [$seclevel,    'course'  ],
                   6882: 				   [$courselevelr,'resource']));
                   6883: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6884: 
1.60      www      6885: # ------------------------------------------------------ third, check map parms
1.218     albertel 6886: 	    my %parmhash=();
                   6887: 	    my $thisparm='';
                   6888: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6889: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6890: 		    &GDBM_READER(),0640)) {
1.218     albertel 6891: 		$thisparm=$parmhash{$symbparm};
                   6892: 		untie(%parmhash);
                   6893: 	    }
1.927     albertel 6894: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6895: 	}
1.594     albertel 6896: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6897: 
1.218     albertel 6898: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6899: 	my $filename;
                   6900: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6901: 	if ($symbparm) {
1.409     www      6902: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6903: 	} else {
1.620     albertel 6904: 	    $filename=$env{'request.filename'};
1.282     albertel 6905: 	}
                   6906: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6907: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6908: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6909: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6910: 
1.927     albertel 6911: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6912: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6913: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6914: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6915: 				     $env{'course.'.$courseid.'.domain'},
                   6916: 				     'course',
1.927     albertel 6917: 				     ([$courselevelm,'map'   ],
                   6918: 				      [$courselevel, 'course']));
                   6919: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6920: 	}
1.145     www      6921: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6922: 	unless ($space eq '0') {
1.336     albertel 6923: 	    my @parts=split(/_/,$space);
                   6924: 	    my $id=pop(@parts);
                   6925: 	    my $part=join('_',@parts);
                   6926: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6927: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6928: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6929: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6930: 	}
1.395     albertel 6931: 	if ($recurse) { return undef; }
                   6932: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6933: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6934: # ---------------------------------------------------- Any other user namespace
                   6935:     } elsif ($realm eq 'environment') {
                   6936: # ----------------------------------------------------------------- environment
1.620     albertel 6937: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6938: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6939: 	} else {
1.770     albertel 6940: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6941: 		return '';
                   6942: 	    }
1.219     albertel 6943: 	    my %returnhash=&userenvironment($udom,$uname,
                   6944: 					    $spacequalifierrest);
                   6945: 	    return $returnhash{$spacequalifierrest};
                   6946: 	}
1.28      www      6947:     } elsif ($realm eq 'system') {
1.48      www      6948: # ----------------------------------------------------------------- system.time
                   6949: 	if ($space eq 'time') {
                   6950: 	    return time;
                   6951:         }
1.696     albertel 6952:     } elsif ($realm eq 'server') {
                   6953: # ----------------------------------------------------------------- system.time
                   6954: 	if ($space eq 'name') {
                   6955: 	    return $ENV{'SERVER_NAME'};
                   6956:         }
1.28      www      6957:     }
1.48      www      6958:     return '';
1.61      www      6959: }
                   6960: 
1.927     albertel 6961: sub get_reply {
                   6962:     my ($reply_value) = @_;
1.940     raeburn  6963:     if (ref($reply_value) eq 'ARRAY') {
                   6964:         if (wantarray) {
                   6965: 	    return @$reply_value;
                   6966:         }
                   6967:         return $reply_value->[0];
                   6968:     } else {
                   6969:         return $reply_value;
1.927     albertel 6970:     }
                   6971: }
                   6972: 
1.691     raeburn  6973: sub check_group_parms {
                   6974:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6975:     my @groupitems = ();
                   6976:     my $resultitem;
1.927     albertel 6977:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6978:     foreach my $group (@{$groups}) {
                   6979:         foreach my $level (@levels) {
1.927     albertel 6980:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6981:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6982:         }
                   6983:     }
                   6984:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6985:                             $env{'course.'.$courseid.'.domain'},
                   6986:                                      'course',@groupitems);
                   6987:     return $coursereply;
                   6988: }
                   6989: 
                   6990: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6991:     my ($courseid,@groups) = @_;
                   6992:     @groups = sort(@groups);
1.691     raeburn  6993:     return @groups;
                   6994: }
                   6995: 
1.395     albertel 6996: sub packages_tab_default {
                   6997:     my ($uri,$varname)=@_;
                   6998:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6999: 
                   7000:     my (@extension,@specifics,$do_default);
                   7001:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7002: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7003: 	if ($pack_type eq 'default') {
                   7004: 	    $do_default=1;
                   7005: 	} elsif ($pack_type eq 'extension') {
                   7006: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7007: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7008: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7009: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7010: 	}
                   7011:     }
                   7012:     # first look for a package that matches the requested part id
                   7013:     foreach my $package (@specifics) {
                   7014: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7015: 	next if ($pack_part ne $part);
                   7016: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7017: 	    return $packagetab{"$pack_type&$name&default"};
                   7018: 	}
                   7019:     }
                   7020:     # look for any possible matching non extension_ package
                   7021:     foreach my $package (@specifics) {
                   7022: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7023: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7024: 	    return $packagetab{"$pack_type&$name&default"};
                   7025: 	}
1.585     albertel 7026: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7027: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7028: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7029: 	}
                   7030:     }
1.738     albertel 7031:     # look for any posible extension_ match
                   7032:     foreach my $package (@extension) {
                   7033: 	my ($package,$pack_type)=@{$package};
                   7034: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7035: 	    return $packagetab{"$pack_type&$name&default"};
                   7036: 	}
                   7037: 	if (defined($packagetab{$package."&$name&default"})) {
                   7038: 	    return $packagetab{$package."&$name&default"};
                   7039: 	}
                   7040:     }
                   7041:     # look for a global default setting
                   7042:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7043: 	return $packagetab{"default&$name&default"};
                   7044:     }
1.395     albertel 7045:     return undef;
                   7046: }
                   7047: 
1.334     albertel 7048: sub add_prefix_and_part {
                   7049:     my ($prefix,$part)=@_;
                   7050:     my $keyroot;
                   7051:     if (defined($prefix) && $prefix !~ /^__/) {
                   7052: 	# prefix that has a part already
                   7053: 	$keyroot=$prefix;
                   7054:     } elsif (defined($prefix)) {
                   7055: 	# prefix that is missing a part
                   7056: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7057:     } else {
                   7058: 	# no prefix at all
                   7059: 	if (defined($part)) { $keyroot='_'.$part; }
                   7060:     }
                   7061:     return $keyroot;
                   7062: }
                   7063: 
1.71      www      7064: # ---------------------------------------------------------------- Get metadata
                   7065: 
1.599     albertel 7066: my %metaentry;
1.71      www      7067: sub metadata {
1.176     www      7068:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7069:     $uri=&declutter($uri);
1.288     albertel 7070:     # if it is a non metadata possible uri return quickly
1.529     albertel 7071:     if (($uri eq '') || 
                   7072: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7073: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7074:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7075: 	return undef;
                   7076:     }
                   7077:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7078: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7079: 	return undef;
1.288     albertel 7080:     }
1.73      www      7081:     my $filename=$uri;
                   7082:     $uri=~s/\.meta$//;
1.172     www      7083: #
                   7084: # Is the metadata already cached?
1.177     www      7085: # Look at timestamp of caching
1.172     www      7086: # Everything is cached by the main uri, libraries are never directly cached
                   7087: #
1.428     albertel 7088:     if (!defined($liburi)) {
1.599     albertel 7089: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7090: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7091:     }
                   7092:     {
1.172     www      7093: #
                   7094: # Is this a recursive call for a library?
                   7095: #
1.599     albertel 7096: #	if (! exists($metacache{$uri})) {
                   7097: #	    $metacache{$uri}={};
                   7098: #	}
1.924     albertel 7099: 	my $cachetime = 60*60;
1.171     www      7100:         if ($liburi) {
                   7101: 	    $liburi=&declutter($liburi);
                   7102:             $filename=$liburi;
1.401     bowersj2 7103:         } else {
1.599     albertel 7104: 	    &devalidate_cache_new('meta',$uri);
                   7105: 	    undef(%metaentry);
1.401     bowersj2 7106: 	}
1.140     www      7107:         my %metathesekeys=();
1.73      www      7108:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7109: 	my $metastring;
1.924     albertel 7110: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7111: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7112: 	    $metastring = 
1.929     albertel 7113: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7114: 					  ('grade_target' => 'meta'));
                   7115: 	    $cachetime = 1; # only want this cached in the child not long term
                   7116: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7117: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7118: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7119: 	    $metastring=&getfile($file);
1.489     albertel 7120: 	}
1.208     albertel 7121:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7122:         my $token;
1.140     www      7123:         undef %metathesekeys;
1.71      www      7124:         while ($token=$parser->get_token) {
1.339     albertel 7125: 	    if ($token->[0] eq 'S') {
                   7126: 		if (defined($token->[2]->{'package'})) {
1.172     www      7127: #
                   7128: # This is a package - get package info
                   7129: #
1.339     albertel 7130: 		    my $package=$token->[2]->{'package'};
                   7131: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7132: 		    if (defined($token->[2]->{'id'})) { 
                   7133: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7134: 		    }
1.599     albertel 7135: 		    if ($metaentry{':packages'}) {
                   7136: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7137: 		    } else {
1.599     albertel 7138: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7139: 		    }
1.736     albertel 7140: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7141: 			my $part=$keyroot;
                   7142: 			$part=~s/^\_//;
1.736     albertel 7143: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7144: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7145: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7146: 			    # ignore package.tab specified default values
                   7147:                             # here &package_tab_default() will fetch those
                   7148: 			    if ($subp eq 'default') { next; }
1.736     albertel 7149: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7150: 			    my $unikey;
                   7151: 			    if ($pack =~ /_0$/) {
                   7152: 				$unikey='parameter_0_'.$name;
                   7153: 				$part=0;
                   7154: 			    } else {
                   7155: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7156: 			    }
1.339     albertel 7157: 			    if ($subp eq 'display') {
                   7158: 				$value.=' [Part: '.$part.']';
                   7159: 			    }
1.599     albertel 7160: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7161: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7162: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7163: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7164: 			    }
1.599     albertel 7165: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7166: 				$metaentry{':'.$unikey}=
                   7167: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7168: 			    }
1.339     albertel 7169: 			}
                   7170: 		    }
                   7171: 		} else {
1.172     www      7172: #
                   7173: # This is not a package - some other kind of start tag
1.339     albertel 7174: #
                   7175: 		    my $entry=$token->[1];
                   7176: 		    my $unikey;
                   7177: 		    if ($entry eq 'import') {
                   7178: 			$unikey='';
                   7179: 		    } else {
                   7180: 			$unikey=$entry;
                   7181: 		    }
                   7182: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7183: 
                   7184: 		    if (defined($token->[2]->{'id'})) { 
                   7185: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7186: 		    }
1.175     www      7187: 
1.339     albertel 7188: 		    if ($entry eq 'import') {
1.175     www      7189: #
                   7190: # Importing a library here
1.339     albertel 7191: #
                   7192: 			if ($depthcount<20) {
                   7193: 			    my $location=$parser->get_text('/import');
                   7194: 			    my $dir=$filename;
                   7195: 			    $dir=~s|[^/]*$||;
                   7196: 			    $location=&filelocation($dir,$location);
1.736     albertel 7197: 			    my $metadata = 
                   7198: 				&metadata($uri,'keys', $location,$unikey,
                   7199: 					  $depthcount+1);
                   7200: 			    foreach my $meta (split(',',$metadata)) {
                   7201: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7202: 				$metathesekeys{$meta}=1;
1.339     albertel 7203: 			    }
                   7204: 			}
                   7205: 		    } else { 
                   7206: 			
                   7207: 			if (defined($token->[2]->{'name'})) { 
                   7208: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7209: 			}
                   7210: 			$metathesekeys{$unikey}=1;
1.736     albertel 7211: 			foreach my $param (@{$token->[3]}) {
                   7212: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7213: 				$token->[2]->{$param};
1.339     albertel 7214: 			}
                   7215: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7216: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7217: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7218: 		 # only ws inside the tag, and not in default, so use default
                   7219: 		 # as value
1.599     albertel 7220: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7221: 			} elsif ( $internaltext =~ /\S/ ) {
                   7222: 		  # something interesting inside the tag
                   7223: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7224: 			} else {
1.908     albertel 7225: 		  # no interesting values, don't set a default
1.339     albertel 7226: 			}
1.172     www      7227: # end of not-a-package not-a-library import
1.339     albertel 7228: 		    }
1.172     www      7229: # end of not-a-package start tag
1.339     albertel 7230: 		}
1.172     www      7231: # the next is the end of "start tag"
1.339     albertel 7232: 	    }
                   7233: 	}
1.483     albertel 7234: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7235: 	$extension = lc($extension);
                   7236: 	if ($extension eq 'htm') { $extension='html'; }
                   7237: 
1.737     albertel 7238: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7239: 	    #no specific packages #how's our extension
                   7240: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7241: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7242: 					 \%metathesekeys);
                   7243: 	}
1.883     albertel 7244: 
                   7245: 	if (!exists($metaentry{':packages'})
                   7246: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7247: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7248: 		#no specific packages well let's get default then
                   7249: 		if ($key!~/^default&/) { next; }
1.488     albertel 7250: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7251: 					     \%metathesekeys);
                   7252: 	    }
                   7253: 	}
1.338     www      7254: # are there custom rights to evaluate
1.599     albertel 7255: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7256: 
1.338     www      7257:     #
                   7258:     # Importing a rights file here
1.339     albertel 7259:     #
                   7260: 	    unless ($depthcount) {
1.599     albertel 7261: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7262: 		my $dir=$filename;
                   7263: 		$dir=~s|[^/]*$||;
                   7264: 		$location=&filelocation($dir,$location);
1.736     albertel 7265: 		my $rights_metadata =
                   7266: 		    &metadata($uri,'keys',$location,'_rights',
                   7267: 			      $depthcount+1);
                   7268: 		foreach my $rights (split(',',$rights_metadata)) {
                   7269: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7270: 		    $metathesekeys{$rights}=1;
1.339     albertel 7271: 		}
                   7272: 	    }
                   7273: 	}
1.737     albertel 7274: 	# uniqifiy package listing
                   7275: 	my %seen;
                   7276: 	my @uniq_packages =
                   7277: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7278: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7279: 
                   7280: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7281: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7282: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7283: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7284: # this is the end of "was not already recently cached
1.71      www      7285:     }
1.599     albertel 7286:     return $metaentry{':'.$what};
1.261     albertel 7287: }
                   7288: 
1.488     albertel 7289: sub metadata_create_package_def {
1.483     albertel 7290:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7291:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7292:     if ($subp eq 'default') { next; }
                   7293:     
1.599     albertel 7294:     if (defined($metaentry{':packages'})) {
                   7295: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7296:     } else {
1.599     albertel 7297: 	$metaentry{':packages'}=$package;
1.483     albertel 7298:     }
                   7299:     my $value=$packagetab{$key};
                   7300:     my $unikey;
                   7301:     $unikey='parameter_0_'.$name;
1.599     albertel 7302:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7303:     $$metathesekeys{$unikey}=1;
1.599     albertel 7304:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7305: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7306:     }
1.599     albertel 7307:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7308: 	$metaentry{':'.$unikey}=
                   7309: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7310:     }
                   7311: }
                   7312: 
1.261     albertel 7313: sub metadata_generate_part0 {
                   7314:     my ($metadata,$metacache,$uri) = @_;
                   7315:     my %allnames;
1.737     albertel 7316:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7317: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7318: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7319: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7320: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7321: 	    $allnames{$name}=$part;
                   7322: 	  }
                   7323: 	}
                   7324:     }
                   7325:     foreach my $name (keys(%allnames)) {
                   7326:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7327:       my $key=":parameter_0_$name";
1.261     albertel 7328:       $$metacache{"$key.part"}='0';
                   7329:       $$metacache{"$key.name"}=$name;
1.428     albertel 7330:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7331: 					   $allnames{$name}.'_'.$name.
                   7332: 					   '.type'};
1.428     albertel 7333:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7334: 			     '.display'};
1.644     www      7335:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7336:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7337:       $$metacache{"$key.display"}=$olddis;
                   7338:     }
1.71      www      7339: }
                   7340: 
1.764     albertel 7341: # ------------------------------------------------------ Devalidate title cache
                   7342: 
                   7343: sub devalidate_title_cache {
                   7344:     my ($url)=@_;
                   7345:     if (!$env{'request.course.id'}) { return; }
                   7346:     my $symb=&symbread($url);
                   7347:     if (!$symb) { return; }
                   7348:     my $key=$env{'request.course.id'}."\0".$symb;
                   7349:     &devalidate_cache_new('title',$key);
                   7350: }
                   7351: 
1.301     www      7352: # ------------------------------------------------- Get the title of a resource
                   7353: 
                   7354: sub gettitle {
                   7355:     my $urlsymb=shift;
                   7356:     my $symb=&symbread($urlsymb);
1.534     albertel 7357:     if ($symb) {
1.620     albertel 7358: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7359: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7360: 	if (defined($cached)) { 
                   7361: 	    return $result;
                   7362: 	}
1.534     albertel 7363: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7364: 	my $title='';
1.907     albertel 7365: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7366: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7367: 	} else {
                   7368: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7369: 		    &GDBM_READER(),0640)) {
                   7370: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7371: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7372: 		untie(%bighash);
                   7373: 	    }
1.534     albertel 7374: 	}
                   7375: 	$title=~s/\&colon\;/\:/gs;
                   7376: 	if ($title) {
1.599     albertel 7377: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7378: 	}
                   7379: 	$urlsymb=$url;
                   7380:     }
                   7381:     my $title=&metadata($urlsymb,'title');
                   7382:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7383:     return $title;
1.301     www      7384: }
1.613     albertel 7385: 
1.614     albertel 7386: sub get_slot {
                   7387:     my ($which,$cnum,$cdom)=@_;
                   7388:     if (!$cnum || !$cdom) {
1.790     albertel 7389: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7390: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7391: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7392:     }
1.703     albertel 7393:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7394:     my %slotinfo;
                   7395:     if (exists($remembered{$key})) {
                   7396: 	$slotinfo{$which} = $remembered{$key};
                   7397:     } else {
                   7398: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7399: 	&Apache::lonhomework::showhash(%slotinfo);
                   7400: 	my ($tmp)=keys(%slotinfo);
                   7401: 	if ($tmp=~/^error:/) { return (); }
                   7402: 	$remembered{$key} = $slotinfo{$which};
                   7403:     }
1.616     albertel 7404:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7405: 	return %{$slotinfo{$which}};
                   7406:     }
                   7407:     return $slotinfo{$which};
1.614     albertel 7408: }
1.31      www      7409: # ------------------------------------------------- Update symbolic store links
                   7410: 
                   7411: sub symblist {
                   7412:     my ($mapname,%newhash)=@_;
1.438     www      7413:     $mapname=&deversion(&declutter($mapname));
1.31      www      7414:     my %hash;
1.620     albertel 7415:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7416:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7417:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7418: 	    foreach my $url (keys %newhash) {
                   7419: 		next if ($url eq 'last_known'
                   7420: 			 && $env{'form.no_update_last_known'});
                   7421: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7422: 						    $newhash{$url}->[1],
                   7423: 						    $newhash{$url}->[0]);
1.191     harris41 7424:             }
1.31      www      7425:             if (untie(%hash)) {
                   7426: 		return 'ok';
                   7427:             }
                   7428:         }
                   7429:     }
                   7430:     return 'error';
1.212     www      7431: }
                   7432: 
                   7433: # --------------------------------------------------------------- Verify a symb
                   7434: 
                   7435: sub symbverify {
1.510     www      7436:     my ($symb,$thisurl)=@_;
                   7437:     my $thisfn=$thisurl;
1.439     www      7438:     $thisfn=&declutter($thisfn);
1.215     www      7439: # direct jump to resource in page or to a sequence - will construct own symbs
                   7440:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7441: # check URL part
1.409     www      7442:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7443: 
1.431     www      7444:     unless ($url eq $thisfn) { return 0; }
1.213     www      7445: 
1.216     www      7446:     $symb=&symbclean($symb);
1.510     www      7447:     $thisurl=&deversion($thisurl);
1.439     www      7448:     $thisfn=&deversion($thisfn);
1.213     www      7449: 
                   7450:     my %bighash;
                   7451:     my $okay=0;
1.431     www      7452: 
1.620     albertel 7453:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7454:                             &GDBM_READER(),0640)) {
1.510     www      7455:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7456:         unless ($ids) { 
1.510     www      7457:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7458:         }
                   7459:         if ($ids) {
                   7460: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7461: 	    foreach my $id (split(/\,/,$ids)) {
                   7462: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7463:                if (
                   7464:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7465:    eq $symb) { 
1.620     albertel 7466: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7467: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7468: 		       $okay=1; 
                   7469: 		   }
                   7470: 	       }
1.216     www      7471: 	   }
                   7472:         }
1.213     www      7473: 	untie(%bighash);
                   7474:     }
                   7475:     return $okay;
1.31      www      7476: }
                   7477: 
1.210     www      7478: # --------------------------------------------------------------- Clean-up symb
                   7479: 
                   7480: sub symbclean {
                   7481:     my $symb=shift;
1.568     albertel 7482:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7483: # remove version from map
                   7484:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7485: 
1.210     www      7486: # remove version from URL
                   7487:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7488: 
1.507     www      7489: # remove wrapper
                   7490: 
1.510     www      7491:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7492:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7493:     return $symb;
1.409     www      7494: }
                   7495: 
                   7496: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7497: 
                   7498: sub encode_symb {
                   7499:     my ($map,$resid,$url)=@_;
                   7500:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7501: }
1.409     www      7502: 
                   7503: sub decode_symb {
1.568     albertel 7504:     my $symb=shift;
                   7505:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7506:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7507:     return (&fixversion($map),$resid,&fixversion($url));
                   7508: }
                   7509: 
                   7510: sub fixversion {
                   7511:     my $fn=shift;
1.609     banghart 7512:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7513:     my %bighash;
                   7514:     my $uri=&clutter($fn);
1.620     albertel 7515:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7516: # is this cached?
1.599     albertel 7517:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7518:     if (defined($cached)) { return $result; }
                   7519: # unfortunately not cached, or expired
1.620     albertel 7520:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7521: 	    &GDBM_READER(),0640)) {
                   7522:  	if ($bighash{'version_'.$uri}) {
                   7523:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7524:  	    unless (($version eq 'mostrecent') || 
                   7525: 		    ($version==&getversion($uri))) {
1.440     www      7526:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7527:  	    }
                   7528:  	}
                   7529:  	untie %bighash;
1.413     www      7530:     }
1.599     albertel 7531:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7532: }
                   7533: 
                   7534: sub deversion {
                   7535:     my $url=shift;
                   7536:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7537:     return $url;
1.210     www      7538: }
                   7539: 
1.31      www      7540: # ------------------------------------------------------ Return symb list entry
                   7541: 
                   7542: sub symbread {
1.249     www      7543:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7544:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7545:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7546: # no filename provided? try from environment
1.44      www      7547:     unless ($thisfn) {
1.620     albertel 7548:         if ($env{'request.symb'}) {
                   7549: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7550: 	}
1.620     albertel 7551: 	$thisfn=$env{'request.filename'};
1.44      www      7552:     }
1.569     albertel 7553:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7554: # is that filename actually a symb? Verify, clean, and return
                   7555:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7556: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7557: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7558: 	}
1.242     www      7559:     }
1.44      www      7560:     $thisfn=declutter($thisfn);
1.31      www      7561:     my %hash;
1.37      www      7562:     my %bighash;
                   7563:     my $syval='';
1.620     albertel 7564:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7565:         my $targetfn = $thisfn;
1.609     banghart 7566:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7567:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7568:         }
1.687     albertel 7569: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7570: 	    $targetfn=$1;
                   7571: 	}
1.620     albertel 7572:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7573:                       &GDBM_READER(),0640)) {
1.481     raeburn  7574: 	    $syval=$hash{$targetfn};
1.37      www      7575:             untie(%hash);
                   7576:         }
                   7577: # ---------------------------------------------------------- There was an entry
                   7578:         if ($syval) {
1.601     albertel 7579: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7580: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7581: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7582: 		    #return $env{$cache_str}='';
1.601     albertel 7583: 		#}    
                   7584: 		#$syval.=$1;
                   7585: 	    #}
1.37      www      7586:         } else {
                   7587: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7588:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7589:                             &GDBM_READER(),0640)) {
1.37      www      7590: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7591:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7592:               unless ($ids) { 
                   7593:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7594:               }
                   7595:               unless ($ids) {
                   7596: # alias?
                   7597: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7598:               }
1.37      www      7599:               if ($ids) {
                   7600: # ------------------------------------------------------------------- Has ID(s)
                   7601:                  my @possibilities=split(/\,/,$ids);
1.39      www      7602:                  if ($#possibilities==0) {
                   7603: # ----------------------------------------------- There is only one possibility
1.37      www      7604: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7605: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7606: 						    $resid,$thisfn);
1.249     www      7607:                  } elsif (!$donotrecurse) {
1.39      www      7608: # ------------------------------------------ There is more than one possibility
                   7609:                      my $realpossible=0;
1.800     albertel 7610:                      foreach my $id (@possibilities) {
                   7611: 			 my $file=$bighash{'src_'.$id};
1.39      www      7612:                          if (&allowed('bre',$file)) {
1.800     albertel 7613:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7614:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7615: 				$realpossible++;
1.626     albertel 7616:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7617: 						    $resid,$thisfn);
1.39      www      7618:                             }
                   7619: 			 }
1.191     harris41 7620:                      }
1.39      www      7621: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7622:                  } else {
                   7623:                      $syval='';
1.37      www      7624:                  }
                   7625: 	      }
                   7626:               untie(%bighash)
1.481     raeburn  7627:            }
1.31      www      7628:         }
1.62      www      7629:         if ($syval) {
1.620     albertel 7630: 	    return $env{$cache_str}=$syval;
1.62      www      7631:         }
1.31      www      7632:     }
1.949     raeburn  7633:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7634:     return $env{$cache_str}='';
1.31      www      7635: }
                   7636: 
                   7637: # ---------------------------------------------------------- Return random seed
                   7638: 
1.32      www      7639: sub numval {
                   7640:     my $txt=shift;
                   7641:     $txt=~tr/A-J/0-9/;
                   7642:     $txt=~tr/a-j/0-9/;
                   7643:     $txt=~tr/K-T/0-9/;
                   7644:     $txt=~tr/k-t/0-9/;
                   7645:     $txt=~tr/U-Z/0-5/;
                   7646:     $txt=~tr/u-z/0-5/;
                   7647:     $txt=~s/\D//g;
1.564     albertel 7648:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7649:     return int($txt);
1.368     albertel 7650: }
                   7651: 
1.484     albertel 7652: sub numval2 {
                   7653:     my $txt=shift;
                   7654:     $txt=~tr/A-J/0-9/;
                   7655:     $txt=~tr/a-j/0-9/;
                   7656:     $txt=~tr/K-T/0-9/;
                   7657:     $txt=~tr/k-t/0-9/;
                   7658:     $txt=~tr/U-Z/0-5/;
                   7659:     $txt=~tr/u-z/0-5/;
                   7660:     $txt=~s/\D//g;
                   7661:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7662:     my $total;
                   7663:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7664:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7665:     return int($total);
                   7666: }
                   7667: 
1.575     albertel 7668: sub numval3 {
                   7669:     use integer;
                   7670:     my $txt=shift;
                   7671:     $txt=~tr/A-J/0-9/;
                   7672:     $txt=~tr/a-j/0-9/;
                   7673:     $txt=~tr/K-T/0-9/;
                   7674:     $txt=~tr/k-t/0-9/;
                   7675:     $txt=~tr/U-Z/0-5/;
                   7676:     $txt=~tr/u-z/0-5/;
                   7677:     $txt=~s/\D//g;
                   7678:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7679:     my $total;
                   7680:     foreach my $val (@txts) { $total+=$val; }
                   7681:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7682:     return $total;
                   7683: }
                   7684: 
1.675     albertel 7685: sub digest {
                   7686:     my ($data)=@_;
                   7687:     my $digest=&Digest::MD5::md5($data);
                   7688:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7689:     my ($e,$f);
                   7690:     {
                   7691:         use integer;
                   7692:         $e=($a+$b);
                   7693:         $f=($c+$d);
                   7694:         if ($_64bit) {
                   7695:             $e=(($e<<32)>>32);
                   7696:             $f=(($f<<32)>>32);
                   7697:         }
                   7698:     }
                   7699:     if (wantarray) {
                   7700: 	return ($e,$f);
                   7701:     } else {
                   7702: 	my $g;
                   7703: 	{
                   7704: 	    use integer;
                   7705: 	    $g=($e+$f);
                   7706: 	    if ($_64bit) {
                   7707: 		$g=(($g<<32)>>32);
                   7708: 	    }
                   7709: 	}
                   7710: 	return $g;
                   7711:     }
                   7712: }
                   7713: 
1.368     albertel 7714: sub latest_rnd_algorithm_id {
1.675     albertel 7715:     return '64bit5';
1.366     albertel 7716: }
1.32      www      7717: 
1.503     albertel 7718: sub get_rand_alg {
                   7719:     my ($courseid)=@_;
1.790     albertel 7720:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7721:     if ($courseid) {
1.620     albertel 7722: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7723:     }
                   7724:     return &latest_rnd_algorithm_id();
                   7725: }
                   7726: 
1.562     albertel 7727: sub validCODE {
                   7728:     my ($CODE)=@_;
                   7729:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7730:     return 0;
                   7731: }
                   7732: 
1.491     albertel 7733: sub getCODE {
1.620     albertel 7734:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7735:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7736: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7737: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7738: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7739:     }
                   7740:     return undef;
                   7741: }
                   7742: 
1.31      www      7743: sub rndseed {
1.155     albertel 7744:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7745:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7746:     if (!defined($symb)) {
1.366     albertel 7747: 	unless ($symb=$wsymb) { return time; }
                   7748:     }
                   7749:     if (!$courseid) { $courseid=$wcourseid; }
                   7750:     if (!$domain) { $domain=$wdomain; }
                   7751:     if (!$username) { $username=$wusername }
1.503     albertel 7752:     my $which=&get_rand_alg();
1.803     albertel 7753: 
1.491     albertel 7754:     if (defined(&getCODE())) {
1.675     albertel 7755: 	if ($which eq '64bit5') {
                   7756: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7757: 	} elsif ($which eq '64bit4') {
1.575     albertel 7758: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7759: 	} else {
                   7760: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7761: 	}
1.675     albertel 7762:     } elsif ($which eq '64bit5') {
                   7763: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7764:     } elsif ($which eq '64bit4') {
                   7765: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7766:     } elsif ($which eq '64bit3') {
                   7767: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7768:     } elsif ($which eq '64bit2') {
                   7769: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7770:     } elsif ($which eq '64bit') {
                   7771: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7772:     }
                   7773:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7774: }
                   7775: 
                   7776: sub rndseed_32bit {
                   7777:     my ($symb,$courseid,$domain,$username)=@_;
                   7778:     {
                   7779: 	use integer;
                   7780: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7781: 	my $symbseed=numval($symb) << 22;
                   7782: 	my $namechck=unpack("%32C*",$username) << 17;
                   7783: 	my $nameseed=numval($username) << 12;
                   7784: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7785: 	my $courseseed=unpack("%32C*",$courseid);
                   7786: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7787: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7788: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7789: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7790: 	return $num;
                   7791:     }
                   7792: }
                   7793: 
                   7794: sub rndseed_64bit {
                   7795:     my ($symb,$courseid,$domain,$username)=@_;
                   7796:     {
                   7797: 	use integer;
                   7798: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7799: 	my $symbseed=numval($symb) << 10;
                   7800: 	my $namechck=unpack("%32S*",$username);
                   7801: 	
                   7802: 	my $nameseed=numval($username) << 21;
                   7803: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7804: 	my $courseseed=unpack("%32S*",$courseid);
                   7805: 	
                   7806: 	my $num1=$symbchck+$symbseed+$namechck;
                   7807: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7808: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7809: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7810: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7811: 	return "$num1,$num2";
1.155     albertel 7812:     }
1.366     albertel 7813: }
                   7814: 
1.443     albertel 7815: sub rndseed_64bit2 {
                   7816:     my ($symb,$courseid,$domain,$username)=@_;
                   7817:     {
                   7818: 	use integer;
                   7819: 	# strings need to be an even # of cahracters long, it it is odd the
                   7820:         # last characters gets thrown away
                   7821: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7822: 	my $symbseed=numval($symb) << 10;
                   7823: 	my $namechck=unpack("%32S*",$username.' ');
                   7824: 	
                   7825: 	my $nameseed=numval($username) << 21;
1.501     albertel 7826: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7827: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7828: 	
                   7829: 	my $num1=$symbchck+$symbseed+$namechck;
                   7830: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7831: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7832: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7833: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7834: 	return "$num1,$num2";
                   7835:     }
                   7836: }
                   7837: 
                   7838: sub rndseed_64bit3 {
                   7839:     my ($symb,$courseid,$domain,$username)=@_;
                   7840:     {
                   7841: 	use integer;
                   7842: 	# strings need to be an even # of cahracters long, it it is odd the
                   7843:         # last characters gets thrown away
                   7844: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7845: 	my $symbseed=numval2($symb) << 10;
                   7846: 	my $namechck=unpack("%32S*",$username.' ');
                   7847: 	
                   7848: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7849: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7850: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7851: 	
                   7852: 	my $num1=$symbchck+$symbseed+$namechck;
                   7853: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7854: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7855: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7856: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7857: 	
1.503     albertel 7858: 	return "$num1:$num2";
1.443     albertel 7859:     }
                   7860: }
                   7861: 
1.575     albertel 7862: sub rndseed_64bit4 {
                   7863:     my ($symb,$courseid,$domain,$username)=@_;
                   7864:     {
                   7865: 	use integer;
                   7866: 	# strings need to be an even # of cahracters long, it it is odd the
                   7867:         # last characters gets thrown away
                   7868: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7869: 	my $symbseed=numval3($symb) << 10;
                   7870: 	my $namechck=unpack("%32S*",$username.' ');
                   7871: 	
                   7872: 	my $nameseed=numval3($username) << 21;
                   7873: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7874: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7875: 	
                   7876: 	my $num1=$symbchck+$symbseed+$namechck;
                   7877: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7878: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7879: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7880: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7881: 	
                   7882: 	return "$num1:$num2";
                   7883:     }
                   7884: }
                   7885: 
1.675     albertel 7886: sub rndseed_64bit5 {
                   7887:     my ($symb,$courseid,$domain,$username)=@_;
                   7888:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7889:     return "$num1:$num2";
                   7890: }
                   7891: 
1.366     albertel 7892: sub rndseed_CODE_64bit {
                   7893:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7894:     {
1.366     albertel 7895: 	use integer;
1.443     albertel 7896: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7897: 	my $symbseed=numval2($symb);
1.491     albertel 7898: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7899: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7900: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7901: 	my $num1=$symbseed+$CODEchck;
                   7902: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7903: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7904: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7905: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7906: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7907: 	return "$num1:$num2";
1.366     albertel 7908:     }
                   7909: }
                   7910: 
1.575     albertel 7911: sub rndseed_CODE_64bit4 {
                   7912:     my ($symb,$courseid,$domain,$username)=@_;
                   7913:     {
                   7914: 	use integer;
                   7915: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7916: 	my $symbseed=numval3($symb);
                   7917: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7918: 	my $CODEseed=numval3(&getCODE());
                   7919: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7920: 	my $num1=$symbseed+$CODEchck;
                   7921: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7922: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7923: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7924: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7925: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7926: 	return "$num1:$num2";
                   7927:     }
                   7928: }
                   7929: 
1.675     albertel 7930: sub rndseed_CODE_64bit5 {
                   7931:     my ($symb,$courseid,$domain,$username)=@_;
                   7932:     my $code = &getCODE();
                   7933:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7934:     return "$num1:$num2";
                   7935: }
                   7936: 
1.366     albertel 7937: sub setup_random_from_rndseed {
                   7938:     my ($rndseed)=@_;
1.503     albertel 7939:     if ($rndseed =~/([,:])/) {
                   7940: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7941: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7942:     } else {
                   7943: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7944:     }
1.36      albertel 7945: }
                   7946: 
1.474     albertel 7947: sub latest_receipt_algorithm_id {
1.835     albertel 7948:     return 'receipt3';
1.474     albertel 7949: }
                   7950: 
1.480     www      7951: sub recunique {
                   7952:     my $fucourseid=shift;
                   7953:     my $unique;
1.835     albertel 7954:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7955: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7956: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7957:     } else {
                   7958: 	$unique=$perlvar{'lonReceipt'};
                   7959:     }
                   7960:     return unpack("%32C*",$unique);
                   7961: }
                   7962: 
                   7963: sub recprefix {
                   7964:     my $fucourseid=shift;
                   7965:     my $prefix;
1.835     albertel 7966:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7967: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7968: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7969:     } else {
                   7970: 	$prefix=$perlvar{'lonHostID'};
                   7971:     }
                   7972:     return unpack("%32C*",$prefix);
                   7973: }
                   7974: 
1.76      www      7975: sub ireceipt {
1.474     albertel 7976:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7977: 
                   7978:     my $return =&recprefix($fucourseid).'-';
                   7979: 
                   7980:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7981: 	$env{'request.state'} eq 'construct') {
                   7982: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7983: 	return $return;
                   7984:     }
                   7985: 
1.76      www      7986:     my $cuname=unpack("%32C*",$funame);
                   7987:     my $cudom=unpack("%32C*",$fudom);
                   7988:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7989:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7990:     my $cunique=&recunique($fucourseid);
1.474     albertel 7991:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7992:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7993: 
1.790     albertel 7994: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7995: 			       
                   7996: 	$return.= ($cunique%$cuname+
                   7997: 		   $cunique%$cudom+
                   7998: 		   $cusymb%$cuname+
                   7999: 		   $cusymb%$cudom+
                   8000: 		   $cucourseid%$cuname+
                   8001: 		   $cucourseid%$cudom+
                   8002: 		   $cpart%$cuname+
                   8003: 		   $cpart%$cudom);
                   8004:     } else {
                   8005: 	$return.= ($cunique%$cuname+
                   8006: 		   $cunique%$cudom+
                   8007: 		   $cusymb%$cuname+
                   8008: 		   $cusymb%$cudom+
                   8009: 		   $cucourseid%$cuname+
                   8010: 		   $cucourseid%$cudom);
                   8011:     }
                   8012:     return $return;
1.76      www      8013: }
                   8014: 
                   8015: sub receipt {
1.474     albertel 8016:     my ($part)=@_;
1.790     albertel 8017:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8018:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8019: }
1.260     ng       8020: 
1.790     albertel 8021: sub whichuser {
                   8022:     my ($passedsymb)=@_;
                   8023:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8024:     if (defined($env{'form.grade_symb'})) {
                   8025: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8026: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8027: 	if (!$allowed &&
                   8028: 	    exists($env{'request.course.sec'}) &&
                   8029: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8030: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8031: 			      '/'.$env{'request.course.sec'});
                   8032: 	}
                   8033: 	if ($allowed) {
                   8034: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8035: 	    $courseid=$tmp_courseid;
                   8036: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8037: 	    ($name)=&get_env_multiple('form.grade_username');
                   8038: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8039: 	}
                   8040:     }
                   8041:     if (!$passedsymb) {
                   8042: 	$symb=&symbread();
                   8043:     } else {
                   8044: 	$symb=$passedsymb;
                   8045:     }
                   8046:     $courseid=$env{'request.course.id'};
                   8047:     $domain=$env{'user.domain'};
                   8048:     $name=$env{'user.name'};
                   8049:     if ($name eq 'public' && $domain eq 'public') {
                   8050: 	if (!defined($env{'form.username'})) {
                   8051: 	    $env{'form.username'}.=time.rand(10000000);
                   8052: 	}
                   8053: 	$name.=$env{'form.username'};
                   8054:     }
                   8055:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8056: 
                   8057: }
                   8058: 
1.36      albertel 8059: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8060: # returns either the contents of the file or 
                   8061: # -1 if the file doesn't exist
1.481     raeburn  8062: #
                   8063: # if the target is a file that was uploaded via DOCS, 
                   8064: # a check will be made to see if a current copy exists on the local server,
                   8065: # if it does this will be served, otherwise a copy will be retrieved from
                   8066: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8067: # the local server.   
1.472     albertel 8068: 
1.36      albertel 8069: sub getfile {
1.538     albertel 8070:     my ($file) = @_;
1.609     banghart 8071:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8072:     &repcopy($file);
                   8073:     return &readfile($file);
                   8074: }
                   8075: 
                   8076: sub repcopy_userfile {
                   8077:     my ($file)=@_;
1.609     banghart 8078:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8079:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8080:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8081: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8082:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8083:     if (-e "$file") {
1.828     www      8084: # we already have a local copy, check it out
1.538     albertel 8085: 	my @fileinfo = stat($file);
1.828     www      8086: 	my $rtncode;
                   8087: 	my $info;
1.538     albertel 8088: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8089: 	if ($lwpresp ne 'ok') {
1.828     www      8090: # there is no such file anymore, even though we had a local copy
1.482     albertel 8091: 	    if ($rtncode eq '404') {
1.538     albertel 8092: 		unlink($file);
1.482     albertel 8093: 	    }
                   8094: 	    return -1;
                   8095: 	}
                   8096: 	if ($info < $fileinfo[9]) {
1.828     www      8097: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8098: 	    return 'ok';
1.828     www      8099: 	} else {
                   8100: # the file is outdated, get rid of it
                   8101: 	    unlink($file);
1.482     albertel 8102: 	}
1.828     www      8103:     }
                   8104: # one way or the other, at this point, we don't have the file
                   8105: # construct the correct path for the file
                   8106:     my @parts = ($cdom,$cnum); 
                   8107:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8108: 	push @parts, split(/\//,$1);
                   8109:     }
                   8110:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8111:     foreach my $part (@parts) {
                   8112: 	$path .= '/'.$part;
                   8113: 	if (!-e $path) {
                   8114: 	    mkdir($path,0770);
1.482     albertel 8115: 	}
                   8116:     }
1.828     www      8117: # now the path exists for sure
                   8118: # get a user agent
                   8119:     my $ua=new LWP::UserAgent;
                   8120:     my $transferfile=$file.'.in.transfer';
                   8121: # FIXME: this should flock
                   8122:     if (-e $transferfile) { return 'ok'; }
                   8123:     my $request;
                   8124:     $uri=~s/^\///;
1.838     albertel 8125:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8126:     my $response=$ua->request($request,$transferfile);
                   8127: # did it work?
                   8128:     if ($response->is_error()) {
                   8129: 	unlink($transferfile);
                   8130: 	&logthis("Userfile repcopy failed for $uri");
                   8131: 	return -1;
                   8132:     }
                   8133: # worked, rename the transfer file
                   8134:     rename($transferfile,$file);
1.607     raeburn  8135:     return 'ok';
1.481     raeburn  8136: }
                   8137: 
1.517     albertel 8138: sub tokenwrapper {
                   8139:     my $uri=shift;
1.552     albertel 8140:     $uri=~s|^http\://([^/]+)||;
                   8141:     $uri=~s|^/||;
1.620     albertel 8142:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8143:     my $token=$1;
1.552     albertel 8144:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8145:     if ($udom && $uname && $file) {
                   8146: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8147:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8148:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8149:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8150:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8151:     } else {
                   8152:         return '/adm/notfound.html';
                   8153:     }
                   8154: }
                   8155: 
1.828     www      8156: # call with reqtype HEAD: get last modification time
                   8157: # call with reqtype GET: get the file contents
                   8158: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8159: #
1.481     raeburn  8160: sub getuploaded {
                   8161:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8162:     $uri=~s/^\///;
1.838     albertel 8163:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8164:     my $ua=new LWP::UserAgent;
                   8165:     my $request=new HTTP::Request($reqtype,$uri);
                   8166:     my $response=$ua->request($request);
                   8167:     $$rtncode = $response->code;
1.482     albertel 8168:     if (! $response->is_success()) {
                   8169: 	return 'failed';
                   8170:     }      
                   8171:     if ($reqtype eq 'HEAD') {
1.486     www      8172: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8173:     } elsif ($reqtype eq 'GET') {
                   8174: 	$$info = $response->content;
1.472     albertel 8175:     }
1.482     albertel 8176:     return 'ok';
1.36      albertel 8177: }
                   8178: 
1.481     raeburn  8179: sub readfile {
                   8180:     my $file = shift;
                   8181:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8182:     my $fh;
                   8183:     open($fh,"<$file");
                   8184:     my $a='';
1.800     albertel 8185:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8186:     return $a;
                   8187: }
                   8188: 
1.36      albertel 8189: sub filelocation {
1.590     banghart 8190:     my ($dir,$file) = @_;
                   8191:     my $location;
                   8192:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8193: 
                   8194:     if ($file =~ m-^/adm/-) {
                   8195: 	$file=~s-^/adm/wrapper/-/-;
                   8196: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8197:     }
1.882     albertel 8198: 
1.590     banghart 8199:     if ($file=~m:^/~:) { # is a contruction space reference
                   8200:         $location = $file;
                   8201:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8202:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8203: 	# is a correct contruction space reference
                   8204:         $location = $file;
1.956     raeburn  8205:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8206:         $location = $file;
1.609     banghart 8207:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8208:         my ($udom,$uname,$filename)=
1.811     albertel 8209:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8210:         my $home=&homeserver($uname,$udom);
                   8211:         my $is_me=0;
                   8212:         my @ids=&current_machine_ids();
                   8213:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8214:         if ($is_me) {
1.955     raeburn  8215:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8216:         } else {
                   8217:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8218:   	      $udom.'/'.$uname.'/'.$filename;
                   8219:         }
1.882     albertel 8220:     } elsif ($file =~ m-^/adm/-) {
                   8221: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8222:     } else {
                   8223:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8224:         $file=~s:^/res/:/:;
                   8225:         if ( !( $file =~ m:^/:) ) {
                   8226:             $location = $dir. '/'.$file;
                   8227:         } else {
                   8228:             $location = '/home/httpd/html/res'.$file;
                   8229:         }
1.59      albertel 8230:     }
1.590     banghart 8231:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8232:     while ($location=~m{/\.\./}) {
                   8233: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8234: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8235: 	} else {
                   8236: 	    $location=~ s{/\.\./}{/}g;
                   8237: 	}
                   8238:     } #remove dir/..
1.590     banghart 8239:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8240:     return $location;
1.46      www      8241: }
1.36      albertel 8242: 
1.46      www      8243: sub hreflocation {
                   8244:     my ($dir,$file)=@_;
1.460     albertel 8245:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8246: 	$file=filelocation($dir,$file);
1.700     albertel 8247:     } elsif ($file=~m-^/adm/-) {
                   8248: 	$file=~s-^/adm/wrapper/-/-;
                   8249: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8250:     }
                   8251:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8252: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8253:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8254: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8255:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8256: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8257: 	    -/uploaded/$1/$2/-x;
1.46      www      8258:     }
1.913     albertel 8259:     if ($file=~ m{^/userfiles/}) {
                   8260: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8261:     }
1.462     albertel 8262:     return $file;
1.465     albertel 8263: }
                   8264: 
                   8265: sub current_machine_domains {
1.853     albertel 8266:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8267: }
                   8268: 
                   8269: sub machine_domains {
                   8270:     my ($hostname) = @_;
1.465     albertel 8271:     my @domains;
1.838     albertel 8272:     my %hostname = &all_hostnames();
1.465     albertel 8273:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8274: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8275: 	if ($hostname eq $name) {
1.844     albertel 8276: 	    push(@domains,&host_domain($id));
1.465     albertel 8277: 	}
                   8278:     }
                   8279:     return @domains;
                   8280: }
                   8281: 
                   8282: sub current_machine_ids {
1.853     albertel 8283:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8284: }
                   8285: 
                   8286: sub machine_ids {
                   8287:     my ($hostname) = @_;
                   8288:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8289:     my @ids;
1.888     albertel 8290:     my %name_to_host = &all_names();
1.889     albertel 8291:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8292: 	return @{ $name_to_host{$hostname} };
                   8293:     }
                   8294:     return;
1.31      www      8295: }
                   8296: 
1.824     raeburn  8297: sub additional_machine_domains {
                   8298:     my @domains;
                   8299:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8300:     while( my $line = <$fh>) {
                   8301:         $line =~ s/\s//g;
                   8302:         push(@domains,$line);
                   8303:     }
                   8304:     return @domains;
                   8305: }
                   8306: 
                   8307: sub default_login_domain {
                   8308:     my $domain = $perlvar{'lonDefDomain'};
                   8309:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8310:     foreach my $posdom (&current_machine_domains(),
                   8311:                         &additional_machine_domains()) {
                   8312:         if (lc($posdom) eq lc($testdomain)) {
                   8313:             $domain=$posdom;
                   8314:             last;
                   8315:         }
                   8316:     }
                   8317:     return $domain;
                   8318: }
                   8319: 
1.31      www      8320: # ------------------------------------------------------------- Declutters URLs
                   8321: 
                   8322: sub declutter {
                   8323:     my $thisfn=shift;
1.569     albertel 8324:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8325:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8326:     $thisfn=~s/^\///;
1.697     albertel 8327:     $thisfn=~s|^adm/wrapper/||;
                   8328:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8329:     $thisfn=~s/^res\///;
1.235     www      8330:     $thisfn=~s/\?.+$//;
1.268     www      8331:     return $thisfn;
                   8332: }
                   8333: 
                   8334: # ------------------------------------------------------------- Clutter up URLs
                   8335: 
                   8336: sub clutter {
                   8337:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8338:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8339: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8340:        $thisfn='/res'.$thisfn; 
                   8341:     }
1.694     albertel 8342:     if ($thisfn !~m|/adm|) {
1.695     albertel 8343: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8344: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8345: 	} else {
                   8346: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8347: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8348: 	    if ($embstyle eq 'ssi'
                   8349: 		|| ($embstyle eq 'hdn')
                   8350: 		|| ($embstyle eq 'rat')
                   8351: 		|| ($embstyle eq 'prv')
                   8352: 		|| ($embstyle eq 'ign')) {
                   8353: 		#do nothing with these
                   8354: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8355: 		|| ($embstyle eq 'emb')
                   8356: 		|| ($embstyle eq 'wrp')) {
                   8357: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8358: 	    } elsif ($embstyle eq 'unk'
                   8359: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8360: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8361: 	    } else {
1.718     www      8362: #		&logthis("Got a blank emb style");
1.695     albertel 8363: 	    }
1.694     albertel 8364: 	}
                   8365:     }
1.31      www      8366:     return $thisfn;
1.12      www      8367: }
                   8368: 
1.787     albertel 8369: sub clutter_with_no_wrapper {
                   8370:     my $uri = &clutter(shift);
                   8371:     if ($uri =~ m-^/adm/-) {
                   8372: 	$uri =~ s-^/adm/wrapper/-/-;
                   8373: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8374:     }
                   8375:     return $uri;
                   8376: }
                   8377: 
1.557     albertel 8378: sub freeze_escape {
                   8379:     my ($value)=@_;
                   8380:     if (ref($value)) {
                   8381: 	$value=&nfreeze($value);
                   8382: 	return '__FROZEN__'.&escape($value);
                   8383:     }
                   8384:     return &escape($value);
                   8385: }
                   8386: 
1.11      www      8387: 
1.557     albertel 8388: sub thaw_unescape {
                   8389:     my ($value)=@_;
                   8390:     if ($value =~ /^__FROZEN__/) {
                   8391: 	substr($value,0,10,undef);
                   8392: 	$value=&unescape($value);
                   8393: 	return &thaw($value);
                   8394:     }
                   8395:     return &unescape($value);
                   8396: }
                   8397: 
1.436     albertel 8398: sub correct_line_ends {
                   8399:     my ($result)=@_;
                   8400:     $$result =~s/\r\n/\n/mg;
                   8401:     $$result =~s/\r/\n/mg;
1.415     albertel 8402: }
1.1       albertel 8403: # ================================================================ Main Program
                   8404: 
1.184     www      8405: sub goodbye {
1.204     albertel 8406:    &logthis("Starting Shut down");
1.443     albertel 8407: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8408:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8409: #converted
1.599     albertel 8410: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8411:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8412: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8413: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8414: #1.1 only
1.870     albertel 8415: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8416: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8417: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8418: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8419:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8420:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8421:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8422:    &flushcourselogs();
                   8423:    &logthis("Shutting down");
                   8424: }
                   8425: 
1.852     albertel 8426: sub get_dns {
1.869     albertel 8427:     my ($url,$func,$ignore_cache) = @_;
                   8428:     if (!$ignore_cache) {
                   8429: 	my ($content,$cached)=
                   8430: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8431: 	if ($cached) {
                   8432: 	    &$func($content);
                   8433: 	    return;
                   8434: 	}
                   8435:     }
                   8436: 
                   8437:     my %alldns;
1.852     albertel 8438:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8439:     foreach my $dns (<$config>) {
                   8440: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8441: 	$alldns{$1} = 1;
                   8442:     }
                   8443:     while (%alldns) {
                   8444: 	my ($dns) = keys(%alldns);
                   8445: 	delete($alldns{$dns});
1.852     albertel 8446: 	my $ua=new LWP::UserAgent;
                   8447: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8448: 	my $response=$ua->request($request);
                   8449: 	next if ($response->is_error());
                   8450: 	my @content = split("\n",$response->content);
1.869     albertel 8451: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8452: 	&$func(\@content);
1.869     albertel 8453: 	return;
1.852     albertel 8454:     }
                   8455:     close($config);
1.871     albertel 8456:     my $which = (split('/',$url))[3];
                   8457:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8458:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8459:     my @content = <$config>;
                   8460:     &$func(\@content);
                   8461:     return;
1.852     albertel 8462: }
1.327     albertel 8463: # ------------------------------------------------------------ Read domain file
                   8464: {
1.852     albertel 8465:     my $loaded;
1.846     albertel 8466:     my %domain;
                   8467: 
1.852     albertel 8468:     sub parse_domain_tab {
                   8469: 	my ($lines) = @_;
                   8470: 	foreach my $line (@$lines) {
                   8471: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8472: 
1.846     albertel 8473: 	    chomp($line);
1.852     albertel 8474: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8475: 	    my %this_domain;
                   8476: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8477: 			       'lang_def', 'city', 'longi', 'lati',
                   8478: 			       'primary') {
                   8479: 		$this_domain{$field} = shift(@elements);
                   8480: 	    }
                   8481: 	    $domain{$name} = \%this_domain;
1.852     albertel 8482: 	}
                   8483:     }
1.864     albertel 8484: 
                   8485:     sub reset_domain_info {
                   8486: 	undef($loaded);
                   8487: 	undef(%domain);
                   8488:     }
                   8489: 
1.852     albertel 8490:     sub load_domain_tab {
1.869     albertel 8491: 	my ($ignore_cache) = @_;
                   8492: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8493: 	my $fh;
                   8494: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8495: 	    my @lines = <$fh>;
                   8496: 	    &parse_domain_tab(\@lines);
1.448     albertel 8497: 	}
1.852     albertel 8498: 	close($fh);
                   8499: 	$loaded = 1;
1.327     albertel 8500:     }
1.846     albertel 8501: 
                   8502:     sub domain {
1.852     albertel 8503: 	&load_domain_tab() if (!$loaded);
                   8504: 
1.846     albertel 8505: 	my ($name,$what) = @_;
                   8506: 	return if ( !exists($domain{$name}) );
                   8507: 
                   8508: 	if (!$what) {
                   8509: 	    return $domain{$name}{'description'};
                   8510: 	}
                   8511: 	return $domain{$name}{$what};
                   8512:     }
1.327     albertel 8513: }
                   8514: 
                   8515: 
1.1       albertel 8516: # ------------------------------------------------------------- Read hosts file
                   8517: {
1.838     albertel 8518:     my %hostname;
1.844     albertel 8519:     my %hostdom;
1.845     albertel 8520:     my %libserv;
1.852     albertel 8521:     my $loaded;
1.888     albertel 8522:     my %name_to_host;
1.852     albertel 8523: 
                   8524:     sub parse_hosts_tab {
                   8525: 	my ($file) = @_;
                   8526: 	foreach my $configline (@$file) {
                   8527: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8528: 	    next if ($configline =~ /^\^/);
                   8529: 	    chomp($configline);
                   8530: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8531: 	    $name=~s/\s//g;
                   8532: 	    if ($id && $domain && $role && $name) {
                   8533: 		$hostname{$id}=$name;
1.888     albertel 8534: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8535: 		$hostdom{$id}=$domain;
                   8536: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8537: 	    }
                   8538: 	}
                   8539:     }
1.864     albertel 8540:     
                   8541:     sub reset_hosts_info {
1.897     albertel 8542: 	&purge_remembered();
1.864     albertel 8543: 	&reset_domain_info();
                   8544: 	&reset_hosts_ip_info();
1.892     albertel 8545: 	undef(%name_to_host);
1.864     albertel 8546: 	undef(%hostname);
                   8547: 	undef(%hostdom);
                   8548: 	undef(%libserv);
                   8549: 	undef($loaded);
                   8550:     }
1.1       albertel 8551: 
1.852     albertel 8552:     sub load_hosts_tab {
1.869     albertel 8553: 	my ($ignore_cache) = @_;
                   8554: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8555: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8556: 	my @config = <$config>;
                   8557: 	&parse_hosts_tab(\@config);
                   8558: 	close($config);
                   8559: 	$loaded=1;
1.1       albertel 8560:     }
1.852     albertel 8561: 
1.838     albertel 8562:     sub hostname {
1.852     albertel 8563: 	&load_hosts_tab() if (!$loaded);
                   8564: 
1.838     albertel 8565: 	my ($lonid) = @_;
                   8566: 	return $hostname{$lonid};
                   8567:     }
1.845     albertel 8568: 
1.838     albertel 8569:     sub all_hostnames {
1.852     albertel 8570: 	&load_hosts_tab() if (!$loaded);
                   8571: 
1.838     albertel 8572: 	return %hostname;
                   8573:     }
1.845     albertel 8574: 
1.888     albertel 8575:     sub all_names {
                   8576: 	&load_hosts_tab() if (!$loaded);
                   8577: 
                   8578: 	return %name_to_host;
                   8579:     }
                   8580: 
1.845     albertel 8581:     sub is_library {
1.852     albertel 8582: 	&load_hosts_tab() if (!$loaded);
                   8583: 
1.845     albertel 8584: 	return exists($libserv{$_[0]});
                   8585:     }
                   8586: 
                   8587:     sub all_library {
1.852     albertel 8588: 	&load_hosts_tab() if (!$loaded);
                   8589: 
1.845     albertel 8590: 	return %libserv;
                   8591:     }
                   8592: 
1.841     albertel 8593:     sub get_servers {
1.852     albertel 8594: 	&load_hosts_tab() if (!$loaded);
                   8595: 
1.841     albertel 8596: 	my ($domain,$type) = @_;
                   8597: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8598: 	                                          : %hostname;
                   8599: 	my %result;
1.842     albertel 8600: 	if (ref($domain) eq 'ARRAY') {
                   8601: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8602: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8603: 		    $result{$host} = $hostname;
                   8604: 		}
                   8605: 	    }
                   8606: 	} else {
                   8607: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8608: 		if ($hostdom{$host} eq $domain) {
                   8609: 		    $result{$host} = $hostname;
                   8610: 		}
1.841     albertel 8611: 	    }
                   8612: 	}
                   8613: 	return %result;
                   8614:     }
1.845     albertel 8615: 
1.844     albertel 8616:     sub host_domain {
1.852     albertel 8617: 	&load_hosts_tab() if (!$loaded);
                   8618: 
1.844     albertel 8619: 	my ($lonid) = @_;
                   8620: 	return $hostdom{$lonid};
                   8621:     }
                   8622: 
1.841     albertel 8623:     sub all_domains {
1.852     albertel 8624: 	&load_hosts_tab() if (!$loaded);
                   8625: 
1.841     albertel 8626: 	my %seen;
                   8627: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8628: 	return @uniq;
                   8629:     }
1.1       albertel 8630: }
                   8631: 
1.847     albertel 8632: { 
                   8633:     my %iphost;
1.856     albertel 8634:     my %name_to_ip;
                   8635:     my %lonid_to_ip;
1.869     albertel 8636: 
1.847     albertel 8637:     sub get_hosts_from_ip {
                   8638: 	my ($ip) = @_;
                   8639: 	my %iphosts = &get_iphost();
                   8640: 	if (ref($iphosts{$ip})) {
                   8641: 	    return @{$iphosts{$ip}};
                   8642: 	}
                   8643: 	return;
1.839     albertel 8644:     }
1.864     albertel 8645:     
                   8646:     sub reset_hosts_ip_info {
                   8647: 	undef(%iphost);
                   8648: 	undef(%name_to_ip);
                   8649: 	undef(%lonid_to_ip);
                   8650:     }
1.856     albertel 8651: 
                   8652:     sub get_host_ip {
                   8653: 	my ($lonid) = @_;
                   8654: 	if (exists($lonid_to_ip{$lonid})) {
                   8655: 	    return $lonid_to_ip{$lonid};
                   8656: 	}
                   8657: 	my $name=&hostname($lonid);
                   8658:    	my $ip = gethostbyname($name);
                   8659: 	return if (!$ip || length($ip) ne 4);
                   8660: 	$ip=inet_ntoa($ip);
                   8661: 	$name_to_ip{$name}   = $ip;
                   8662: 	$lonid_to_ip{$lonid} = $ip;
                   8663: 	return $ip;
                   8664:     }
1.847     albertel 8665:     
                   8666:     sub get_iphost {
1.869     albertel 8667: 	my ($ignore_cache) = @_;
1.894     albertel 8668: 
1.869     albertel 8669: 	if (!$ignore_cache) {
                   8670: 	    if (%iphost) {
                   8671: 		return %iphost;
                   8672: 	    }
                   8673: 	    my ($ip_info,$cached)=
                   8674: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8675: 	    if ($cached) {
                   8676: 		%iphost      = %{$ip_info->[0]};
                   8677: 		%name_to_ip  = %{$ip_info->[1]};
                   8678: 		%lonid_to_ip = %{$ip_info->[2]};
                   8679: 		return %iphost;
                   8680: 	    }
                   8681: 	}
1.894     albertel 8682: 
                   8683: 	# get yesterday's info for fallback
                   8684: 	my %old_name_to_ip;
                   8685: 	my ($ip_info,$cached)=
                   8686: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8687: 	if ($cached) {
                   8688: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8689: 	}
                   8690: 
1.888     albertel 8691: 	my %name_to_host = &all_names();
                   8692: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8693: 	    my $ip;
                   8694: 	    if (!exists($name_to_ip{$name})) {
                   8695: 		$ip = gethostbyname($name);
                   8696: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8697: 		    if (defined($old_name_to_ip{$name})) {
                   8698: 			$ip = $old_name_to_ip{$name};
                   8699: 			&logthis("Can't find $name defaulting to old $ip");
                   8700: 		    } else {
                   8701: 			&logthis("Name $name no IP found");
                   8702: 			next;
                   8703: 		    }
                   8704: 		} else {
                   8705: 		    $ip=inet_ntoa($ip);
1.847     albertel 8706: 		}
                   8707: 		$name_to_ip{$name} = $ip;
                   8708: 	    } else {
                   8709: 		$ip = $name_to_ip{$name};
1.653     albertel 8710: 	    }
1.888     albertel 8711: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8712: 		$lonid_to_ip{$id} = $ip;
                   8713: 	    }
                   8714: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8715: 	}
1.869     albertel 8716: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8717: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8718: 				      48*60*60);
1.869     albertel 8719: 
1.847     albertel 8720: 	return %iphost;
1.598     albertel 8721:     }
                   8722: }
                   8723: 
1.862     albertel 8724: BEGIN {
                   8725: 
                   8726: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8727:     unless ($readit) {
                   8728: {
                   8729:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8730:     %perlvar = (%perlvar,%{$configvars});
                   8731: }
                   8732: 
                   8733: 
1.1       albertel 8734: # ------------------------------------------------------ Read spare server file
                   8735: {
1.448     albertel 8736:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8737: 
                   8738:     while (my $configline=<$config>) {
                   8739:        chomp($configline);
1.284     matthew  8740:        if ($configline) {
1.784     albertel 8741: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8742: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8743: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8744:        }
                   8745:     }
1.448     albertel 8746:     close($config);
1.1       albertel 8747: }
1.11      www      8748: # ------------------------------------------------------------ Read permissions
                   8749: {
1.448     albertel 8750:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8751: 
                   8752:     while (my $configline=<$config>) {
1.448     albertel 8753: 	chomp($configline);
                   8754: 	if ($configline) {
                   8755: 	    my ($role,$perm)=split(/ /,$configline);
                   8756: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8757: 	}
1.11      www      8758:     }
1.448     albertel 8759:     close($config);
1.11      www      8760: }
                   8761: 
                   8762: # -------------------------------------------- Read plain texts for permissions
                   8763: {
1.448     albertel 8764:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8765: 
                   8766:     while (my $configline=<$config>) {
1.448     albertel 8767: 	chomp($configline);
                   8768: 	if ($configline) {
1.742     raeburn  8769: 	    my ($short,@plain)=split(/:/,$configline);
                   8770:             %{$prp{$short}} = ();
                   8771: 	    if (@plain > 0) {
                   8772:                 $prp{$short}{'std'} = $plain[0];
                   8773:                 for (my $i=1; $i<@plain; $i++) {
                   8774:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8775:                 }
                   8776:             }
1.448     albertel 8777: 	}
1.135     www      8778:     }
1.448     albertel 8779:     close($config);
1.135     www      8780: }
                   8781: 
                   8782: # ---------------------------------------------------------- Read package table
                   8783: {
1.448     albertel 8784:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8785: 
                   8786:     while (my $configline=<$config>) {
1.483     albertel 8787: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8788: 	chomp($configline);
                   8789: 	my ($short,$plain)=split(/:/,$configline);
                   8790: 	my ($pack,$name)=split(/\&/,$short);
                   8791: 	if ($plain ne '') {
                   8792: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8793: 	    $packagetab{$short}=$plain; 
                   8794: 	}
1.11      www      8795:     }
1.448     albertel 8796:     close($config);
1.329     matthew  8797: }
                   8798: 
                   8799: # ------------- set up temporary directory
                   8800: {
                   8801:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8802: 
1.11      www      8803: }
                   8804: 
1.794     albertel 8805: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8806: 				'compress_threshold'=> 20_000,
                   8807:  			        });
1.185     www      8808: 
1.281     www      8809: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8810: $dumpcount=0;
1.958     www      8811: $locknum=0;
1.22      www      8812: 
1.163     harris41 8813: &logtouch();
1.672     albertel 8814: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8815: $readit=1;
1.564     albertel 8816:     {
                   8817: 	use integer;
                   8818: 	my $test=(2**32)+1;
1.568     albertel 8819: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8820: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8821:     }
1.195     www      8822: }
1.1       albertel 8823: }
1.179     www      8824: 
1.1       albertel 8825: 1;
1.191     harris41 8826: __END__
                   8827: 
1.243     albertel 8828: =pod
                   8829: 
1.191     harris41 8830: =head1 NAME
                   8831: 
1.243     albertel 8832: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8833: 
                   8834: =head1 SYNOPSIS
                   8835: 
1.243     albertel 8836: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8837: 
                   8838:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8839: 
1.243     albertel 8840: Common parameters:
                   8841: 
                   8842: =over 4
                   8843: 
                   8844: =item *
                   8845: 
                   8846: $uname : an internal username (if $cname expecting a course Id specifically)
                   8847: 
                   8848: =item *
                   8849: 
                   8850: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8851: 
                   8852: =item *
                   8853: 
                   8854: $symb : a resource instance identifier
                   8855: 
                   8856: =item *
                   8857: 
                   8858: $namespace : the name of a .db file that contains the data needed or
                   8859: being set.
                   8860: 
                   8861: =back
                   8862: 
1.394     bowersj2 8863: =head1 OVERVIEW
1.191     harris41 8864: 
1.394     bowersj2 8865: lonnet provides subroutines which interact with the
                   8866: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8867: about classes, users, and resources.
1.243     albertel 8868: 
                   8869: For many of these objects you can also use this to store data about
                   8870: them or modify them in various ways.
1.191     harris41 8871: 
1.394     bowersj2 8872: =head2 Symbs
1.191     harris41 8873: 
1.394     bowersj2 8874: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8875: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8876: map, the resource number of the resource in the map, and the URL of
                   8877: the resource itself. The latter is somewhat redundant, but might help
                   8878: if maps change.
                   8879: 
                   8880: An example is
                   8881: 
                   8882:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8883: 
                   8884: The respective map entry is
                   8885: 
                   8886:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8887:   title="Problem 2">
                   8888:  </resource>
                   8889: 
                   8890: Symbs are used by the random number generator, as well as to store and
                   8891: restore data specific to a certain instance of for example a problem.
                   8892: 
                   8893: =head2 Storing And Retrieving Data
                   8894: 
                   8895: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8896: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8897: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8898: is is the non-critical message twin of cstore. These functions are for
                   8899: handlers to store a perl hash to a user's permanent data space in an
                   8900: easy manner, and to retrieve it again on another call. It is expected
                   8901: that a handler would use this once at the beginning to retrieve data,
                   8902: and then again once at the end to send only the new data back.
                   8903: 
                   8904: The data is stored in the user's data directory on the user's
                   8905: homeserver under the ID of the course.
                   8906: 
                   8907: The hash that is returned by restore will have all of the previous
                   8908: value for all of the elements of the hash.
                   8909: 
                   8910: Example:
                   8911: 
                   8912:  #creating a hash
                   8913:  my %hash;
                   8914:  $hash{'foo'}='bar';
                   8915: 
                   8916:  #storing it
                   8917:  &Apache::lonnet::cstore(\%hash);
                   8918: 
                   8919:  #changing a value
                   8920:  $hash{'foo'}='notbar';
                   8921: 
                   8922:  #adding a new value
                   8923:  $hash{'bar'}='foo';
                   8924:  &Apache::lonnet::cstore(\%hash);
                   8925: 
                   8926:  #retrieving the hash
                   8927:  my %history=&Apache::lonnet::restore();
                   8928: 
                   8929:  #print the hash
                   8930:  foreach my $key (sort(keys(%history))) {
                   8931:    print("\%history{$key} = $history{$key}");
                   8932:  }
                   8933: 
                   8934: Will print out:
1.191     harris41 8935: 
1.394     bowersj2 8936:  %history{1:foo} = bar
                   8937:  %history{1:keys} = foo:timestamp
                   8938:  %history{1:timestamp} = 990455579
                   8939:  %history{2:bar} = foo
                   8940:  %history{2:foo} = notbar
                   8941:  %history{2:keys} = foo:bar:timestamp
                   8942:  %history{2:timestamp} = 990455580
                   8943:  %history{bar} = foo
                   8944:  %history{foo} = notbar
                   8945:  %history{timestamp} = 990455580
                   8946:  %history{version} = 2
                   8947: 
                   8948: Note that the special hash entries C<keys>, C<version> and
                   8949: C<timestamp> were added to the hash. C<version> will be equal to the
                   8950: total number of versions of the data that have been stored. The
                   8951: C<timestamp> attribute will be the UNIX time the hash was
                   8952: stored. C<keys> is available in every historical section to list which
                   8953: keys were added or changed at a specific historical revision of a
                   8954: hash.
                   8955: 
                   8956: B<Warning>: do not store the hash that restore returns directly. This
                   8957: will cause a mess since it will restore the historical keys as if the
                   8958: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8959: 
1.394     bowersj2 8960: Calling convention:
1.191     harris41 8961: 
1.394     bowersj2 8962:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8963:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8964: 
1.394     bowersj2 8965: For more detailed information, see lonnet specific documentation.
1.191     harris41 8966: 
1.394     bowersj2 8967: =head1 RETURN MESSAGES
1.191     harris41 8968: 
1.394     bowersj2 8969: =over 4
1.191     harris41 8970: 
1.394     bowersj2 8971: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8972: 
1.394     bowersj2 8973: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8974: when the connection is brought back up
1.191     harris41 8975: 
1.394     bowersj2 8976: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8977: for later delivery
1.191     harris41 8978: 
1.394     bowersj2 8979: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8980: 
1.394     bowersj2 8981: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8982: that was requested
1.191     harris41 8983: 
1.243     albertel 8984: =back
1.191     harris41 8985: 
1.243     albertel 8986: =head1 PUBLIC SUBROUTINES
1.191     harris41 8987: 
1.243     albertel 8988: =head2 Session Environment Functions
1.191     harris41 8989: 
1.243     albertel 8990: =over 4
1.191     harris41 8991: 
1.394     bowersj2 8992: =item * 
                   8993: X<appenv()>
1.949     raeburn  8994: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 8995: the user envirnoment file, and will be restored for each access this
1.620     albertel 8996: user makes during this session, also modifies the %env for the current
1.949     raeburn  8997: process. Optional rolesarrayref - if defined contains a reference to an array
                   8998: of roles which are exempt from the restriction on modifying user.role entries 
                   8999: in the user's environment.db and in %env.    
1.191     harris41 9000: 
                   9001: =item *
1.394     bowersj2 9002: X<delenv()>
                   9003: B<delenv($regexp)>: removes all items from the session
                   9004: environment file that matches the regular expression in $regexp. The
1.620     albertel 9005: values are also delted from the current processes %env.
1.191     harris41 9006: 
1.795     albertel 9007: =item * get_env_multiple($name) 
                   9008: 
                   9009: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9010: values may be defined and end up as an array ref.
                   9011: 
                   9012: returns an array of values
                   9013: 
1.243     albertel 9014: =back
                   9015: 
                   9016: =head2 User Information
1.191     harris41 9017: 
1.243     albertel 9018: =over 4
1.191     harris41 9019: 
                   9020: =item *
1.394     bowersj2 9021: X<queryauthenticate()>
                   9022: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9023: authentication scheme
                   9024: 
                   9025: =item *
1.394     bowersj2 9026: X<authenticate()>
                   9027: B<authenticate($uname,$upass,$udom)>: try to
                   9028: authenticate user from domain's lib servers (first use the current
                   9029: one). C<$upass> should be the users password.
1.191     harris41 9030: 
                   9031: =item *
1.394     bowersj2 9032: X<homeserver()>
                   9033: B<homeserver($uname,$udom)>: find the server which has
                   9034: the user's directory and files (there must be only one), this caches
                   9035: the answer, and also caches if there is a borken connection.
1.191     harris41 9036: 
                   9037: =item *
1.394     bowersj2 9038: X<idget()>
                   9039: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9040: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9041: username, and only 1 username per ID in a specific domain) (returns
                   9042: hash: id=>name,id=>name)
1.191     harris41 9043: 
                   9044: =item *
1.394     bowersj2 9045: X<idrget()>
                   9046: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9047: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9048: 
                   9049: =item *
1.394     bowersj2 9050: X<idput()>
                   9051: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9052: 
                   9053: =item *
1.394     bowersj2 9054: X<rolesinit()>
                   9055: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9056: 
                   9057: =item *
1.551     albertel 9058: X<getsection()>
                   9059: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9060: course $cname, return section name/number or '' for "not in course"
                   9061: and '-1' for "no section"
                   9062: 
                   9063: =item *
1.394     bowersj2 9064: X<userenvironment()>
                   9065: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9066: passed in @what from the requested user's environment, returns a hash
                   9067: 
1.858     raeburn  9068: =item * 
                   9069: X<userlog_query()>
1.859     albertel 9070: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9071: activity.log file. %filters defines filters applied when parsing the
                   9072: log file. These can be start or end timestamps, or the type of action
                   9073: - log to look for Login or Logout events, check for Checkin or
                   9074: Checkout, role for role selection. The response is in the form
                   9075: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9076: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9077: 
1.243     albertel 9078: =back
                   9079: 
                   9080: =head2 User Roles
                   9081: 
                   9082: =over 4
                   9083: 
                   9084: =item *
                   9085: 
1.810     raeburn  9086: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9087:  F: full access
                   9088:  U,I,K: authentication modes (cxx only)
                   9089:  '': forbidden
                   9090:  1: user needs to choose course
                   9091:  2: browse allowed
1.766     albertel 9092:  A: passphrase authentication needed
1.243     albertel 9093: 
                   9094: =item *
                   9095: 
                   9096: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9097: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9098: and course level
                   9099: 
                   9100: =item *
                   9101: 
                   9102: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9103: explanation of a user role term
                   9104: 
1.832     raeburn  9105: =item *
                   9106: 
1.935     raeburn  9107: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9108: All arguments are optional. Returns a hash of a roles, either for
                   9109: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9110: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9111: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9112: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9113: For each key, value is set to colon-separated start and end times for
                   9114: the role.  If no username and domain are specified, will default to
1.934     raeburn  9115: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9116: of role statuses (active, future or previous), roles 
                   9117: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9118: to restrict the list of roles reported. If no array ref is 
                   9119: provided for types, will default to return only active roles.
1.834     albertel 9120: 
1.243     albertel 9121: =back
                   9122: 
                   9123: =head2 User Modification
                   9124: 
                   9125: =over 4
                   9126: 
                   9127: =item *
                   9128: 
1.957     raeburn  9129: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9130: user for the level given by URL.  Optional start and end dates (leave empty
                   9131: string or zero for "no date")
1.191     harris41 9132: 
                   9133: =item *
                   9134: 
1.243     albertel 9135: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9136: change a users, password, possible return values are: ok,
                   9137: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9138: refused
1.191     harris41 9139: 
                   9140: =item *
                   9141: 
1.243     albertel 9142: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9143: 
                   9144: =item *
                   9145: 
1.243     albertel 9146: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9147: modify user
1.191     harris41 9148: 
                   9149: =item *
                   9150: 
1.286     matthew  9151: modifystudent
                   9152: 
1.957     raeburn  9153: modify a student's enrollment and identification information.
1.286     matthew  9154: The course id is resolved based on the current users environment.  
                   9155: This means the envoking user must be a course coordinator or otherwise
                   9156: associated with a course.
                   9157: 
1.297     matthew  9158: This call is essentially a wrapper for lonnet::modifyuser and
                   9159: lonnet::modify_student_enrollment
1.286     matthew  9160: 
                   9161: Inputs: 
                   9162: 
                   9163: =over 4
                   9164: 
1.957     raeburn  9165: =item B<$udom> Student's loncapa domain
1.286     matthew  9166: 
1.957     raeburn  9167: =item B<$uname> Student's loncapa login name
1.286     matthew  9168: 
1.957     raeburn  9169: =item B<$uid> Student's id/student number
1.286     matthew  9170: 
1.957     raeburn  9171: =item B<$umode> Student's authentication mode
1.286     matthew  9172: 
1.957     raeburn  9173: =item B<$upass> Student's password
1.286     matthew  9174: 
1.957     raeburn  9175: =item B<$first> Student's first name
1.286     matthew  9176: 
1.957     raeburn  9177: =item B<$middle> Student's middle name
1.286     matthew  9178: 
1.957     raeburn  9179: =item B<$last> Student's last name
1.286     matthew  9180: 
1.957     raeburn  9181: =item B<$gene> Student's generation
1.286     matthew  9182: 
1.957     raeburn  9183: =item B<$usec> Student's section in course
1.286     matthew  9184: 
                   9185: =item B<$end> Unix time of the roles expiration
                   9186: 
                   9187: =item B<$start> Unix time of the roles start date
                   9188: 
                   9189: =item B<$forceid> If defined, allow $uid to be changed
                   9190: 
                   9191: =item B<$desiredhome> server to use as home server for student
                   9192: 
1.957     raeburn  9193: =item B<$email> Student's permanent e-mail address
                   9194: 
                   9195: =item B<$type> Type of enrollment (auto or manual)
                   9196: 
                   9197: =item B<$locktype>
                   9198: 
                   9199: =item B<$cid>
                   9200: 
                   9201: =item B<$selfenroll>
                   9202: 
                   9203: =item B<$context>
                   9204: 
1.286     matthew  9205: =back
1.297     matthew  9206: 
                   9207: =item *
                   9208: 
                   9209: modify_student_enrollment
                   9210: 
                   9211: Change a students enrollment status in a class.  The environment variable
                   9212: 'role.request.course' must be defined for this function to proceed.
                   9213: 
                   9214: Inputs:
                   9215: 
                   9216: =over 4
                   9217: 
                   9218: =item $udom, students domain
                   9219: 
                   9220: =item $uname, students name
                   9221: 
                   9222: =item $uid, students user id
                   9223: 
                   9224: =item $first, students first name
                   9225: 
                   9226: =item $middle
                   9227: 
                   9228: =item $last
                   9229: 
                   9230: =item $gene
                   9231: 
                   9232: =item $usec
                   9233: 
                   9234: =item $end
                   9235: 
                   9236: =item $start
                   9237: 
1.957     raeburn  9238: =item $type
                   9239: 
                   9240: =item $locktype
                   9241: 
                   9242: =item $cid
                   9243: 
                   9244: =item $selfenroll
                   9245: 
                   9246: =item $context
                   9247: 
1.297     matthew  9248: =back
                   9249: 
1.191     harris41 9250: 
                   9251: =item *
                   9252: 
1.243     albertel 9253: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9254: custom role; give a custom role to a user for the level given by URL.  Specify
                   9255: name and domain of role author, and role name
1.191     harris41 9256: 
                   9257: =item *
                   9258: 
1.243     albertel 9259: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9260: 
                   9261: =item *
                   9262: 
1.243     albertel 9263: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9264: 
                   9265: =back
                   9266: 
                   9267: =head2 Course Infomation
                   9268: 
                   9269: =over 4
1.191     harris41 9270: 
                   9271: =item *
                   9272: 
1.631     albertel 9273: coursedescription($courseid) : returns a hash of information about the
                   9274: specified course id, including all environment settings for the
                   9275: course, the description of the course will be in the hash under the
                   9276: key 'description'
1.191     harris41 9277: 
                   9278: =item *
                   9279: 
1.624     albertel 9280: resdata($name,$domain,$type,@which) : request for current parameter
                   9281: setting for a specific $type, where $type is either 'course' or 'user',
                   9282: @what should be a list of parameters to ask about. This routine caches
                   9283: answers for 5 minutes.
1.243     albertel 9284: 
1.877     foxr     9285: =item *
                   9286: 
                   9287: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9288: data base, returning a hash that is keyed by the resource name and has
                   9289: values that are the resource value.  I believe that the timestamps and
                   9290: versions are also returned.
                   9291: 
                   9292: 
1.243     albertel 9293: =back
                   9294: 
                   9295: =head2 Course Modification
                   9296: 
                   9297: =over 4
1.191     harris41 9298: 
                   9299: =item *
                   9300: 
1.243     albertel 9301: writecoursepref($courseid,%prefs) : write preferences (environment
                   9302: database) for a course
1.191     harris41 9303: 
                   9304: =item *
                   9305: 
1.243     albertel 9306: createcourse($udom,$description,$url) : make/modify course
                   9307: 
                   9308: =back
                   9309: 
                   9310: =head2 Resource Subroutines
                   9311: 
                   9312: =over 4
1.191     harris41 9313: 
                   9314: =item *
                   9315: 
1.243     albertel 9316: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9317: 
                   9318: =item *
                   9319: 
1.243     albertel 9320: repcopy($filename) : subscribes to the requested file, and attempts to
                   9321: replicate from the owning library server, Might return
1.607     raeburn  9322: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9323: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9324: resource. Expects the local filesystem pathname
                   9325: (/home/httpd/html/res/....)
                   9326: 
                   9327: =back
                   9328: 
                   9329: =head2 Resource Information
                   9330: 
                   9331: =over 4
1.191     harris41 9332: 
                   9333: =item *
                   9334: 
1.243     albertel 9335: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9336: a vairety of different possible values, $varname should be a request
                   9337: string, and the other parameters can be used to specify who and what
                   9338: one is asking about.
                   9339: 
                   9340: Possible values for $varname are environment.lastname (or other item
                   9341: from the envirnment hash), user.name (or someother aspect about the
                   9342: user), resource.0.maxtries (or some other part and parameter of a
                   9343: resource)
1.204     albertel 9344: 
                   9345: =item *
                   9346: 
1.243     albertel 9347: directcondval($number) : get current value of a condition; reads from a state
                   9348: string
1.204     albertel 9349: 
                   9350: =item *
                   9351: 
1.243     albertel 9352: condval($condidx) : value of condition index based on state
1.204     albertel 9353: 
                   9354: =item *
                   9355: 
1.243     albertel 9356: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9357: resource's metadata, $what should be either a specific key, or either
                   9358: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9359: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9360: 
                   9361: this function automatically caches all requests
1.191     harris41 9362: 
                   9363: =item *
                   9364: 
1.243     albertel 9365: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9366: network of library servers; returns file handle of where SQL and regex results
                   9367: will be stored for query
1.191     harris41 9368: 
                   9369: =item *
                   9370: 
1.243     albertel 9371: symbread($filename) : return symbolic list entry (filename argument optional);
                   9372: returns the data handle
1.191     harris41 9373: 
                   9374: =item *
                   9375: 
1.243     albertel 9376: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9377: a possible symb for the URL in $thisfn, and if is an encryypted
                   9378: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9379: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9380: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9381: 
1.191     harris41 9382: 
                   9383: =item *
                   9384: 
1.243     albertel 9385: symbclean($symb) : removes versions numbers from a symb, returns the
                   9386: cleaned symb
1.191     harris41 9387: 
                   9388: =item *
                   9389: 
1.243     albertel 9390: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9391: course map, user must be in a course for it to work.
1.191     harris41 9392: 
                   9393: =item *
                   9394: 
1.243     albertel 9395: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9396: 
                   9397: =item *
                   9398: 
1.243     albertel 9399: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9400: a random seed, all arguments are optional, if they aren't sent it uses the
                   9401: environment to derive them. Note: if symb isn't sent and it can't get one
                   9402: from &symbread it will use the current time as its return value
1.191     harris41 9403: 
                   9404: =item *
                   9405: 
1.243     albertel 9406: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9407: unfakeable, receipt
1.191     harris41 9408: 
                   9409: =item *
                   9410: 
1.620     albertel 9411: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9412: 
                   9413: =item *
                   9414: 
1.243     albertel 9415: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9416: 
                   9417: =item *
                   9418: 
1.243     albertel 9419: 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 9420: 
                   9421: =item *
                   9422: 
1.243     albertel 9423: 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 9424: 
                   9425: =item *
                   9426: 
1.243     albertel 9427: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9428: 
                   9429: =item *
                   9430: 
1.243     albertel 9431: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9432: forcing spreadsheet to reevaluate the resource scores next time.
                   9433: 
                   9434: =back
                   9435: 
                   9436: =head2 Storing/Retreiving Data
                   9437: 
                   9438: =over 4
1.191     harris41 9439: 
                   9440: =item *
                   9441: 
1.243     albertel 9442: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9443: for this url; hashref needs to be given and should be a \%hashname; the
                   9444: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9445: be derived from the env
1.191     harris41 9446: 
                   9447: =item *
                   9448: 
1.243     albertel 9449: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9450: uses critical subroutine
1.191     harris41 9451: 
                   9452: =item *
                   9453: 
1.243     albertel 9454: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9455: all args are optional
1.191     harris41 9456: 
                   9457: =item *
                   9458: 
1.717     albertel 9459: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9460: dumps the complete (or key matching regexp) namespace into a hash
                   9461: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9462: normally &store()ed into
                   9463: 
                   9464: $range should be either an integer '100' (give me the first 100
                   9465:                                            matching records)
                   9466:               or be  two integers sperated by a - with no spaces
                   9467:                  '30-50' (give me the 30th through the 50th matching
                   9468:                           records)
                   9469: 
                   9470: 
                   9471: =item *
                   9472: 
                   9473: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9474: replaces a &store() version of data with a replacement set of data
                   9475: for a particular resource in a namespace passed in the $storehash hash 
                   9476: reference
                   9477: 
                   9478: =item *
                   9479: 
1.243     albertel 9480: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9481: works very similar to store/cstore, but all data is stored in a
                   9482: temporary location and can be reset using tmpreset, $storehash should
                   9483: be a hash reference, returns nothing on success
1.191     harris41 9484: 
                   9485: =item *
                   9486: 
1.243     albertel 9487: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9488: similar to restore, but all data is stored in a temporary location and
                   9489: can be reset using tmpreset. Returns a hash of values on success,
                   9490: error string otherwise.
1.191     harris41 9491: 
                   9492: =item *
                   9493: 
1.243     albertel 9494: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9495: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9496: 
                   9497: =item *
                   9498: 
1.243     albertel 9499: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9500: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9501: 
                   9502: =item *
                   9503: 
1.243     albertel 9504: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9505: namesp ($udom and $uname are optional)
1.191     harris41 9506: 
                   9507: =item *
                   9508: 
1.702     albertel 9509: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9510: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9511: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9512: 
1.702     albertel 9513: $range should be either an integer '100' (give me the first 100
                   9514:                                            matching records)
                   9515:               or be  two integers sperated by a - with no spaces
                   9516:                  '30-50' (give me the 30th through the 50th matching
                   9517:                           records)
1.449     matthew  9518: =item *
                   9519: 
                   9520: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9521: $store can be a scalar, an array reference, or if the amount to be 
                   9522: incremented is > 1, a hash reference.
                   9523: 
                   9524: ($udom and $uname are optional)
1.191     harris41 9525: 
                   9526: =item *
                   9527: 
1.243     albertel 9528: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9529: ($udom and $uname are optional)
1.191     harris41 9530: 
                   9531: =item *
                   9532: 
1.243     albertel 9533: cput($namespace,$storehash,$udom,$uname) : critical put
                   9534: ($udom and $uname are optional)
1.191     harris41 9535: 
                   9536: =item *
                   9537: 
1.748     albertel 9538: newput($namespace,$storehash,$udom,$uname) :
                   9539: 
                   9540: Attempts to store the items in the $storehash, but only if they don't
                   9541: currently exist, if this succeeds you can be certain that you have 
                   9542: successfully created a new key value pair in the $namespace db.
                   9543: 
                   9544: 
                   9545: Args:
                   9546:  $namespace: name of database to store values to
                   9547:  $storehash: hashref to store to the db
                   9548:  $udom: (optional) domain of user containing the db
                   9549:  $uname: (optional) name of user caontaining the db
                   9550: 
                   9551: Returns:
                   9552:  'ok' -> succeeded in storing all keys of $storehash
                   9553:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9554:                         least <key> already existed in the db (other
                   9555:                         requested keys may also already exist)
                   9556:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9557:  'con_lost' -> unable to contact request server
                   9558:  'refused' -> action was not allowed by remote machine
                   9559: 
                   9560: 
                   9561: =item *
                   9562: 
1.243     albertel 9563: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9564: reference filled in from namesp (encrypts the return communication)
                   9565: ($udom and $uname are optional)
1.191     harris41 9566: 
                   9567: =item *
                   9568: 
1.243     albertel 9569: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9570: critical subroutine
                   9571: 
1.806     raeburn  9572: =item *
                   9573: 
1.860     raeburn  9574: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9575: array reference filled in from namespace found in domain level on either
                   9576: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9577: 
                   9578: =item *
                   9579: 
1.860     raeburn  9580: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9581: domain level either on specified domain server ($uhome) or primary domain 
                   9582: server ($udom and $uhome are optional)
1.806     raeburn  9583: 
1.943     raeburn  9584: =item * 
                   9585: 
                   9586: get_domain_defaults($target_domain) : returns hash with defaults for
                   9587: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9588: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9589: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9590: Values are retrieved from cache (if current), or from domain's configuration.db
                   9591: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9592: or lonTabs/domain.tab. 
                   9593: 
                   9594: %domdefaults = &get_auth_defaults($target_domain);
                   9595: 
1.243     albertel 9596: =back
                   9597: 
                   9598: =head2 Network Status Functions
                   9599: 
                   9600: =over 4
1.191     harris41 9601: 
                   9602: =item *
                   9603: 
                   9604: dirlist($uri) : return directory list based on URI
                   9605: 
                   9606: =item *
                   9607: 
1.243     albertel 9608: spareserver() : find server with least workload from spare.tab
                   9609: 
                   9610: =back
                   9611: 
                   9612: =head2 Apache Request
                   9613: 
                   9614: =over 4
1.191     harris41 9615: 
                   9616: =item *
                   9617: 
1.243     albertel 9618: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9619: localhost, posts hash
                   9620: 
                   9621: =back
                   9622: 
                   9623: =head2 Data to String to Data
                   9624: 
                   9625: =over 4
1.191     harris41 9626: 
                   9627: =item *
                   9628: 
1.243     albertel 9629: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9630: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9631: 
                   9632: =item *
                   9633: 
1.243     albertel 9634: hashref2str($hashref) : convert a hashref into a string complete with
                   9635: escaping and '=' and '&' separators, supports elements that are
                   9636: arrayrefs and hashrefs
1.191     harris41 9637: 
                   9638: =item *
                   9639: 
1.243     albertel 9640: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9641: with escaping and '&' separators, supports elements that are arrayrefs
                   9642: and hashrefs
1.191     harris41 9643: 
                   9644: =item *
                   9645: 
1.243     albertel 9646: str2hash($string) : convert string to hash using unescaping and
                   9647: splitting on '=' and '&', supports elements that are arrayrefs and
                   9648: hashrefs
1.191     harris41 9649: 
                   9650: =item *
                   9651: 
1.243     albertel 9652: str2array($string) : convert string to hash using unescaping and
                   9653: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9654: 
                   9655: =back
                   9656: 
                   9657: =head2 Logging Routines
                   9658: 
                   9659: =over 4
                   9660: 
                   9661: These routines allow one to make log messages in the lonnet.log and
                   9662: lonnet.perm logfiles.
1.191     harris41 9663: 
                   9664: =item *
                   9665: 
1.243     albertel 9666: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9667: 
                   9668: =item *
                   9669: 
1.243     albertel 9670: logthis() : append message to the normal lonnet.log file, it gets
                   9671: preiodically rolled over and deleted.
1.191     harris41 9672: 
                   9673: =item *
                   9674: 
1.243     albertel 9675: logperm() : append a permanent message to lonnet.perm.log, this log
                   9676: file never gets deleted by any automated portion of the system, only
                   9677: messages of critical importance should go in here.
                   9678: 
                   9679: =back
                   9680: 
                   9681: =head2 General File Helper Routines
                   9682: 
                   9683: =over 4
1.191     harris41 9684: 
                   9685: =item *
                   9686: 
1.481     raeburn  9687: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9688: (a) files in /uploaded
                   9689:   (i) If a local copy of the file exists - 
                   9690:       compares modification date of local copy with last-modified date for 
                   9691:       definitive version stored on home server for course. If local copy is 
                   9692:       stale, requests a new version from the home server and stores it. 
                   9693:       If the original has been removed from the home server, then local copy 
                   9694:       is unlinked.
                   9695:   (ii) If local copy does not exist -
                   9696:       requests the file from the home server and stores it. 
                   9697:   
                   9698:   If $caller is 'uploadrep':  
                   9699:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9700:     for request for files originally uploaded via DOCS. 
                   9701:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9702:   
                   9703:   Otherwise:
                   9704:      This indicates a call from the content generation phase of the request.
                   9705:      -  returns the entire contents of the file or -1.
                   9706:      
                   9707: (b) files in /res
                   9708:    - returns the entire contents of a file or -1; 
                   9709:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9710: 
1.712     albertel 9711: 
                   9712: =item *
                   9713: 
                   9714: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9715:                   reference
                   9716: 
                   9717: returns either a stat() list of data about the file or an empty list
                   9718: if the file doesn't exist or couldn't find out about it (connection
                   9719: problems or user unknown)
                   9720: 
1.191     harris41 9721: =item *
                   9722: 
1.243     albertel 9723: filelocation($dir,$file) : returns file system location of a file
                   9724: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9725: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9726: and a file of ../bob will become /a/bob)
1.191     harris41 9727: 
                   9728: =item *
                   9729: 
                   9730: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9731: filelocation except for hrefs
                   9732: 
                   9733: =item *
                   9734: 
                   9735: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9736: 
1.243     albertel 9737: =back
                   9738: 
1.608     albertel 9739: =head2 Usererfile file routines (/uploaded*)
                   9740: 
                   9741: =over 4
                   9742: 
                   9743: =item *
                   9744: 
                   9745: userfileupload(): main rotine for putting a file in a user or course's
                   9746:                   filespace, arguments are,
                   9747: 
1.620     albertel 9748:  formname - required - this is the name of the element in $env where the
1.608     albertel 9749:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9750:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9751:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9752:  coursedoc - if true, store the file in the course of the active role
                   9753:              of the current user
                   9754:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9755:          if undefined, it will be placed in "unknown"
                   9756: 
                   9757:  (This routine calls clean_filename() to remove any dangerous
                   9758:  characters from the filename, and then calls finuserfileupload() to
                   9759:  complete the transaction)
                   9760: 
                   9761:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9762:  and /adm/notfound.html if unsuccessful
                   9763: 
                   9764: =item *
                   9765: 
                   9766: clean_filename(): routine for cleaing a filename up for storage in
                   9767:                  userfile space, argument is:
                   9768: 
                   9769:  filename - proposed filename
                   9770: 
                   9771: returns: the new clean filename
                   9772: 
                   9773: =item *
                   9774: 
                   9775: finishuserfileupload(): routine that creaes and sends the file to
                   9776: userspace, probably shouldn't be called directly
                   9777: 
                   9778:   docuname: username or courseid of destination for the file
                   9779:   docudom: domain of user/course of destination for the file
                   9780:   formname: same as for userfileupload()
                   9781:   fname: filename (inculding subdirectories) for the file
                   9782: 
                   9783:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9784:  and /adm/notfound.html if unsuccessful
                   9785: 
                   9786: =item *
                   9787: 
                   9788: renameuserfile(): renames an existing userfile to a new name
                   9789: 
                   9790:   Args:
                   9791:    docuname: username or courseid of destination for the file
                   9792:    docudom: domain of user/course of destination for the file
                   9793:    old: current file name (including any subdirs under userfiles)
                   9794:    new: desired file name (including any subdirs under userfiles)
                   9795: 
                   9796: =item *
                   9797: 
                   9798: mkdiruserfile(): creates a directory is a userfiles dir
                   9799: 
                   9800:   Args:
                   9801:    docuname: username or courseid of destination for the file
                   9802:    docudom: domain of user/course of destination for the file
                   9803:    dir: dir to create (including any subdirs under userfiles)
                   9804: 
                   9805: =item *
                   9806: 
                   9807: removeuserfile(): removes a file that exists in userfiles
                   9808: 
                   9809:   Args:
                   9810:    docuname: username or courseid of destination for the file
                   9811:    docudom: domain of user/course of destination for the file
                   9812:    fname: filname to delete (including any subdirs under userfiles)
                   9813: 
                   9814: =item *
                   9815: 
                   9816: removeuploadedurl(): convience function for removeuserfile()
                   9817: 
                   9818:   Args:
                   9819:    url:  a full /uploaded/... url to delete
                   9820: 
1.747     albertel 9821: =item * 
                   9822: 
                   9823: get_portfile_permissions():
                   9824:   Args:
                   9825:     domain: domain of user or course contain the portfolio files
                   9826:     user: name of user or num of course contain the portfolio files
                   9827:   Returns:
                   9828:     hashref of a dump of the proper file_permissions.db
                   9829:    
                   9830: 
                   9831: =item * 
                   9832: 
                   9833: get_access_controls():
                   9834: 
                   9835: Args:
                   9836:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9837:   group: (optional) the group you want the files associated with
                   9838:   file: (optional) the file you want access info on
                   9839: 
                   9840: Returns:
1.749     raeburn  9841:     a hash (keys are file names) of hashes containing
                   9842:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9843:         values are XML containing access control settings (see below) 
1.747     albertel 9844: 
                   9845: Internal notes:
                   9846: 
1.749     raeburn  9847:  access controls are stored in file_permissions.db as key=value pairs.
                   9848:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9849:         where scope -> public,guest,course,group,domains or users.
                   9850:               end -> UNIX time for end of access (0 -> no end date)
                   9851:               start -> UNIX time for start of access
                   9852: 
                   9853:     value -> XML description of access control
                   9854:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9855:             <start></start>
                   9856:             <end></end>
                   9857: 
                   9858:             <password></password>  for scope type = guest
                   9859: 
                   9860:             <domain></domain>     for scope type = course or group
                   9861:             <number></number>
                   9862:             <roles id="">
                   9863:              <role></role>
                   9864:              <access></access>
                   9865:              <section></section>
                   9866:              <group></group>
                   9867:             </roles>
                   9868: 
                   9869:             <dom></dom>         for scope type = domains
                   9870: 
                   9871:             <users>             for scope type = users
                   9872:              <user>
                   9873:               <uname></uname>
                   9874:               <udom></udom>
                   9875:              </user>
                   9876:             </users>
                   9877:            </scope> 
                   9878:               
                   9879:  Access data is also aggregated for each file in an additional key=value pair:
                   9880:  key -> path to file/file_name\0accesscontrol 
                   9881:  value -> reference to hash
                   9882:           hash contains key = value pairs
                   9883:           where key = uniqueID:scope_end_start
                   9884:                 value = UNIX time record was last updated
                   9885: 
                   9886:           Used to improve speed of look-ups of access controls for each file.  
                   9887:  
                   9888:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9889: 
                   9890: modify_access_controls():
                   9891: 
                   9892: Modifies access controls for a portfolio file
                   9893: Args
                   9894: 1. file name
                   9895: 2. reference to hash of required changes,
                   9896: 3. domain
                   9897: 4. username
                   9898:   where domain,username are the domain of the portfolio owner 
                   9899:   (either a user or a course) 
                   9900: 
                   9901: Returns:
                   9902: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9903: 2. result of deletions ('ok' or 'error', with error message).
                   9904: 3. reference to hash of any new or updated access controls.
                   9905: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9906:    key = integer (inbound ID)
                   9907:    value = uniqueID  
1.747     albertel 9908: 
1.608     albertel 9909: =back
                   9910: 
1.243     albertel 9911: =head2 HTTP Helper Routines
                   9912: 
                   9913: =over 4
                   9914: 
1.191     harris41 9915: =item *
                   9916: 
                   9917: escape() : unpack non-word characters into CGI-compatible hex codes
                   9918: 
                   9919: =item *
                   9920: 
                   9921: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9922: 
1.243     albertel 9923: =back
                   9924: 
                   9925: =head1 PRIVATE SUBROUTINES
                   9926: 
                   9927: =head2 Underlying communication routines (Shouldn't call)
                   9928: 
                   9929: =over 4
                   9930: 
                   9931: =item *
                   9932: 
                   9933: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9934: 
                   9935: =item *
                   9936: 
                   9937: reply() : uses subreply to send a message to remote machine, logs all failures
                   9938: 
                   9939: =item *
                   9940: 
                   9941: critical() : passes a critical message to another server; if cannot
                   9942: get through then place message in connection buffer directory and
                   9943: returns con_delayed, if incapable of saving message, returns
                   9944: con_failed
                   9945: 
                   9946: =item *
                   9947: 
                   9948: reconlonc() : tries to reconnect lonc client processes.
                   9949: 
                   9950: =back
                   9951: 
                   9952: =head2 Resource Access Logging
                   9953: 
                   9954: =over 4
                   9955: 
                   9956: =item *
                   9957: 
                   9958: flushcourselogs() : flush (save) buffer logs and access logs
                   9959: 
                   9960: =item *
                   9961: 
                   9962: courselog($what) : save message for course in hash
                   9963: 
                   9964: =item *
                   9965: 
                   9966: courseacclog($what) : save message for course using &courselog().  Perform
                   9967: special processing for specific resource types (problems, exams, quizzes, etc).
                   9968: 
1.191     harris41 9969: =item *
                   9970: 
                   9971: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9972: as a PerlChildExitHandler
1.243     albertel 9973: 
                   9974: =back
                   9975: 
                   9976: =head2 Other
                   9977: 
                   9978: =over 4
                   9979: 
                   9980: =item *
                   9981: 
                   9982: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9983: 
                   9984: =back
                   9985: 
                   9986: =cut
1.877     foxr     9987: 

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