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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.969   ! raeburn     4: # $Id: lonnet.pm,v 1.968 2008/09/12 21:25:54 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    37:             $_64bit %env %protocol);
1.871     albertel   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.968     raeburn   646:         my $protocol = 'http';
                    647:         if ($protocol{$spare_server} eq 'https') {
                    648:             $protocol = $protocol{$spare_server};
                    649:         }
                    650: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  651:     }
                    652:     return $spare_server;
                    653: }
                    654: 
                    655: sub compare_server_load {
                    656:     my ($try_server, $spare_server, $lowest_load) = @_;
                    657: 
                    658:     my $loadans     = &reply('load',    $try_server);
                    659:     my $userloadans = &reply('userload',$try_server);
                    660: 
                    661:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    662: 	next; #didn't get a number from the server
                    663:     }
                    664: 
                    665:     my $load;
                    666:     if ($loadans =~ /\d/) {
                    667: 	if ($userloadans =~ /\d/) {
                    668: 	    #both are numbers, pick the bigger one
                    669: 	    $load = ($loadans > $userloadans) ? $loadans 
                    670: 		                              : $userloadans;
1.411     albertel  671: 	} else {
1.784     albertel  672: 	    $load = $loadans;
1.411     albertel  673: 	}
1.784     albertel  674:     } else {
                    675: 	$load = $userloadans;
                    676:     }
                    677: 
                    678:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    679: 	$spare_server = $try_server;
                    680: 	$lowest_load  = $load;
1.370     albertel  681:     }
1.784     albertel  682:     return ($spare_server,$lowest_load);
1.202     matthew   683: }
1.914     albertel  684: 
                    685: # --------------------------- ask offload servers if user already has a session
                    686: sub find_existing_session {
                    687:     my ($udom,$uname) = @_;
                    688:     foreach my $try_server (@{ $spareid{'primary'} },
                    689: 			    @{ $spareid{'default'} }) {
                    690: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    691:     }
                    692:     return;
                    693: }
                    694: 
                    695: # -------------------------------- ask if server already has a session for user
                    696: sub has_user_session {
                    697:     my ($lonid,$udom,$uname) = @_;
                    698:     my $result = &reply(join(':','userhassession',
                    699: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    700:     return 1 if ($result eq 'ok');
                    701: 
                    702:     return 0;
                    703: }
                    704: 
1.202     matthew   705: # --------------------------------------------- Try to change a user's password
                    706: 
                    707: sub changepass {
1.799     raeburn   708:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   709:     $currentpass = &escape($currentpass);
                    710:     $newpass     = &escape($newpass);
1.799     raeburn   711:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   712: 		       $server);
                    713:     if (! $answer) {
                    714: 	&logthis("No reply on password change request to $server ".
                    715: 		 "by $uname in domain $udom.");
                    716:     } elsif ($answer =~ "^ok") {
                    717:         &logthis("$uname in $udom successfully changed their password ".
                    718: 		 "on $server.");
                    719:     } elsif ($answer =~ "^pwchange_failure") {
                    720: 	&logthis("$uname in $udom was unable to change their password ".
                    721: 		 "on $server.  The action was blocked by either lcpasswd ".
                    722: 		 "or pwchange");
                    723:     } elsif ($answer =~ "^non_authorized") {
                    724:         &logthis("$uname in $udom did not get their password correct when ".
                    725: 		 "attempting to change it on $server.");
                    726:     } elsif ($answer =~ "^auth_mode_error") {
                    727:         &logthis("$uname in $udom attempted to change their password despite ".
                    728: 		 "not being locally or internally authenticated on $server.");
                    729:     } elsif ($answer =~ "^unknown_user") {
                    730:         &logthis("$uname in $udom attempted to change their password ".
                    731: 		 "on $server but were unable to because $server is not ".
                    732: 		 "their home server.");
                    733:     } elsif ($answer =~ "^refused") {
                    734: 	&logthis("$server refused to change $uname in $udom password because ".
                    735: 		 "it was sent an unencrypted request to change the password.");
                    736:     }
                    737:     return $answer;
1.1       albertel  738: }
                    739: 
1.169     harris41  740: # ----------------------- Try to determine user's current authentication scheme
                    741: 
                    742: sub queryauthenticate {
                    743:     my ($uname,$udom)=@_;
1.456     albertel  744:     my $uhome=&homeserver($uname,$udom);
                    745:     if (!$uhome) {
                    746: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    747: 	return 'no_host';
                    748:     }
                    749:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    750:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    751: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  752:     }
1.456     albertel  753:     return $answer;
1.169     harris41  754: }
                    755: 
1.1       albertel  756: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       757: 
1.1       albertel  758: sub authenticate {
1.952     raeburn   759:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  760:     $upass=&escape($upass);
                    761:     $uname= &LONCAPA::clean_username($uname);
1.836     www       762:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   763:     my $newhome;
1.836     www       764:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    765: # Maybe the machine was offline and only re-appeared again recently?
                    766:         &reconlonc();
                    767: # One more
1.952     raeburn   768: 	$uhome=&homeserver($uname,$udom,1);
                    769:         if (($uhome eq 'no_host') && $checkdefauth) {
                    770:             if (defined(&domain($udom,'primary'))) {
                    771:                 $newhome=&domain($udom,'primary');
                    772:             }
                    773:             if ($newhome ne '') {
                    774:                 $uhome = $newhome;
                    775:             }
                    776:         }
1.836     www       777: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    778: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   779: 	    return 'no_host';
                    780:         }
1.1       albertel  781:     }
1.952     raeburn   782:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  783:     if ($answer eq 'authorized') {
1.952     raeburn   784:         if ($newhome) {
                    785:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    786:             return 'no_account_on_host'; 
                    787:         } else {
                    788:             &logthis("User $uname at $udom authorized by $uhome");
                    789:             return $uhome;
                    790:         }
1.471     albertel  791:     }
                    792:     if ($answer eq 'non_authorized') {
                    793: 	&logthis("User $uname at $udom rejected by $uhome");
                    794: 	return 'no_host'; 
1.9       www       795:     }
1.471     albertel  796:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  797:     return 'no_host';
                    798: }
                    799: 
                    800: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       801: 
1.599     albertel  802: my %homecache;
1.1       albertel  803: sub homeserver {
1.230     stredwic  804:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  805:     my $index="$uname:$udom";
1.426     albertel  806: 
1.599     albertel  807:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  808: 
                    809:     my %servers = &get_servers($udom,'library');
                    810:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  811:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  812: 		 exists($badServerCache{$tryserver}));
1.841     albertel  813: 
                    814: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    815: 	if ($answer eq 'found') {
                    816: 	    delete($badServerCache{$tryserver}); 
                    817: 	    return $homecache{$index}=$tryserver;
                    818: 	} elsif ($answer eq 'no_host') {
                    819: 	    $badServerCache{$tryserver}=1;
                    820: 	}
1.1       albertel  821:     }    
                    822:     return 'no_host';
1.70      www       823: }
                    824: 
                    825: # ------------------------------------- Find the usernames behind a list of IDs
                    826: 
                    827: sub idget {
                    828:     my ($udom,@ids)=@_;
                    829:     my %returnhash=();
                    830:     
1.841     albertel  831:     my %servers = &get_servers($udom,'library');
                    832:     foreach my $tryserver (keys(%servers)) {
                    833: 	my $idlist=join('&',@ids);
                    834: 	$idlist=~tr/A-Z/a-z/; 
                    835: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    836: 	my @answer=();
                    837: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    838: 	    @answer=split(/\&/,$reply);
                    839: 	}                    ;
                    840: 	my $i;
                    841: 	for ($i=0;$i<=$#ids;$i++) {
                    842: 	    if ($answer[$i]) {
                    843: 		$returnhash{$ids[$i]}=$answer[$i];
                    844: 	    } 
                    845: 	}
                    846:     } 
1.70      www       847:     return %returnhash;
                    848: }
                    849: 
                    850: # ------------------------------------- Find the IDs behind a list of usernames
                    851: 
                    852: sub idrget {
                    853:     my ($udom,@unames)=@_;
                    854:     my %returnhash=();
1.800     albertel  855:     foreach my $uname (@unames) {
                    856:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  857:     }
1.70      www       858:     return %returnhash;
                    859: }
                    860: 
                    861: # ------------------------------- Store away a list of names and associated IDs
                    862: 
                    863: sub idput {
                    864:     my ($udom,%ids)=@_;
                    865:     my %servers=();
1.800     albertel  866:     foreach my $uname (keys(%ids)) {
                    867: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    868:         my $uhom=&homeserver($uname,$udom);
1.70      www       869:         if ($uhom ne 'no_host') {
1.800     albertel  870:             my $id=&escape($ids{$uname});
1.70      www       871:             $id=~tr/A-Z/a-z/;
1.800     albertel  872:             my $esc_unam=&escape($uname);
1.70      www       873: 	    if ($servers{$uhom}) {
1.800     albertel  874: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       875:             } else {
1.800     albertel  876:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       877:             }
                    878:         }
1.191     harris41  879:     }
1.800     albertel  880:     foreach my $server (keys(%servers)) {
                    881:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  882:     }
1.344     www       883: }
                    884: 
1.806     raeburn   885: # ------------------------------------------- get items from domain db files   
                    886: 
                    887: sub get_dom {
1.860     raeburn   888:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   889:     my $items='';
                    890:     foreach my $item (@$storearr) {
                    891:         $items.=&escape($item).'&';
                    892:     }
                    893:     $items=~s/\&$//;
1.860     raeburn   894:     if (!$udom) {
                    895:         $udom=$env{'user.domain'};
                    896:         if (defined(&domain($udom,'primary'))) {
                    897:             $uhome=&domain($udom,'primary');
                    898:         } else {
1.874     albertel  899:             undef($uhome);
1.860     raeburn   900:         }
                    901:     } else {
                    902:         if (!$uhome) {
                    903:             if (defined(&domain($udom,'primary'))) {
                    904:                 $uhome=&domain($udom,'primary');
                    905:             }
                    906:         }
                    907:     }
                    908:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   909:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   910:         my %returnhash;
1.875     albertel  911:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   912:             return %returnhash;
                    913:         }
1.806     raeburn   914:         my @pairs=split(/\&/,$rep);
                    915:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    916:             return @pairs;
                    917:         }
                    918:         my $i=0;
                    919:         foreach my $item (@$storearr) {
                    920:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    921:             $i++;
                    922:         }
                    923:         return %returnhash;
                    924:     } else {
1.880     banghart  925:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   926:     }
                    927: }
                    928: 
                    929: # -------------------------------------------- put items in domain db files 
                    930: 
                    931: sub put_dom {
1.860     raeburn   932:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    933:     if (!$udom) {
                    934:         $udom=$env{'user.domain'};
                    935:         if (defined(&domain($udom,'primary'))) {
                    936:             $uhome=&domain($udom,'primary');
                    937:         } else {
1.874     albertel  938:             undef($uhome);
1.860     raeburn   939:         }
                    940:     } else {
                    941:         if (!$uhome) {
                    942:             if (defined(&domain($udom,'primary'))) {
                    943:                 $uhome=&domain($udom,'primary');
                    944:             }
                    945:         }
                    946:     } 
                    947:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   948:         my $items='';
                    949:         foreach my $item (keys(%$storehash)) {
                    950:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    951:         }
                    952:         $items=~s/\&$//;
                    953:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    954:     } else {
1.860     raeburn   955:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   956:     }
                    957: }
                    958: 
1.837     raeburn   959: sub retrieve_inst_usertypes {
                    960:     my ($udom) = @_;
                    961:     my (%returnhash,@order);
1.846     albertel  962:     if (defined(&domain($udom,'primary'))) {
                    963:         my $uhome=&domain($udom,'primary');
1.837     raeburn   964:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn   965:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                    966:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                    967:             return (\%returnhash,\@order);
                    968:         }
1.837     raeburn   969:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    970:         my @pairs=split(/\&/,$hashitems);
                    971:         foreach my $item (@pairs) {
                    972:             my ($key,$value)=split(/=/,$item,2);
                    973:             $key = &unescape($key);
                    974:             next if ($key =~ /^error: 2 /);
                    975:             $returnhash{$key}=&thaw_unescape($value);
                    976:         }
                    977:         my @esc_order = split(/\&/,$orderitems);
                    978:         foreach my $item (@esc_order) {
                    979:             push(@order,&unescape($item));
                    980:         }
                    981:     } else {
                    982:         &logthis("get_dom failed - no primary domain server for $udom");
                    983:     }
                    984:     return (\%returnhash,\@order);
                    985: }
                    986: 
1.868     raeburn   987: sub is_domainimage {
                    988:     my ($url) = @_;
                    989:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    990:         if (&domain($1) ne '') {
                    991:             return '1';
                    992:         }
                    993:     }
                    994:     return;
                    995: }
                    996: 
1.899     raeburn   997: sub inst_directory_query {
                    998:     my ($srch) = @_;
                    999:     my $udom = $srch->{'srchdomain'};
                   1000:     my %results;
                   1001:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1002:     my $outcome;
1.899     raeburn  1003:     if ($homeserver ne '') {
1.904     albertel 1004: 	my $queryid=&reply("querysend:instdirsearch:".
                   1005: 			   &escape($srch->{'srchby'}).':'.
                   1006: 			   &escape($srch->{'srchterm'}).':'.
                   1007: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1008: 	my $host=&hostname($homeserver);
                   1009: 	if ($queryid !~/^\Q$host\E\_/) {
                   1010: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1011: 	    return;
                   1012: 	}
                   1013: 	my $response = &get_query_reply($queryid);
                   1014: 	my $maxtries = 5;
                   1015: 	my $tries = 1;
                   1016: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1017: 	    $response = &get_query_reply($queryid);
                   1018: 	    $tries ++;
                   1019: 	}
                   1020: 
                   1021:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1022:             if ($response eq 'unavailable') {
                   1023:                 $outcome = $response;
                   1024:             } else {
                   1025:                 $outcome = 'ok';
                   1026:                 my @matches = split(/\n/,$response);
                   1027:                 foreach my $match (@matches) {
                   1028:                     my ($key,$value) = split(/=/,$match);
                   1029:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1030:                 }
1.899     raeburn  1031:             }
                   1032:         }
                   1033:     }
1.909     raeburn  1034:     return ($outcome,%results);
1.899     raeburn  1035: }
                   1036: 
                   1037: sub usersearch {
                   1038:     my ($srch) = @_;
                   1039:     my $dom = $srch->{'srchdomain'};
                   1040:     my %results;
                   1041:     my %libserv = &all_library();
                   1042:     my $query = 'usersearch';
                   1043:     foreach my $tryserver (keys(%libserv)) {
                   1044:         if (&host_domain($tryserver) eq $dom) {
                   1045:             my $host=&hostname($tryserver);
                   1046:             my $queryid=
1.911     raeburn  1047:                 &reply("querysend:".&escape($query).':'.
                   1048:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1049:                        &escape($srch->{'srchtype'}).':'.
                   1050:                        &escape($srch->{'srchterm'}),$tryserver);
                   1051:             if ($queryid !~/^\Q$host\E\_/) {
                   1052:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1053:                 next;
1.899     raeburn  1054:             }
                   1055:             my $reply = &get_query_reply($queryid);
                   1056:             my $maxtries = 1;
                   1057:             my $tries = 1;
                   1058:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1059:                 $reply = &get_query_reply($queryid);
                   1060:                 $tries ++;
                   1061:             }
                   1062:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1063:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1064:             } else {
1.911     raeburn  1065:                 my @matches;
                   1066:                 if ($reply =~ /\n/) {
                   1067:                     @matches = split(/\n/,$reply);
                   1068:                 } else {
                   1069:                     @matches = split(/\&/,$reply);
                   1070:                 }
1.899     raeburn  1071:                 foreach my $match (@matches) {
                   1072:                     my ($uname,$udom,%userhash);
1.911     raeburn  1073:                     foreach my $entry (split(/:/,$match)) {
                   1074:                         my ($key,$value) =
                   1075:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1076:                         $userhash{$key} = $value;
                   1077:                         if ($key eq 'username') {
                   1078:                             $uname = $value;
                   1079:                         } elsif ($key eq 'domain') {
                   1080:                             $udom = $value;
1.911     raeburn  1081:                         }
1.899     raeburn  1082:                     }
                   1083:                     $results{$uname.':'.$udom} = \%userhash;
                   1084:                 }
                   1085:             }
                   1086:         }
                   1087:     }
                   1088:     return %results;
                   1089: }
                   1090: 
1.912     raeburn  1091: sub get_instuser {
                   1092:     my ($udom,$uname,$id) = @_;
                   1093:     my $homeserver = &domain($udom,'primary');
                   1094:     my ($outcome,%results);
                   1095:     if ($homeserver ne '') {
                   1096:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1097:                            &escape($id).':'.&escape($udom),$homeserver);
                   1098:         my $host=&hostname($homeserver);
                   1099:         if ($queryid !~/^\Q$host\E\_/) {
                   1100:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1101:             return;
                   1102:         }
                   1103:         my $response = &get_query_reply($queryid);
                   1104:         my $maxtries = 5;
                   1105:         my $tries = 1;
                   1106:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1107:             $response = &get_query_reply($queryid);
                   1108:             $tries ++;
                   1109:         }
                   1110:         if (!&error($response) && $response ne 'refused') {
                   1111:             if ($response eq 'unavailable') {
                   1112:                 $outcome = $response;
                   1113:             } else {
                   1114:                 $outcome = 'ok';
                   1115:                 my @matches = split(/\n/,$response);
                   1116:                 foreach my $match (@matches) {
                   1117:                     my ($key,$value) = split(/=/,$match);
                   1118:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1119:                 }
                   1120:             }
                   1121:         }
                   1122:     }
                   1123:     my %userinfo;
                   1124:     if (ref($results{$uname}) eq 'HASH') {
                   1125:         %userinfo = %{$results{$uname}};
                   1126:     } 
                   1127:     return ($outcome,%userinfo);
                   1128: }
                   1129: 
                   1130: sub inst_rulecheck {
1.923     raeburn  1131:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1132:     my %returnhash;
                   1133:     if ($udom ne '') {
                   1134:         if (ref($rules) eq 'ARRAY') {
                   1135:             @{$rules} = map {&escape($_);} (@{$rules});
                   1136:             my $rulestr = join(':',@{$rules});
                   1137:             my $homeserver=&domain($udom,'primary');
                   1138:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1139:                 my $response;
                   1140:                 if ($item eq 'username') {                
                   1141:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1142:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1143:                                               $homeserver));
1.923     raeburn  1144:                 } elsif ($item eq 'id') {
                   1145:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1146:                                               ':'.&escape($id).':'.$rulestr,
                   1147:                                               $homeserver));
1.945     raeburn  1148:                 } elsif ($item eq 'selfcreate') {
                   1149:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1150:                                                &escape($udom).':'.&escape($uname).
                   1151:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1152:                 }
1.912     raeburn  1153:                 if ($response ne 'refused') {
                   1154:                     my @pairs=split(/\&/,$response);
                   1155:                     foreach my $item (@pairs) {
                   1156:                         my ($key,$value)=split(/=/,$item,2);
                   1157:                         $key = &unescape($key);
                   1158:                         next if ($key =~ /^error: 2 /);
                   1159:                         $returnhash{$key}=&thaw_unescape($value);
                   1160:                     }
                   1161:                 }
                   1162:             }
                   1163:         }
                   1164:     }
                   1165:     return %returnhash;
                   1166: }
                   1167: 
                   1168: sub inst_userrules {
1.923     raeburn  1169:     my ($udom,$check) = @_;
1.912     raeburn  1170:     my (%ruleshash,@ruleorder);
                   1171:     if ($udom ne '') {
                   1172:         my $homeserver=&domain($udom,'primary');
                   1173:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1174:             my $response;
                   1175:             if ($check eq 'id') {
                   1176:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1177:                                  $homeserver);
1.943     raeburn  1178:             } elsif ($check eq 'email') {
                   1179:                 $response=&reply('instemailrules:'.&escape($udom),
                   1180:                                  $homeserver);
1.923     raeburn  1181:             } else {
                   1182:                 $response=&reply('instuserrules:'.&escape($udom),
                   1183:                                  $homeserver);
                   1184:             }
1.912     raeburn  1185:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1186:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1187:                 ($response ne 'no_such_host')) {
                   1188:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1189:                 my @pairs=split(/\&/,$hashitems);
                   1190:                 foreach my $item (@pairs) {
                   1191:                     my ($key,$value)=split(/=/,$item,2);
                   1192:                     $key = &unescape($key);
                   1193:                     next if ($key =~ /^error: 2 /);
                   1194:                     $ruleshash{$key}=&thaw_unescape($value);
                   1195:                 }
                   1196:                 my @esc_order = split(/\&/,$orderitems);
                   1197:                 foreach my $item (@esc_order) {
                   1198:                     push(@ruleorder,&unescape($item));
                   1199:                 }
                   1200:             }
                   1201:         }
                   1202:     }
                   1203:     return (\%ruleshash,\@ruleorder);
                   1204: }
                   1205: 
1.943     raeburn  1206: # ------------------------- Get Authentication and Language Defaults for Domain
                   1207: 
                   1208: sub get_domain_defaults {
                   1209:     my ($domain) = @_;
                   1210:     my $cachetime = 60*60*24;
                   1211:     my ($defauthtype,$defautharg,$deflang);
                   1212:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1213:     if (defined($cached)) {
                   1214:         if (ref($result) eq 'HASH') {
                   1215:             return %{$result};
                   1216:         }
                   1217:     }
                   1218:     my %domdefaults;
                   1219:     my %domconfig =
                   1220:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1221:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1222:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1223:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1224:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1225:     } else {
                   1226:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1227:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1228:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1229:     }
                   1230:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1231:                                   $cachetime);
                   1232:     return %domdefaults;
                   1233: }
                   1234: 
1.344     www      1235: # --------------------------------------------------- Assign a key to a student
                   1236: 
                   1237: sub assign_access_key {
1.364     www      1238: #
                   1239: # a valid key looks like uname:udom#comments
                   1240: # comments are being appended
                   1241: #
1.498     www      1242:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1243:     $kdom=
1.620     albertel 1244:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1245:     $knum=
1.620     albertel 1246:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1247:     $cdom=
1.620     albertel 1248:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1249:     $cnum=
1.620     albertel 1250:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1251:     $udom=$env{'user.name'} unless (defined($udom));
                   1252:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1253:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1254:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1255:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1256:                                                   # assigned to this person
                   1257:                                                   # - this should not happen,
1.345     www      1258:                                                   # unless something went wrong
                   1259:                                                   # the first time around
                   1260: # ready to assign
1.364     www      1261:         $logentry=$1.'; '.$logentry;
1.496     www      1262:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1263:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1264: # key now belongs to user
1.346     www      1265: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1266:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1267:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1268:                 return 'ok';
                   1269:             } else {
                   1270:                 return 
                   1271:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1272: 	    }
                   1273:         } else {
                   1274:             return 'error: Could not assign key, try again later.';
                   1275:         }
1.364     www      1276:     } elsif (!$existing{$ckey}) {
1.345     www      1277: # the key does not exist
                   1278: 	return 'error: The key does not exist';
                   1279:     } else {
                   1280: # the key is somebody else's
                   1281: 	return 'error: The key is already in use';
                   1282:     }
1.344     www      1283: }
                   1284: 
1.364     www      1285: # ------------------------------------------ put an additional comment on a key
                   1286: 
                   1287: sub comment_access_key {
                   1288: #
                   1289: # a valid key looks like uname:udom#comments
                   1290: # comments are being appended
                   1291: #
                   1292:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1293:     $cdom=
1.620     albertel 1294:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1295:     $cnum=
1.620     albertel 1296:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1297:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1298:     if ($existing{$ckey}) {
                   1299:         $existing{$ckey}.='; '.$logentry;
                   1300: # ready to assign
1.367     www      1301:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1302:                                                  $cdom,$cnum) eq 'ok') {
                   1303: 	    return 'ok';
                   1304:         } else {
                   1305: 	    return 'error: Count not store comment.';
                   1306:         }
                   1307:     } else {
                   1308: # the key does not exist
                   1309: 	return 'error: The key does not exist';
                   1310:     }
                   1311: }
                   1312: 
1.344     www      1313: # ------------------------------------------------------ Generate a set of keys
                   1314: 
                   1315: sub generate_access_keys {
1.364     www      1316:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1317:     $cdom=
1.620     albertel 1318:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1319:     $cnum=
1.620     albertel 1320:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1321:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1322:     unless (($cdom) && ($cnum)) { return 0; }
                   1323:     if ($number>10000) { return 0; }
                   1324:     sleep(2); # make sure don't get same seed twice
                   1325:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1326:     my $total=0;
                   1327:     for (my $i=1;$i<=$number;$i++) {
                   1328:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1329:                   sprintf("%lx",int(100000*rand)).'-'.
                   1330:                   sprintf("%lx",int(100000*rand));
                   1331:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1332:        $newkey=~s/0/h/g; # and also 0 and O
                   1333:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1334:        if ($existing{$newkey}) {
                   1335:            $i--;
                   1336:        } else {
1.364     www      1337: 	  if (&put('accesskeys',
                   1338:               { $newkey => '# generated '.localtime().
1.620     albertel 1339:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1340:                            '; '.$logentry },
                   1341: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1342:               $total++;
                   1343: 	  }
                   1344:        }
                   1345:     }
1.620     albertel 1346:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1347:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1348:     return $total;
                   1349: }
                   1350: 
                   1351: # ------------------------------------------------------- Validate an accesskey
                   1352: 
                   1353: sub validate_access_key {
                   1354:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1355:     $cdom=
1.620     albertel 1356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1357:     $cnum=
1.620     albertel 1358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1359:     $udom=$env{'user.domain'} unless (defined($udom));
                   1360:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1361:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1362:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1363: }
                   1364: 
                   1365: # ------------------------------------- Find the section of student in a course
1.652     albertel 1366: sub devalidate_getsection_cache {
                   1367:     my ($udom,$unam,$courseid)=@_;
                   1368:     my $hashid="$udom:$unam:$courseid";
                   1369:     &devalidate_cache_new('getsection',$hashid);
                   1370: }
1.298     matthew  1371: 
1.815     albertel 1372: sub courseid_to_courseurl {
                   1373:     my ($courseid) = @_;
                   1374:     #already url style courseid
                   1375:     return $courseid if ($courseid =~ m{^/});
                   1376: 
                   1377:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1378: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1379: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1380: 	return "/$cdom/$cnum";
                   1381:     }
                   1382: 
                   1383:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1384:     if (exists($courseinfo{'num'})) {
                   1385: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1386:     }
                   1387: 
                   1388:     return undef;
                   1389: }
                   1390: 
1.298     matthew  1391: sub getsection {
                   1392:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1393:     my $cachetime=1800;
1.551     albertel 1394: 
                   1395:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1396:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1397:     if (defined($cached)) { return $result; }
                   1398: 
1.298     matthew  1399:     my %Pending; 
                   1400:     my %Expired;
                   1401:     #
                   1402:     # Each role can either have not started yet (pending), be active, 
                   1403:     #    or have expired.
                   1404:     #
                   1405:     # If there is an active role, we are done.
                   1406:     #
                   1407:     # If there is more than one role which has not started yet, 
                   1408:     #     choose the one which will start sooner
                   1409:     # If there is one role which has not started yet, return it.
                   1410:     #
                   1411:     # If there is more than one expired role, choose the one which ended last.
                   1412:     # If there is a role which has expired, return it.
                   1413:     #
1.815     albertel 1414:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1415:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1416:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1417:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1418:         my $section=$1;
                   1419:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1420:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1421:         my $now=time;
1.548     albertel 1422:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1423:             $Expired{$end}=$section;
                   1424:             next;
                   1425:         }
1.548     albertel 1426:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1427:             $Pending{$start}=$section;
                   1428:             next;
                   1429:         }
1.599     albertel 1430:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1431:     }
                   1432:     #
                   1433:     # Presumedly there will be few matching roles from the above
                   1434:     # loop and the sorting time will be negligible.
                   1435:     if (scalar(keys(%Pending))) {
                   1436:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1437:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1438:     } 
                   1439:     if (scalar(keys(%Expired))) {
                   1440:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1441:         my $time = pop(@sorted);
1.599     albertel 1442:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1443:     }
1.599     albertel 1444:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1445: }
1.70      www      1446: 
1.599     albertel 1447: sub save_cache {
                   1448:     &purge_remembered();
1.722     albertel 1449:     #&Apache::loncommon::validate_page();
1.620     albertel 1450:     undef(%env);
1.780     albertel 1451:     undef($env_loaded);
1.599     albertel 1452: }
1.452     albertel 1453: 
1.599     albertel 1454: my $to_remember=-1;
                   1455: my %remembered;
                   1456: my %accessed;
                   1457: my $kicks=0;
                   1458: my $hits=0;
1.849     albertel 1459: sub make_key {
                   1460:     my ($name,$id) = @_;
1.872     albertel 1461:     if (length($id) > 65 
                   1462: 	&& length(&escape($id)) > 200) {
                   1463: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1464:     }
1.849     albertel 1465:     return &escape($name.':'.$id);
                   1466: }
                   1467: 
1.599     albertel 1468: sub devalidate_cache_new {
                   1469:     my ($name,$id,$debug) = @_;
                   1470:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1471:     $id=&make_key($name,$id);
1.599     albertel 1472:     $memcache->delete($id);
                   1473:     delete($remembered{$id});
                   1474:     delete($accessed{$id});
                   1475: }
                   1476: 
                   1477: sub is_cached_new {
                   1478:     my ($name,$id,$debug) = @_;
1.849     albertel 1479:     $id=&make_key($name,$id);
1.599     albertel 1480:     if (exists($remembered{$id})) {
                   1481: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1482: 	$accessed{$id}=[&gettimeofday()];
                   1483: 	$hits++;
                   1484: 	return ($remembered{$id},1);
                   1485:     }
                   1486:     my $value = $memcache->get($id);
                   1487:     if (!(defined($value))) {
                   1488: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1489: 	return (undef,undef);
1.416     albertel 1490:     }
1.599     albertel 1491:     if ($value eq '__undef__') {
                   1492: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1493: 	$value=undef;
                   1494:     }
                   1495:     &make_room($id,$value,$debug);
                   1496:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1497:     return ($value,1);
                   1498: }
                   1499: 
                   1500: sub do_cache_new {
                   1501:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1502:     $id=&make_key($name,$id);
1.599     albertel 1503:     my $setvalue=$value;
                   1504:     if (!defined($setvalue)) {
                   1505: 	$setvalue='__undef__';
                   1506:     }
1.623     albertel 1507:     if (!defined($time) ) {
                   1508: 	$time=600;
                   1509:     }
1.599     albertel 1510:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1511:     my $result = $memcache->set($id,$setvalue,$time);
                   1512:     if (! $result) {
1.872     albertel 1513: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1514: 	$memcache->disconnect_all();
1.872     albertel 1515:     }
1.600     albertel 1516:     # need to make a copy of $value
1.919     albertel 1517:     &make_room($id,$value,$debug);
1.599     albertel 1518:     return $value;
                   1519: }
                   1520: 
                   1521: sub make_room {
                   1522:     my ($id,$value,$debug)=@_;
1.919     albertel 1523: 
                   1524:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1525:                                     : $value;
1.599     albertel 1526:     if ($to_remember<0) { return; }
                   1527:     $accessed{$id}=[&gettimeofday()];
                   1528:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1529:     my $to_kick;
                   1530:     my $max_time=0;
                   1531:     foreach my $other (keys(%accessed)) {
                   1532: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1533: 	    $to_kick=$other;
                   1534: 	    $max_time=&tv_interval($accessed{$other});
                   1535: 	}
                   1536:     }
                   1537:     delete($remembered{$to_kick});
                   1538:     delete($accessed{$to_kick});
                   1539:     $kicks++;
                   1540:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1541:     return;
                   1542: }
                   1543: 
1.599     albertel 1544: sub purge_remembered {
1.604     albertel 1545:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1546:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1547:     undef(%remembered);
                   1548:     undef(%accessed);
1.428     albertel 1549: }
1.70      www      1550: # ------------------------------------- Read an entry from a user's environment
                   1551: 
                   1552: sub userenvironment {
                   1553:     my ($udom,$unam,@what)=@_;
                   1554:     my %returnhash=();
                   1555:     my @answer=split(/\&/,
                   1556:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1557:                       &homeserver($unam,$udom)));
                   1558:     my $i;
                   1559:     for ($i=0;$i<=$#what;$i++) {
                   1560: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1561:     }
                   1562:     return %returnhash;
1.1       albertel 1563: }
                   1564: 
1.617     albertel 1565: # ---------------------------------------------------------- Get a studentphoto
                   1566: sub studentphoto {
                   1567:     my ($udom,$unam,$ext) = @_;
                   1568:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1569:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1570:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1571:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1572:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1573:             } else {
                   1574:                 my ($result,$perm_reqd)=
1.707     albertel 1575: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1576:                 if ($result eq 'ok') {
                   1577:                     if (!($perm_reqd eq 'yes')) {
                   1578:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1579:                     }
                   1580:                 }
                   1581:             }
                   1582:         }
                   1583:     } else {
                   1584:         my ($result,$perm_reqd) = 
1.707     albertel 1585: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1586:         if ($result eq 'ok') {
                   1587:             if (!($perm_reqd eq 'yes')) {
                   1588:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1589:             }
                   1590:         }
                   1591:     }
                   1592:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1593: }
                   1594: 
                   1595: sub retrievestudentphoto {
                   1596:     my ($udom,$unam,$ext,$type) = @_;
                   1597:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1598:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1599:     if ($ret eq 'ok') {
                   1600:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1601:         if ($type eq 'thumbnail') {
                   1602:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1603:         }
                   1604:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1605:         return $tokenurl;
                   1606:     } else {
                   1607:         if ($type eq 'thumbnail') {
                   1608:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1609:         } else { 
                   1610:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1611:         }
1.617     albertel 1612:     }
                   1613: }
                   1614: 
1.263     www      1615: # -------------------------------------------------------------------- New chat
                   1616: 
                   1617: sub chatsend {
1.724     raeburn  1618:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1619:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1620:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1621:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1622:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1623: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1624: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1625: }
                   1626: 
                   1627: # ------------------------------------------ Find current version of a resource
                   1628: 
                   1629: sub getversion {
                   1630:     my $fname=&clutter(shift);
                   1631:     unless ($fname=~/^\/res\//) { return -1; }
                   1632:     return &currentversion(&filelocation('',$fname));
                   1633: }
                   1634: 
                   1635: sub currentversion {
                   1636:     my $fname=shift;
1.599     albertel 1637:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1638:     if (defined($cached)) { return $result; }
1.292     www      1639:     my $author=$fname;
                   1640:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1641:     my ($udom,$uname)=split(/\//,$author);
                   1642:     my $home=homeserver($uname,$udom);
                   1643:     if ($home eq 'no_host') { 
                   1644:         return -1; 
                   1645:     }
                   1646:     my $answer=reply("currentversion:$fname",$home);
                   1647:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1648: 	return -1;
                   1649:     }
1.599     albertel 1650:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1651: }
                   1652: 
1.1       albertel 1653: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1654: 
1.1       albertel 1655: sub subscribe {
                   1656:     my $fname=shift;
1.761     raeburn  1657:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1658:     $fname=~s/[\n\r]//g;
1.1       albertel 1659:     my $author=$fname;
                   1660:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1661:     my ($udom,$uname)=split(/\//,$author);
                   1662:     my $home=homeserver($uname,$udom);
1.335     albertel 1663:     if ($home eq 'no_host') {
                   1664:         return 'not_found';
1.1       albertel 1665:     }
                   1666:     my $answer=reply("sub:$fname",$home);
1.64      www      1667:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1668: 	$answer.=' by '.$home;
                   1669:     }
1.1       albertel 1670:     return $answer;
                   1671: }
                   1672:     
1.8       www      1673: # -------------------------------------------------------------- Replicate file
                   1674: 
                   1675: sub repcopy {
                   1676:     my $filename=shift;
1.23      www      1677:     $filename=~s/\/+/\//g;
1.607     raeburn  1678:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1679:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1680:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1681: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1682: 	return &repcopy_userfile($filename);
                   1683:     }
1.532     albertel 1684:     $filename=~s/[\n\r]//g;
1.8       www      1685:     my $transname="$filename.in.transfer";
1.828     www      1686: # FIXME: this should flock
1.607     raeburn  1687:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1688:     my $remoteurl=subscribe($filename);
1.64      www      1689:     if ($remoteurl =~ /^con_lost by/) {
                   1690: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1691:            return 'unavailable';
1.8       www      1692:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1693: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1694: 	   return 'not_found';
1.64      www      1695:     } elsif ($remoteurl =~ /^rejected by/) {
                   1696: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1697:            return 'forbidden';
1.20      www      1698:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1699:            return 'ok';
1.8       www      1700:     } else {
1.290     www      1701:         my $author=$filename;
                   1702:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1703:         my ($udom,$uname)=split(/\//,$author);
                   1704:         my $home=homeserver($uname,$udom);
                   1705:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1706:            my @parts=split(/\//,$filename);
                   1707:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1708:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1709:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1710: 	       return 'bad_request';
1.8       www      1711:            }
                   1712:            my $count;
                   1713:            for ($count=5;$count<$#parts;$count++) {
                   1714:                $path.="/$parts[$count]";
                   1715:                if ((-e $path)!=1) {
                   1716: 		   mkdir($path,0777);
                   1717:                }
                   1718:            }
                   1719:            my $ua=new LWP::UserAgent;
                   1720:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1721:            my $response=$ua->request($request,$transname);
                   1722:            if ($response->is_error()) {
                   1723: 	       unlink($transname);
                   1724:                my $message=$response->status_line;
1.672     albertel 1725:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1726:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1727:                return 'unavailable';
1.8       www      1728:            } else {
1.16      www      1729: 	       if ($remoteurl!~/\.meta$/) {
                   1730:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1731:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1732:                   if ($mresponse->is_error()) {
                   1733: 		      unlink($filename.'.meta');
                   1734:                       &logthis(
1.672     albertel 1735:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1736:                   }
                   1737: 	       }
1.8       www      1738:                rename($transname,$filename);
1.607     raeburn  1739:                return 'ok';
1.8       www      1740:            }
1.290     www      1741:        }
1.8       www      1742:     }
1.330     www      1743: }
                   1744: 
                   1745: # ------------------------------------------------ Get server side include body
                   1746: sub ssi_body {
1.381     albertel 1747:     my ($filelink,%form)=@_;
1.606     matthew  1748:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1749:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1750:     }
1.953     www      1751:     my $output='';
                   1752:     my $response;
                   1753:     if ($filelink=~/^http\:/) {
1.954     raeburn  1754:        ($output,$response)=&externalssi($filelink);
1.953     www      1755:     } else {
                   1756:        ($output,$response)=&ssi($filelink,%form);
                   1757:     }
1.778     albertel 1758:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1759:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1760:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1761:     if (wantarray) {
                   1762:         return ($output, $response);
                   1763:     } else {
                   1764:         return $output;
                   1765:     }
1.8       www      1766: }
                   1767: 
1.15      www      1768: # --------------------------------------------------------- Server Side Include
                   1769: 
1.782     albertel 1770: sub absolute_url {
                   1771:     my ($host_name) = @_;
                   1772:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1773:     if ($host_name eq '') {
                   1774: 	$host_name = $ENV{'SERVER_NAME'};
                   1775:     }
                   1776:     return $protocol.$host_name;
                   1777: }
                   1778: 
1.942     foxr     1779: #
                   1780: #   Server side include.
                   1781: # Parameters:
                   1782: #  fn     Possibly encrypted resource name/id.
                   1783: #  form   Hash that describes how the rendering should be done
                   1784: #         and other things.
1.944     foxr     1785: # Returns:
1.950     raeburn  1786: #   Scalar context: The content of the response.
                   1787: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1788: #     
1.15      www      1789: sub ssi {
                   1790: 
1.944     foxr     1791:     my ($fn,%form)=@_;
1.15      www      1792:     my $ua=new LWP::UserAgent;
1.23      www      1793:     my $request;
1.711     albertel 1794: 
                   1795:     $form{'no_update_last_known'}=1;
1.895     albertel 1796:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1797:     if (%form) {
1.782     albertel 1798:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1799:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1800:     } else {
1.782     albertel 1801:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1802:     }
                   1803: 
1.15      www      1804:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1805:     my $response=$ua->request($request);
                   1806: 
1.944     foxr     1807:     if (wantarray) {
                   1808: 	return ($response->content, $response);
                   1809:     } else {
                   1810: 	return $response->content;
1.942     foxr     1811:     }
1.324     www      1812: }
                   1813: 
                   1814: sub externalssi {
                   1815:     my ($url)=@_;
                   1816:     my $ua=new LWP::UserAgent;
                   1817:     my $request=new HTTP::Request('GET',$url);
                   1818:     my $response=$ua->request($request);
1.954     raeburn  1819:     if (wantarray) {
                   1820:         return ($response->content, $response);
                   1821:     } else {
                   1822:         return $response->content;
                   1823:     }
1.15      www      1824: }
1.254     www      1825: 
1.492     albertel 1826: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1827: 
                   1828: sub allowuploaded {
                   1829:     my ($srcurl,$url)=@_;
                   1830:     $url=&clutter(&declutter($url));
                   1831:     my $dir=$url;
                   1832:     $dir=~s/\/[^\/]+$//;
                   1833:     my %httpref=();
                   1834:     my $httpurl=&hreflocation('',$url);
                   1835:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1836:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1837: }
1.477     raeburn  1838: 
1.478     albertel 1839: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1840: # input: action, courseID, current domain, intended
1.637     raeburn  1841: #        path to file, source of file, instruction to parse file for objects,
                   1842: #        ref to hash for embedded objects,
                   1843: #        ref to hash for codebase of java objects.
                   1844: #
1.485     raeburn  1845: # output: url to file (if action was uploaddoc), 
                   1846: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1847: #
1.478     albertel 1848: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1849: # course.
1.477     raeburn  1850: #
1.478     albertel 1851: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1852: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1853: #          course's home server.
1.477     raeburn  1854: #
1.478     albertel 1855: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1856: #          be copied from $source (current location) to 
                   1857: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1858: #         and will then be copied to
                   1859: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1860: #         course's home server.
1.485     raeburn  1861: #
1.481     raeburn  1862: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1863: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1864: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1865: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1866: #         in course's home server.
1.637     raeburn  1867: #
1.477     raeburn  1868: 
                   1869: sub process_coursefile {
1.638     albertel 1870:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1871:     my $fetchresult;
1.638     albertel 1872:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1873:     if ($action eq 'propagate') {
1.638     albertel 1874:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1875: 			     $home);
1.481     raeburn  1876:     } else {
1.477     raeburn  1877:         my $fpath = '';
                   1878:         my $fname = $file;
1.478     albertel 1879:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1880:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1881:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1882:         if ($action eq 'copy') {
                   1883:             if ($source eq '') {
                   1884:                 $fetchresult = 'no source file';
                   1885:                 return $fetchresult;
                   1886:             } else {
                   1887:                 my $destination = $filepath.'/'.$fname;
                   1888:                 rename($source,$destination);
                   1889:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1890:                                  $home);
1.481     raeburn  1891:             }
                   1892:         } elsif ($action eq 'uploaddoc') {
                   1893:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1894:             print $fh $env{'form.'.$source};
1.481     raeburn  1895:             close($fh);
1.637     raeburn  1896:             if ($parser eq 'parse') {
1.961     raeburn  1897:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1898:                 unless ($parse_result eq 'ok') {
                   1899:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1900:                 }
                   1901:             }
1.477     raeburn  1902:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1903:                                  $home);
1.481     raeburn  1904:             if ($fetchresult eq 'ok') {
                   1905:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1906:             } else {
                   1907:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1908:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1909:                 return '/adm/notfound.html';
                   1910:             }
1.477     raeburn  1911:         }
                   1912:     }
1.485     raeburn  1913:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1914:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1915:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1916:     }
                   1917:     return $fetchresult;
                   1918: }
                   1919: 
1.637     raeburn  1920: sub build_filepath {
                   1921:     my ($fpath) = @_;
                   1922:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1923:     unless ($fpath eq '') {
                   1924:         my @parts=split('/',$fpath);
                   1925:         foreach my $part (@parts) {
                   1926:             $filepath.= '/'.$part;
                   1927:             if ((-e $filepath)!=1) {
                   1928:                 mkdir($filepath,0777);
                   1929:             }
                   1930:         }
                   1931:     }
                   1932:     return $filepath;
                   1933: }
                   1934: 
                   1935: sub store_edited_file {
1.638     albertel 1936:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1937:     my $file = $primary_url;
                   1938:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1939:     my $fpath = '';
                   1940:     my $fname = $file;
                   1941:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1942:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1943:     my $filepath = &build_filepath($fpath);
                   1944:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1945:     print $fh $content;
                   1946:     close($fh);
1.638     albertel 1947:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1948:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1949: 			  $home);
1.637     raeburn  1950:     if ($$fetchresult eq 'ok') {
                   1951:         return '/uploaded/'.$fpath.'/'.$fname;
                   1952:     } else {
1.638     albertel 1953:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1954: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1955:         return '/adm/notfound.html';
                   1956:     }
                   1957: }
                   1958: 
1.531     albertel 1959: sub clean_filename {
1.831     albertel 1960:     my ($fname,$args)=@_;
1.315     www      1961: # Replace Windows backslashes by forward slashes
1.257     www      1962:     $fname=~s/\\/\//g;
1.831     albertel 1963:     if (!$args->{'keep_path'}) {
                   1964:         # Get rid of everything but the actual filename
                   1965: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1966:     }
1.315     www      1967: # Replace spaces by underscores
                   1968:     $fname=~s/\s+/\_/g;
                   1969: # Replace all other weird characters by nothing
1.831     albertel 1970:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1971: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1972: # numbers
                   1973:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1974:     return $fname;
                   1975: }
                   1976: 
1.608     albertel 1977: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1978: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1979: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1980: #        $coursedoc - if true up to the current course
                   1981: #                     if false
                   1982: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1983: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1984: #        $allfiles - reference to hash for embedded objects
                   1985: #        $codebase - reference to hash for codebase of java objects
                   1986: #        $desuname - username for permanent storage of uploaded file
                   1987: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1988: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1989: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1990: # 
1.686     albertel 1991: # output: url of file in userspace, or error: <message> 
                   1992: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1993: 
                   1994: 
1.531     albertel 1995: sub userfileupload {
1.860     raeburn  1996:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1997:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1998:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1999:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2000:     $fname=&clean_filename($fname);
1.315     www      2001: # See if there is anything left
1.257     www      2002:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2003:     chop($env{'form.'.$formname});
1.523     raeburn  2004:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2005:         my $now = time;
                   2006:         my $filepath = 'tmp/helprequests/'.$now;
                   2007:         my @parts=split(/\//,$filepath);
                   2008:         my $fullpath = $perlvar{'lonDaemons'};
                   2009:         for (my $i=0;$i<@parts;$i++) {
                   2010:             $fullpath .= '/'.$parts[$i];
                   2011:             if ((-e $fullpath)!=1) {
                   2012:                 mkdir($fullpath,0777);
                   2013:             }
                   2014:         }
                   2015:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2016:         print $fh $env{'form.'.$formname};
1.523     raeburn  2017:         close($fh);
1.741     raeburn  2018:         return $fullpath.'/'.$fname;
                   2019:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2020:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2021:                        '_'.$env{'user.domain'}.'/pending';
                   2022:         my @parts=split(/\//,$filepath);
                   2023:         my $fullpath = $perlvar{'lonDaemons'};
                   2024:         for (my $i=0;$i<@parts;$i++) {
                   2025:             $fullpath .= '/'.$parts[$i];
                   2026:             if ((-e $fullpath)!=1) {
                   2027:                 mkdir($fullpath,0777);
                   2028:             }
                   2029:         }
                   2030:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2031:         print $fh $env{'form.'.$formname};
                   2032:         close($fh);
                   2033:         return $fullpath.'/'.$fname;
1.523     raeburn  2034:     }
1.719     banghart 2035:     
1.258     www      2036: # Create the directory if not present
1.493     albertel 2037:     $fname="$subdir/$fname";
1.259     www      2038:     if ($coursedoc) {
1.638     albertel 2039: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2040: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2041:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2042:             return &finishuserfileupload($docuname,$docudom,
                   2043: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2044: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2045:         } else {
1.620     albertel 2046:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2047:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2048: 				       $fname,$formname,$parser,
                   2049: 				       $allfiles,$codebase);
1.481     raeburn  2050:         }
1.719     banghart 2051:     } elsif (defined($destuname)) {
                   2052:         my $docuname=$destuname;
                   2053:         my $docudom=$destudom;
1.860     raeburn  2054: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2055: 				     $parser,$allfiles,$codebase,
                   2056:                                      $thumbwidth,$thumbheight);
1.719     banghart 2057:         
1.259     www      2058:     } else {
1.638     albertel 2059:         my $docuname=$env{'user.name'};
                   2060:         my $docudom=$env{'user.domain'};
1.714     raeburn  2061:         if (exists($env{'form.group'})) {
                   2062:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2063:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2064:         }
1.860     raeburn  2065: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2066: 				     $parser,$allfiles,$codebase,
                   2067:                                      $thumbwidth,$thumbheight);
1.259     www      2068:     }
1.271     www      2069: }
                   2070: 
                   2071: sub finishuserfileupload {
1.860     raeburn  2072:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2073:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2074:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2075:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2076:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2077:     $file=$fname;
                   2078:     if ($fname=~m|/|) {
                   2079:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2080: 	$path.=$fnamepath.'/';
                   2081:     }
1.259     www      2082:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2083:     my $count;
                   2084:     for ($count=4;$count<=$#parts;$count++) {
                   2085:         $filepath.="/$parts[$count]";
                   2086:         if ((-e $filepath)!=1) {
                   2087: 	    mkdir($filepath,0777);
                   2088:         }
                   2089:     }
                   2090: # Save the file
                   2091:     {
1.701     albertel 2092: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2093: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2094: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2095: 	    return '/adm/notfound.html';
                   2096: 	}
                   2097: 	if (!print FH ($env{'form.'.$formname})) {
                   2098: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2099: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2100: 	    return '/adm/notfound.html';
                   2101: 	}
1.570     albertel 2102: 	close(FH);
1.258     www      2103:     }
1.637     raeburn  2104:     if ($parser eq 'parse') {
1.961     raeburn  2105:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2106: 						   $codebase);
1.637     raeburn  2107:         unless ($parse_result eq 'ok') {
1.638     albertel 2108:             &logthis('Failed to parse '.$filepath.$file.
                   2109: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2110:         }
                   2111:     }
1.860     raeburn  2112:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2113:         my $input = $filepath.'/'.$file;
                   2114:         my $output = $filepath.'/'.'tn-'.$file;
                   2115:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2116:         system("convert -sample $thumbsize $input $output");
                   2117:         if (-e $filepath.'/'.'tn-'.$file) {
                   2118:             $fetchthumb  = 1; 
                   2119:         }
                   2120:     }
1.858     raeburn  2121:  
1.259     www      2122: # Notify homeserver to grep it
                   2123: #
1.638     albertel 2124:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2125:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2126:     if ($fetchresult eq 'ok') {
1.860     raeburn  2127:         if ($fetchthumb) {
                   2128:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2129:             if ($thumbresult ne 'ok') {
                   2130:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2131:                          $docuhome.': '.$thumbresult);
                   2132:             }
                   2133:         }
1.259     www      2134: #
1.258     www      2135: # Return the URL to it
1.494     albertel 2136:         return '/uploaded/'.$path.$file;
1.263     www      2137:     } else {
1.494     albertel 2138:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2139: 		 ': '.$fetchresult);
1.263     www      2140:         return '/adm/notfound.html';
1.858     raeburn  2141:     }
1.493     albertel 2142: }
                   2143: 
1.637     raeburn  2144: sub extract_embedded_items {
1.961     raeburn  2145:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2146:     my @state = ();
                   2147:     my %javafiles = (
                   2148:                       codebase => '',
                   2149:                       code => '',
                   2150:                       archive => ''
                   2151:                     );
                   2152:     my %mediafiles = (
                   2153:                       src => '',
                   2154:                       movie => '',
                   2155:                      );
1.648     raeburn  2156:     my $p;
                   2157:     if ($content) {
                   2158:         $p = HTML::LCParser->new($content);
                   2159:     } else {
1.961     raeburn  2160:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2161:     }
1.641     albertel 2162:     while (my $t=$p->get_token()) {
1.640     albertel 2163: 	if ($t->[0] eq 'S') {
                   2164: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2165: 	    push(@state, $tagname);
1.648     raeburn  2166:             if (lc($tagname) eq 'allow') {
                   2167:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2168:             }
1.640     albertel 2169: 	    if (lc($tagname) eq 'img') {
                   2170: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2171: 	    }
1.886     albertel 2172: 	    if (lc($tagname) eq 'a') {
                   2173: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2174: 	    }
1.645     raeburn  2175:             if (lc($tagname) eq 'script') {
                   2176:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2177:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2178:                 } else {
                   2179:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2180:                 }
                   2181:             }
                   2182:             if (lc($tagname) eq 'link') {
                   2183:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2184:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2185:                 }
                   2186:             }
1.640     albertel 2187: 	    if (lc($tagname) eq 'object' ||
                   2188: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2189: 		foreach my $item (keys(%javafiles)) {
                   2190: 		    $javafiles{$item} = '';
                   2191: 		}
                   2192: 	    }
                   2193: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2194: 		my $name = lc($attr->{'name'});
                   2195: 		foreach my $item (keys(%javafiles)) {
                   2196: 		    if ($name eq $item) {
                   2197: 			$javafiles{$item} = $attr->{'value'};
                   2198: 			last;
                   2199: 		    }
                   2200: 		}
                   2201: 		foreach my $item (keys(%mediafiles)) {
                   2202: 		    if ($name eq $item) {
                   2203: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2204: 			last;
                   2205: 		    }
                   2206: 		}
                   2207: 	    }
                   2208: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2209: 		foreach my $item (keys(%javafiles)) {
                   2210: 		    if ($attr->{$item}) {
                   2211: 			$javafiles{$item} = $attr->{$item};
                   2212: 			last;
                   2213: 		    }
                   2214: 		}
                   2215: 		foreach my $item (keys(%mediafiles)) {
                   2216: 		    if ($attr->{$item}) {
                   2217: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2218: 			last;
                   2219: 		    }
                   2220: 		}
                   2221: 	    }
                   2222: 	} elsif ($t->[0] eq 'E') {
                   2223: 	    my ($tagname) = ($t->[1]);
                   2224: 	    if ($javafiles{'codebase'} ne '') {
                   2225: 		$javafiles{'codebase'} .= '/';
                   2226: 	    }  
                   2227: 	    if (lc($tagname) eq 'applet' ||
                   2228: 		lc($tagname) eq 'object' ||
                   2229: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2230: 		) {
                   2231: 		foreach my $item (keys(%javafiles)) {
                   2232: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2233: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2234: 			&add_filetype($allfiles,$file,$item);
                   2235: 		    }
                   2236: 		}
                   2237: 	    } 
                   2238: 	    pop @state;
                   2239: 	}
                   2240:     }
1.637     raeburn  2241:     return 'ok';
                   2242: }
                   2243: 
1.639     albertel 2244: sub add_filetype {
                   2245:     my ($allfiles,$file,$type)=@_;
                   2246:     if (exists($allfiles->{$file})) {
                   2247: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2248: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2249: 	}
                   2250:     } else {
                   2251: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2252:     }
                   2253: }
                   2254: 
1.493     albertel 2255: sub removeuploadedurl {
                   2256:     my ($url)=@_;
                   2257:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2258:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2259: }
                   2260: 
                   2261: sub removeuserfile {
                   2262:     my ($docuname,$docudom,$fname)=@_;
                   2263:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2264:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2265:     if ($result eq 'ok') {
                   2266:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2267:             my $metafile = $fname.'.meta';
                   2268:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2269: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2270:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2271:             my $sqlresult = 
1.823     albertel 2272:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2273:                                         'portfolio_metadata',$group,
                   2274:                                         'delete');
1.798     raeburn  2275:         }
                   2276:     }
                   2277:     return $result;
1.257     www      2278: }
1.15      www      2279: 
1.530     albertel 2280: sub mkdiruserfile {
                   2281:     my ($docuname,$docudom,$dir)=@_;
                   2282:     my $home=&homeserver($docuname,$docudom);
                   2283:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2284: }
                   2285: 
1.531     albertel 2286: sub renameuserfile {
                   2287:     my ($docuname,$docudom,$old,$new)=@_;
                   2288:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2289:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2290:                         &escape("$old").':'.&escape("$new"),$home);
                   2291:     if ($result eq 'ok') {
                   2292:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2293:             my $oldmeta = $old.'.meta';
                   2294:             my $newmeta = $new.'.meta';
                   2295:             my $metaresult = 
                   2296:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2297: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2298:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2299:             my $sqlresult = 
1.823     albertel 2300:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2301:                                         'portfolio_metadata',$group,
                   2302:                                         'delete');
1.798     raeburn  2303:         }
                   2304:     }
                   2305:     return $result;
1.531     albertel 2306: }
                   2307: 
1.14      www      2308: # ------------------------------------------------------------------------- Log
                   2309: 
                   2310: sub log {
                   2311:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2312:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2313: }
                   2314: 
                   2315: # ------------------------------------------------------------------ Course Log
1.352     www      2316: #
                   2317: # This routine flushes several buffers of non-mission-critical nature
                   2318: #
1.157     www      2319: 
                   2320: sub flushcourselogs {
1.352     www      2321:     &logthis('Flushing log buffers');
                   2322: #
                   2323: # course logs
                   2324: # This is a log of all transactions in a course, which can be used
                   2325: # for data mining purposes
                   2326: #
                   2327: # It also collects the courseid database, which lists last transaction
                   2328: # times and course titles for all courseids
                   2329: #
                   2330:     my %courseidbuffer=();
1.921     raeburn  2331:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2332:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2333: 		          &escape($courselogs{$crsid}),
                   2334: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2335: 	    delete $courselogs{$crsid};
                   2336:         } else {
                   2337:             &logthis('Failed to flush log buffer for '.$crsid);
                   2338:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2339:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2340:                         " exceeded maximum size, deleting.</font>");
                   2341:                delete $courselogs{$crsid};
                   2342:             }
1.352     www      2343:         }
1.920     raeburn  2344:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2345:             'description' => $coursedescrbuf{$crsid},
                   2346:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2347:             'type'        => $coursetypebuf{$crsid},
                   2348:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2349:         };
1.191     harris41 2350:     }
1.352     www      2351: #
                   2352: # Write course id database (reverse lookup) to homeserver of courses 
                   2353: # Is used in pickcourse
                   2354: #
1.840     albertel 2355:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2356:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2357:                                     $courseidbuffer{$crs_home},
                   2358:                                     $crs_home,'timeonly');
1.352     www      2359:     }
                   2360: #
                   2361: # File accesses
                   2362: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2363: #
1.449     matthew  2364:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2365:         if ($entry =~ /___count$/) {
                   2366:             my ($dom,$name);
1.807     albertel 2367:             ($dom,$name,undef)=
1.811     albertel 2368: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2369:             if (! defined($dom) || $dom eq '' || 
                   2370:                 ! defined($name) || $name eq '') {
1.620     albertel 2371:                 my $cid = $env{'request.course.id'};
                   2372:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2373:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2374:             }
1.450     matthew  2375:             my $value = $accesshash{$entry};
                   2376:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2377:             my %temphash=($url => $value);
1.449     matthew  2378:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2379:             if ($result eq 'ok') {
                   2380:                 delete $accesshash{$entry};
                   2381:             } elsif ($result eq 'unknown_cmd') {
                   2382:                 # Target server has old code running on it.
1.450     matthew  2383:                 my %temphash=($entry => $value);
1.449     matthew  2384:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2385:                     delete $accesshash{$entry};
                   2386:                 }
                   2387:             }
                   2388:         } else {
1.811     albertel 2389:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2390:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2391:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2392:                 delete $accesshash{$entry};
                   2393:             }
1.185     www      2394:         }
1.191     harris41 2395:     }
1.352     www      2396: #
                   2397: # Roles
                   2398: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2399: #
1.800     albertel 2400:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2401:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2402: 	    split(/\:/,$entry);
                   2403:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2404:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2405:                 $rudom,$runame) eq 'ok') {
                   2406: 	    delete $userrolehash{$entry};
                   2407:         }
                   2408:     }
1.662     raeburn  2409: #
                   2410: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2411: #
                   2412:     my %domrolebuffer = ();
                   2413:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2414:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2415:         if ($domrolebuffer{$rudom}) {
                   2416:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2417:                       '='.&escape($domainrolehash{$entry});
                   2418:         } else {
                   2419:             $domrolebuffer{$rudom}.=&escape($entry).
                   2420:                       '='.&escape($domainrolehash{$entry});
                   2421:         }
                   2422:         delete $domainrolehash{$entry};
                   2423:     }
                   2424:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2425: 	my %servers = &get_servers($dom,'library');
                   2426: 	foreach my $tryserver (keys(%servers)) {
                   2427: 	    unless (&reply('domroleput:'.$dom.':'.
                   2428: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2429: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2430: 	    }
1.662     raeburn  2431:         }
                   2432:     }
1.186     www      2433:     $dumpcount++;
1.157     www      2434: }
                   2435: 
                   2436: sub courselog {
                   2437:     my $what=shift;
1.158     www      2438:     $what=time.':'.$what;
1.620     albertel 2439:     unless ($env{'request.course.id'}) { return ''; }
                   2440:     $coursedombuf{$env{'request.course.id'}}=
                   2441:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2442:     $coursenumbuf{$env{'request.course.id'}}=
                   2443:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2444:     $coursehombuf{$env{'request.course.id'}}=
                   2445:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2446:     $coursedescrbuf{$env{'request.course.id'}}=
                   2447:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2448:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2449:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2450:     $courseownerbuf{$env{'request.course.id'}}=
                   2451:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2452:     $coursetypebuf{$env{'request.course.id'}}=
                   2453:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2454:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2455: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2456:     } else {
1.620     albertel 2457: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2458:     }
1.620     albertel 2459:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2460: 	&flushcourselogs();
                   2461:     }
1.158     www      2462: }
                   2463: 
                   2464: sub courseacclog {
                   2465:     my $fnsymb=shift;
1.620     albertel 2466:     unless ($env{'request.course.id'}) { return ''; }
                   2467:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2468:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2469:         $what.=':POST';
1.583     matthew  2470:         # FIXME: Probably ought to escape things....
1.800     albertel 2471: 	foreach my $key (keys(%env)) {
                   2472:             if ($key=~/^form\.(.*)/) {
                   2473: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2474:             }
1.191     harris41 2475:         }
1.583     matthew  2476:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2477:         # FIXME: We should not be depending on a form parameter that someone
                   2478:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2479:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2480:             $what.= ':POST';
                   2481:             # FIXME: Probably ought to escape things....
                   2482:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2483:                                  'crsdiscuss') {
1.620     albertel 2484:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2485:             }
                   2486:         }
1.158     www      2487:     }
                   2488:     &courselog($what);
1.149     www      2489: }
                   2490: 
1.185     www      2491: sub countacc {
                   2492:     my $url=&declutter(shift);
1.458     matthew  2493:     return if (! defined($url) || $url eq '');
1.620     albertel 2494:     unless ($env{'request.course.id'}) { return ''; }
                   2495:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2496:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2497:     $accesshash{$key}++;
1.185     www      2498: }
1.349     www      2499: 
1.361     www      2500: sub linklog {
                   2501:     my ($from,$to)=@_;
                   2502:     $from=&declutter($from);
                   2503:     $to=&declutter($to);
                   2504:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2505:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2506: }
                   2507:   
1.349     www      2508: sub userrolelog {
                   2509:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2510:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2511:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2512:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2513:         ($trole=~/^ta/)) {
1.350     www      2514:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2515:        $userrolehash
                   2516:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2517:                     =$tend.':'.$tstart;
1.662     raeburn  2518:     }
1.898     albertel 2519:     if (($env{'request.role'} =~ /dc\./) &&
                   2520: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2521: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2522: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2523:        $userrolehash
                   2524:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2525:                     =$tend.':'.$tstart;
                   2526:     }
1.662     raeburn  2527:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2528:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2529:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2530:         ($trole=~/^sc/)) {
                   2531:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2532:        $domainrolehash
                   2533:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2534:                     = $tend.':'.$tstart;
                   2535:     }
1.351     www      2536: }
                   2537: 
1.957     raeburn  2538: sub courserolelog {
                   2539:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2540:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2541:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2542:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2543:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2544:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2545:             my $cdom = $1;
                   2546:             my $cnum = $2;
                   2547:             my $sec = $3;
                   2548:             my $namespace = 'rolelog';
                   2549:             my %storehash = (
                   2550:                                role    => $trole,
                   2551:                                start   => $tstart,
                   2552:                                end     => $tend,
                   2553:                                selfenroll => $selfenroll,
                   2554:                                context    => $context,
                   2555:                             );
                   2556:             if ($trole eq 'gr') {
                   2557:                 $namespace = 'groupslog';
                   2558:                 $storehash{'group'} = $sec;
                   2559:             } else {
                   2560:                 $storehash{'section'} = $sec;
                   2561:             }
                   2562:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2563:         }
                   2564:     }
                   2565:     return;
                   2566: }
                   2567: 
1.351     www      2568: sub get_course_adv_roles {
1.948     raeburn  2569:     my ($cid,$codes) = @_;
1.620     albertel 2570:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2571:     my %coursehash=&coursedescription($cid);
1.470     www      2572:     my %nothide=();
1.800     albertel 2573:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2574:         if ($user !~ /:/) {
                   2575: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2576:         } else {
                   2577:             $nothide{$user}=1;
                   2578:         }
1.470     www      2579:     }
1.351     www      2580:     my %returnhash=();
                   2581:     my %dumphash=
                   2582:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2583:     my $now=time;
1.800     albertel 2584:     foreach my $entry (keys %dumphash) {
                   2585: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2586:         if (($tstart) && ($tstart<0)) { next; }
                   2587:         if (($tend) && ($tend<$now)) { next; }
                   2588:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2589:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2590: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2591: 	if ((&privileged($username,$domain)) && 
                   2592: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2593: 	if ($role eq 'cr') { next; }
1.948     raeburn  2594:         if ($codes) {
                   2595:             if ($section) { $role .= ':'.$section; }
                   2596:             if ($returnhash{$role}) {
                   2597:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2598:             } else {
                   2599:                 $returnhash{$role}=$username.':'.$domain;
                   2600:             }
1.351     www      2601:         } else {
1.948     raeburn  2602:             my $key=&plaintext($role);
                   2603:             if ($section) { $key.=' (Section '.$section.')'; }
                   2604:             if ($returnhash{$key}) {
                   2605: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2606:             } else {
                   2607:                 $returnhash{$key}=$username.':'.$domain;
                   2608:             }
1.351     www      2609:         }
1.948     raeburn  2610:     }
1.400     www      2611:     return %returnhash;
                   2612: }
                   2613: 
                   2614: sub get_my_roles {
1.937     raeburn  2615:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2616:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2617:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2618:     my (%dumphash,%nothide);
1.858     raeburn  2619:     if ($context eq 'userroles') { 
                   2620:         %dumphash = &dump('roles',$udom,$uname);
                   2621:     } else {
                   2622:         %dumphash=
1.400     www      2623:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2624:         if ($hidepriv) {
                   2625:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2626:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2627:                 if ($user !~ /:/) {
                   2628:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2629:                 } else {
                   2630:                     $nothide{$user} = 1;
                   2631:                 }
                   2632:             }
                   2633:         }
1.858     raeburn  2634:     }
1.400     www      2635:     my %returnhash=();
                   2636:     my $now=time;
1.800     albertel 2637:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2638:         my ($role,$tend,$tstart);
                   2639:         if ($context eq 'userroles') {
                   2640: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2641:         } else {
                   2642:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2643:         }
1.400     www      2644:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2645:         my $status = 'active';
1.939     raeburn  2646:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2647:             $status = 'previous';
                   2648:         } 
                   2649:         if (($tstart) && ($now<$tstart)) {
                   2650:             $status = 'future';
                   2651:         }
                   2652:         if (ref($types) eq 'ARRAY') {
                   2653:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2654:                 next;
                   2655:             } 
                   2656:         } else {
                   2657:             if ($status ne 'active') {
                   2658:                 next;
                   2659:             }
                   2660:         }
1.867     raeburn  2661:         my ($rolecode,$username,$domain,$section,$area);
                   2662:         if ($context eq 'userroles') {
                   2663:             ($area,$rolecode) = split(/_/,$entry);
                   2664:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2665:         } else {
                   2666:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2667:         }
1.832     raeburn  2668:         if (ref($roledoms) eq 'ARRAY') {
                   2669:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2670:                 next;
                   2671:             }
                   2672:         }
                   2673:         if (ref($roles) eq 'ARRAY') {
                   2674:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2675:                 if ($role =~ /^cr\//) {
                   2676:                     if (!grep(/^cr$/,@{$roles})) {
                   2677:                         next;
                   2678:                     }
                   2679:                 } else {
                   2680:                     next;
                   2681:                 }
1.832     raeburn  2682:             }
1.867     raeburn  2683:         }
1.937     raeburn  2684:         if ($hidepriv) {
                   2685:             if ((&privileged($username,$domain)) &&
                   2686:                 (!$nothide{$username.':'.$domain})) { 
                   2687:                 next;
                   2688:             }
                   2689:         }
1.933     raeburn  2690:         if ($withsec) {
                   2691:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2692:                 $tstart.':'.$tend;
                   2693:         } else {
                   2694:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2695:         }
1.832     raeburn  2696:     }
1.373     www      2697:     return %returnhash;
1.399     www      2698: }
                   2699: 
                   2700: # ----------------------------------------------------- Frontpage Announcements
                   2701: #
                   2702: #
                   2703: 
                   2704: sub postannounce {
                   2705:     my ($server,$text)=@_;
1.844     albertel 2706:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2707:     unless ($text=~/\w/) { $text=''; }
                   2708:     return &reply('setannounce:'.&escape($text),$server);
                   2709: }
                   2710: 
                   2711: sub getannounce {
1.448     albertel 2712: 
                   2713:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2714: 	my $announcement='';
1.800     albertel 2715: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2716: 	close($fh);
1.399     www      2717: 	if ($announcement=~/\w/) { 
                   2718: 	    return 
                   2719:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2720:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2721: 	} else {
                   2722: 	    return '';
                   2723: 	}
                   2724:     } else {
                   2725: 	return '';
                   2726:     }
1.351     www      2727: }
1.353     www      2728: 
                   2729: # ---------------------------------------------------------- Course ID routines
                   2730: # Deal with domain's nohist_courseid.db files
                   2731: #
                   2732: 
                   2733: sub courseidput {
1.921     raeburn  2734:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2735:     my $outcome;
                   2736:     if ($caller eq 'timeonly') {
                   2737:         my $cids = '';
                   2738:         foreach my $item (keys(%$storehash)) {
                   2739:             $cids.=&escape($item).'&';
                   2740:         }
                   2741:         $cids=~s/\&$//;
                   2742:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2743:                           $coursehome);       
                   2744:     } else {
                   2745:         my $items = '';
                   2746:         foreach my $item (keys(%$storehash)) {
                   2747:             $items.= &escape($item).'='.
                   2748:                      &freeze_escape($$storehash{$item}).'&';
                   2749:         }
                   2750:         $items=~s/\&$//;
                   2751:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2752:                           $coursehome);
1.918     raeburn  2753:     }
                   2754:     if ($outcome eq 'unknown_cmd') {
                   2755:         my $what;
                   2756:         foreach my $cid (keys(%$storehash)) {
                   2757:             $what .= &escape($cid).'=';
1.921     raeburn  2758:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2759:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2760:             }
                   2761:             $what =~ s/\:$/&/;
                   2762:         }
                   2763:         $what =~ s/\&$//;  
                   2764:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2765:     } else {
                   2766:         return $outcome;
                   2767:     }
1.353     www      2768: }
                   2769: 
                   2770: sub courseiddump {
1.921     raeburn  2771:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2772:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2773:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2774:     my $as_hash = 1;
                   2775:     my %returnhash;
                   2776:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2777:     my %libserv = &all_library();
                   2778:     foreach my $tryserver (keys(%libserv)) {
                   2779:         if ( (  $hostidflag == 1 
                   2780: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2781: 	     || (!defined($hostidflag)) ) {
                   2782: 
1.918     raeburn  2783: 	    if (($domfilter eq '') ||
                   2784: 		(&host_domain($tryserver) eq $domfilter)) {
                   2785:                 my $rep = 
                   2786:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2787:                          $sincefilter.':'.&escape($descfilter).':'.
                   2788:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2789:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2790:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2791:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2792:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2793:                 my @pairs=split(/\&/,$rep);
                   2794:                 foreach my $item (@pairs) {
                   2795:                     my ($key,$value)=split(/\=/,$item,2);
                   2796:                     $key = &unescape($key);
                   2797:                     next if ($key =~ /^error: 2 /);
                   2798:                     my $result = &thaw_unescape($value);
                   2799:                     if (ref($result) eq 'HASH') {
                   2800:                         $returnhash{$key}=$result;
                   2801:                     } else {
1.921     raeburn  2802:                         my @responses = split(/:/,$value);
                   2803:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2804:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2805:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2806:                         }
                   2807:                     } 
1.353     www      2808:                 }
                   2809:             }
                   2810:         }
                   2811:     }
                   2812:     return %returnhash;
                   2813: }
                   2814: 
1.658     raeburn  2815: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2816: 
                   2817: sub dcmailput {
1.685     raeburn  2818:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2819:     my $status = &Apache::lonnet::critical(
1.740     www      2820:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2821:        &escape($message),$server);
1.662     raeburn  2822:     return $status;
                   2823: }
                   2824: 
1.658     raeburn  2825: sub dcmaildump {
                   2826:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2827:     my %returnhash=();
1.846     albertel 2828: 
                   2829:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2830:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2831:                                                          &escape($enddate).':';
                   2832: 	my @esc_senders=map { &escape($_)} @$senders;
                   2833: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2834: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2835:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2836:             if (($key) && ($value)) {
                   2837:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2838:             }
                   2839:         }
                   2840:     }
                   2841:     return %returnhash;
                   2842: }
1.662     raeburn  2843: # ---------------------------------------------------------- Domain roles
                   2844: 
                   2845: sub get_domain_roles {
                   2846:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2847:     if (undef($startdate) || $startdate eq '') {
                   2848:         $startdate = '.';
                   2849:     }
                   2850:     if (undef($enddate) || $enddate eq '') {
                   2851:         $enddate = '.';
                   2852:     }
1.922     raeburn  2853:     my $rolelist;
                   2854:     if (ref($roles) eq 'ARRAY') {
                   2855:         $rolelist = join(':',@{$roles});
                   2856:     }
1.662     raeburn  2857:     my %personnel = ();
1.841     albertel 2858: 
                   2859:     my %servers = &get_servers($dom,'library');
                   2860:     foreach my $tryserver (keys(%servers)) {
                   2861: 	%{$personnel{$tryserver}}=();
                   2862: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2863: 					    &escape($startdate).':'.
                   2864: 					    &escape($enddate).':'.
                   2865: 					    &escape($rolelist), $tryserver))) {
                   2866: 	    my ($key,$value) = split(/\=/,$line,2);
                   2867: 	    if (($key) && ($value)) {
                   2868: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2869: 	    }
                   2870: 	}
1.662     raeburn  2871:     }
                   2872:     return %personnel;
                   2873: }
1.658     raeburn  2874: 
1.149     www      2875: # ----------------------------------------------------------- Check out an item
                   2876: 
1.504     albertel 2877: sub get_first_access {
                   2878:     my ($type,$argsymb)=@_;
1.790     albertel 2879:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2880:     if ($argsymb) { $symb=$argsymb; }
                   2881:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2882:     if ($type eq 'course') {
                   2883: 	$res='course';
                   2884:     } elsif ($type eq 'map') {
1.588     albertel 2885: 	$res=&symbread($map);
                   2886:     } else {
                   2887: 	$res=$symb;
                   2888:     }
                   2889:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2890:     return $times{"$courseid\0$res"};
1.504     albertel 2891: }
                   2892: 
                   2893: sub set_first_access {
                   2894:     my ($type)=@_;
1.790     albertel 2895:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2896:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2897:     if ($type eq 'course') {
                   2898: 	$res='course';
                   2899:     } elsif ($type eq 'map') {
1.588     albertel 2900: 	$res=&symbread($map);
                   2901:     } else {
                   2902: 	$res=$symb;
                   2903:     }
                   2904:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2905:     if (!$firstaccess) {
1.588     albertel 2906: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2907:     }
                   2908:     return 'already_set';
1.504     albertel 2909: }
                   2910: 
1.149     www      2911: sub checkout {
                   2912:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2913:     my $now=time;
                   2914:     my $lonhost=$perlvar{'lonHostID'};
                   2915:     my $infostr=&escape(
1.234     www      2916:                  'CHECKOUTTOKEN&'.
1.149     www      2917:                  $tuname.'&'.
                   2918:                  $tudom.'&'.
                   2919:                  $tcrsid.'&'.
                   2920:                  $symb.'&'.
                   2921: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2922:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2923:     if ($token=~/^error\:/) { 
1.672     albertel 2924:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2925:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2926:                  "</font>");
                   2927:         return ''; 
                   2928:     }
                   2929: 
1.149     www      2930:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2931:     $token=~tr/a-z/A-Z/;
                   2932: 
1.153     www      2933:     my %infohash=('resource.0.outtoken' => $token,
                   2934:                   'resource.0.checkouttime' => $now,
                   2935:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2936: 
                   2937:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2938:        return '';
1.151     www      2939:     } else {
1.672     albertel 2940:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2941:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2942:                  "</font>");
1.149     www      2943:     }    
                   2944: 
                   2945:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2946:                          &escape('Checkout '.$infostr.' - '.
                   2947:                                                  $token)) ne 'ok') {
                   2948: 	return '';
1.151     www      2949:     } else {
1.672     albertel 2950:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2951:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2952:                  "</font>");
1.149     www      2953:     }
1.151     www      2954:     return $token;
1.149     www      2955: }
                   2956: 
                   2957: # ------------------------------------------------------------ Check in an item
                   2958: 
                   2959: sub checkin {
                   2960:     my $token=shift;
1.150     www      2961:     my $now=time;
                   2962:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2963:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2964:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2965:     $dtoken=~s/\W/\_/g;
1.234     www      2966:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2967:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2968: 
1.154     www      2969:     unless (($tuname) && ($tudom)) {
                   2970:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2971:         return '';
                   2972:     }
                   2973:     
                   2974:     unless (&allowed('mgr',$tcrsid)) {
                   2975:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2976:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2977:         return '';
                   2978:     }
                   2979: 
1.153     www      2980:     my %infohash=('resource.0.intoken' => $token,
                   2981:                   'resource.0.checkintime' => $now,
                   2982:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2983: 
                   2984:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2985:        return '';
                   2986:     }    
                   2987: 
                   2988:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2989:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2990: 	return '';
                   2991:     }
                   2992: 
                   2993:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2994: }
                   2995: 
                   2996: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2997: 
                   2998: sub expirespread {
                   2999:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3000:     my $cid=$env{'request.course.id'}; 
1.110     www      3001:     if ($cid) {
                   3002:        my $now=time;
                   3003:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3004:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3005:                             $env{'course.'.$cid.'.num'}.
1.110     www      3006: 	        	    ':nohist_expirationdates:'.
                   3007:                             &escape($key).'='.$now,
1.620     albertel 3008:                             $env{'course.'.$cid.'.home'})
1.110     www      3009:     }
                   3010:     return 'ok';
1.14      www      3011: }
                   3012: 
1.109     www      3013: # ----------------------------------------------------- Devalidate Spreadsheets
                   3014: 
                   3015: sub devalidate {
1.325     www      3016:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3017:     my $cid=$env{'request.course.id'}; 
1.109     www      3018:     if ($cid) {
1.391     matthew  3019:         # delete the stored spreadsheets for
                   3020:         # - the student level sheet of this user in course's homespace
                   3021:         # - the assessment level sheet for this resource 
                   3022:         #   for this user in user's homespace
1.553     albertel 3023: 	# - current conditional state info
1.325     www      3024: 	my $key=$uname.':'.$udom.':';
1.109     www      3025:         my $status=
1.299     matthew  3026: 	    &del('nohist_calculatedsheets',
1.391     matthew  3027: 		 [$key.'studentcalc:'],
1.620     albertel 3028: 		 $env{'course.'.$cid.'.domain'},
                   3029: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3030: 		.' '.
                   3031: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3032: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3033:         unless ($status eq 'ok ok') {
                   3034:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3035:                     $uname.' at '.$udom.' for '.
1.109     www      3036: 		    $symb.': '.$status);
1.133     albertel 3037:         }
1.553     albertel 3038: 	&delenv('user.state.'.$cid);
1.109     www      3039:     }
                   3040: }
                   3041: 
1.265     albertel 3042: sub get_scalar {
                   3043:     my ($string,$end) = @_;
                   3044:     my $value;
                   3045:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3046: 	$value = $1;
                   3047:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3048: 	$value = $1;
                   3049:     }
                   3050:     return &unescape($value);
                   3051: }
                   3052: 
                   3053: sub array2str {
                   3054:   my (@array) = @_;
                   3055:   my $result=&arrayref2str(\@array);
                   3056:   $result=~s/^__ARRAY_REF__//;
                   3057:   $result=~s/__END_ARRAY_REF__$//;
                   3058:   return $result;
                   3059: }
                   3060: 
1.204     albertel 3061: sub arrayref2str {
                   3062:   my ($arrayref) = @_;
1.265     albertel 3063:   my $result='__ARRAY_REF__';
1.204     albertel 3064:   foreach my $elem (@$arrayref) {
1.265     albertel 3065:     if(ref($elem) eq 'ARRAY') {
                   3066:       $result.=&arrayref2str($elem).'&';
                   3067:     } elsif(ref($elem) eq 'HASH') {
                   3068:       $result.=&hashref2str($elem).'&';
                   3069:     } elsif(ref($elem)) {
                   3070:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3071:     } else {
                   3072:       $result.=&escape($elem).'&';
                   3073:     }
                   3074:   }
                   3075:   $result=~s/\&$//;
1.265     albertel 3076:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3077:   return $result;
                   3078: }
                   3079: 
1.168     albertel 3080: sub hash2str {
1.204     albertel 3081:   my (%hash) = @_;
                   3082:   my $result=&hashref2str(\%hash);
1.265     albertel 3083:   $result=~s/^__HASH_REF__//;
                   3084:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3085:   return $result;
                   3086: }
                   3087: 
                   3088: sub hashref2str {
                   3089:   my ($hashref)=@_;
1.265     albertel 3090:   my $result='__HASH_REF__';
1.800     albertel 3091:   foreach my $key (sort(keys(%$hashref))) {
                   3092:     if (ref($key) eq 'ARRAY') {
                   3093:       $result.=&arrayref2str($key).'=';
                   3094:     } elsif (ref($key) eq 'HASH') {
                   3095:       $result.=&hashref2str($key).'=';
                   3096:     } elsif (ref($key)) {
1.265     albertel 3097:       $result.='=';
1.800     albertel 3098:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3099:     } else {
1.800     albertel 3100: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3101:     }
                   3102: 
1.800     albertel 3103:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3104:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3105:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3106:       $result.=&hashref2str($hashref->{$key}).'&';
                   3107:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3108:        $result.='&';
1.800     albertel 3109:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3110:     } else {
1.800     albertel 3111:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3112:     }
                   3113:   }
1.168     albertel 3114:   $result=~s/\&$//;
1.265     albertel 3115:   $result .= '__END_HASH_REF__';
1.168     albertel 3116:   return $result;
                   3117: }
                   3118: 
                   3119: sub str2hash {
1.265     albertel 3120:     my ($string)=@_;
                   3121:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3122:     return %$hash;
                   3123: }
                   3124: 
                   3125: sub str2hashref {
1.168     albertel 3126:   my ($string) = @_;
1.265     albertel 3127: 
                   3128:   my %hash;
                   3129: 
                   3130:   if($string !~ /^__HASH_REF__/) {
                   3131:       if (! ($string eq '' || !defined($string))) {
                   3132: 	  $hash{'error'}='Not hash reference';
                   3133:       }
                   3134:       return (\%hash, $string);
                   3135:   }
                   3136: 
                   3137:   $string =~ s/^__HASH_REF__//;
                   3138: 
                   3139:   while($string !~ /^__END_HASH_REF__/) {
                   3140:       #key
                   3141:       my $key='';
                   3142:       if($string =~ /^__HASH_REF__/) {
                   3143:           ($key, $string)=&str2hashref($string);
                   3144:           if(defined($key->{'error'})) {
                   3145:               $hash{'error'}='Bad data';
                   3146:               return (\%hash, $string);
                   3147:           }
                   3148:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3149:           ($key, $string)=&str2arrayref($string);
                   3150:           if($key->[0] eq 'Array reference error') {
                   3151:               $hash{'error'}='Bad data';
                   3152:               return (\%hash, $string);
                   3153:           }
                   3154:       } else {
                   3155:           $string =~ s/^(.*?)=//;
1.267     albertel 3156: 	  $key=&unescape($1);
1.265     albertel 3157:       }
                   3158:       $string =~ s/^=//;
                   3159: 
                   3160:       #value
                   3161:       my $value='';
                   3162:       if($string =~ /^__HASH_REF__/) {
                   3163:           ($value, $string)=&str2hashref($string);
                   3164:           if(defined($value->{'error'})) {
                   3165:               $hash{'error'}='Bad data';
                   3166:               return (\%hash, $string);
                   3167:           }
                   3168:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3169:           ($value, $string)=&str2arrayref($string);
                   3170:           if($value->[0] eq 'Array reference error') {
                   3171:               $hash{'error'}='Bad data';
                   3172:               return (\%hash, $string);
                   3173:           }
                   3174:       } else {
                   3175: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3176:       }
                   3177:       $string =~ s/^&//;
                   3178: 
                   3179:       $hash{$key}=$value;
1.204     albertel 3180:   }
1.265     albertel 3181: 
                   3182:   $string =~ s/^__END_HASH_REF__//;
                   3183: 
                   3184:   return (\%hash, $string);
1.204     albertel 3185: }
                   3186: 
                   3187: sub str2array {
1.265     albertel 3188:     my ($string)=@_;
                   3189:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3190:     return @$array;
                   3191: }
                   3192: 
                   3193: sub str2arrayref {
1.204     albertel 3194:   my ($string) = @_;
1.265     albertel 3195:   my @array;
                   3196: 
                   3197:   if($string !~ /^__ARRAY_REF__/) {
                   3198:       if (! ($string eq '' || !defined($string))) {
                   3199: 	  $array[0]='Array reference error';
                   3200:       }
                   3201:       return (\@array, $string);
                   3202:   }
                   3203: 
                   3204:   $string =~ s/^__ARRAY_REF__//;
                   3205: 
                   3206:   while($string !~ /^__END_ARRAY_REF__/) {
                   3207:       my $value='';
                   3208:       if($string =~ /^__HASH_REF__/) {
                   3209:           ($value, $string)=&str2hashref($string);
                   3210:           if(defined($value->{'error'})) {
                   3211:               $array[0] ='Array reference error';
                   3212:               return (\@array, $string);
                   3213:           }
                   3214:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3215:           ($value, $string)=&str2arrayref($string);
                   3216:           if($value->[0] eq 'Array reference error') {
                   3217:               $array[0] ='Array reference error';
                   3218:               return (\@array, $string);
                   3219:           }
                   3220:       } else {
                   3221: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3222:       }
                   3223:       $string =~ s/^&//;
                   3224: 
                   3225:       push(@array, $value);
1.191     harris41 3226:   }
1.265     albertel 3227: 
                   3228:   $string =~ s/^__END_ARRAY_REF__//;
                   3229: 
                   3230:   return (\@array, $string);
1.168     albertel 3231: }
                   3232: 
1.167     albertel 3233: # -------------------------------------------------------------------Temp Store
                   3234: 
1.168     albertel 3235: sub tmpreset {
                   3236:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3237:   if (!$symb) {
                   3238:     $symb=&symbread();
1.620     albertel 3239:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3240:   }
                   3241:   $symb=escape($symb);
                   3242: 
1.620     albertel 3243:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3244:   $namespace=~s/\//\_/g;
                   3245:   $namespace=~s/\W//g;
                   3246: 
1.620     albertel 3247:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3248:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3249:   if ($domain eq 'public' && $stuname eq 'public') {
                   3250:       $stuname=$ENV{'REMOTE_ADDR'};
                   3251:   }
1.168     albertel 3252:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3253:   my %hash;
                   3254:   if (tie(%hash,'GDBM_File',
                   3255: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3256: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3257:     foreach my $key (keys %hash) {
1.180     albertel 3258:       if ($key=~ /:$symb/) {
1.168     albertel 3259: 	delete($hash{$key});
                   3260:       }
                   3261:     }
                   3262:   }
                   3263: }
                   3264: 
1.167     albertel 3265: sub tmpstore {
1.168     albertel 3266:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3267: 
                   3268:   if (!$symb) {
                   3269:     $symb=&symbread();
1.620     albertel 3270:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3271:   }
                   3272:   $symb=escape($symb);
                   3273: 
                   3274:   if (!$namespace) {
                   3275:     # I don't think we would ever want to store this for a course.
                   3276:     # it seems this will only be used if we don't have a course.
1.620     albertel 3277:     #$namespace=$env{'request.course.id'};
1.168     albertel 3278:     #if (!$namespace) {
1.620     albertel 3279:       $namespace=$env{'request.state'};
1.168     albertel 3280:     #}
                   3281:   }
                   3282:   $namespace=~s/\//\_/g;
                   3283:   $namespace=~s/\W//g;
1.620     albertel 3284:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3285:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3286:   if ($domain eq 'public' && $stuname eq 'public') {
                   3287:       $stuname=$ENV{'REMOTE_ADDR'};
                   3288:   }
1.168     albertel 3289:   my $now=time;
                   3290:   my %hash;
                   3291:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3292:   if (tie(%hash,'GDBM_File',
                   3293: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3294: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3295:     $hash{"version:$symb"}++;
                   3296:     my $version=$hash{"version:$symb"};
                   3297:     my $allkeys=''; 
                   3298:     foreach my $key (keys(%$storehash)) {
                   3299:       $allkeys.=$key.':';
1.591     albertel 3300:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3301:     }
                   3302:     $hash{"$version:$symb:timestamp"}=$now;
                   3303:     $allkeys.='timestamp';
                   3304:     $hash{"$version:keys:$symb"}=$allkeys;
                   3305:     if (untie(%hash)) {
                   3306:       return 'ok';
                   3307:     } else {
                   3308:       return "error:$!";
                   3309:     }
                   3310:   } else {
                   3311:     return "error:$!";
                   3312:   }
                   3313: }
1.167     albertel 3314: 
1.168     albertel 3315: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3316: 
1.168     albertel 3317: sub tmprestore {
                   3318:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3319: 
1.168     albertel 3320:   if (!$symb) {
                   3321:     $symb=&symbread();
1.620     albertel 3322:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3323:   }
                   3324:   $symb=escape($symb);
                   3325: 
1.620     albertel 3326:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3327: 
1.620     albertel 3328:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3329:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3330:   if ($domain eq 'public' && $stuname eq 'public') {
                   3331:       $stuname=$ENV{'REMOTE_ADDR'};
                   3332:   }
1.168     albertel 3333:   my %returnhash;
                   3334:   $namespace=~s/\//\_/g;
                   3335:   $namespace=~s/\W//g;
                   3336:   my %hash;
                   3337:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3338:   if (tie(%hash,'GDBM_File',
                   3339: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3340: 	  &GDBM_READER(),0640)) {
1.168     albertel 3341:     my $version=$hash{"version:$symb"};
                   3342:     $returnhash{'version'}=$version;
                   3343:     my $scope;
                   3344:     for ($scope=1;$scope<=$version;$scope++) {
                   3345:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3346:       my @keys=split(/:/,$vkeys);
                   3347:       my $key;
                   3348:       $returnhash{"$scope:keys"}=$vkeys;
                   3349:       foreach $key (@keys) {
1.591     albertel 3350: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3351: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3352:       }
                   3353:     }
1.168     albertel 3354:     if (!(untie(%hash))) {
                   3355:       return "error:$!";
                   3356:     }
                   3357:   } else {
                   3358:     return "error:$!";
                   3359:   }
                   3360:   return %returnhash;
1.167     albertel 3361: }
                   3362: 
1.9       www      3363: # ----------------------------------------------------------------------- Store
                   3364: 
                   3365: sub store {
1.124     www      3366:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3367:     my $home='';
                   3368: 
1.168     albertel 3369:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3370: 
1.213     www      3371:     $symb=&symbclean($symb);
1.122     albertel 3372:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3373: 
1.620     albertel 3374:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3375:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3376: 
                   3377:     &devalidate($symb,$stuname,$domain);
1.109     www      3378: 
                   3379:     $symb=escape($symb);
1.187     www      3380:     if (!$namespace) { 
1.620     albertel 3381:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3382:           return ''; 
                   3383:        } 
                   3384:     }
1.620     albertel 3385:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3386: 
                   3387:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3388:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3389: 
1.12      www      3390:     my $namevalue='';
1.800     albertel 3391:     foreach my $key (keys(%$storehash)) {
                   3392:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3393:     }
1.12      www      3394:     $namevalue=~s/\&$//;
1.187     www      3395:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3396:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3397: }
                   3398: 
1.47      www      3399: # -------------------------------------------------------------- Critical Store
                   3400: 
                   3401: sub cstore {
1.124     www      3402:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3403:     my $home='';
                   3404: 
1.168     albertel 3405:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3406: 
1.213     www      3407:     $symb=&symbclean($symb);
1.122     albertel 3408:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3409: 
1.620     albertel 3410:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3411:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3412: 
                   3413:     &devalidate($symb,$stuname,$domain);
1.109     www      3414: 
                   3415:     $symb=escape($symb);
1.187     www      3416:     if (!$namespace) { 
1.620     albertel 3417:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3418:           return ''; 
                   3419:        } 
                   3420:     }
1.620     albertel 3421:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3422: 
                   3423:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3424:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3425: 
1.47      www      3426:     my $namevalue='';
1.800     albertel 3427:     foreach my $key (keys(%$storehash)) {
                   3428:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3429:     }
1.47      www      3430:     $namevalue=~s/\&$//;
1.187     www      3431:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3432:     return critical
                   3433:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3434: }
                   3435: 
1.9       www      3436: # --------------------------------------------------------------------- Restore
                   3437: 
                   3438: sub restore {
1.124     www      3439:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3440:     my $home='';
                   3441: 
1.168     albertel 3442:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3443: 
1.122     albertel 3444:     if (!$symb) {
                   3445:       unless ($symb=escape(&symbread())) { return ''; }
                   3446:     } else {
1.213     www      3447:       $symb=&escape(&symbclean($symb));
1.122     albertel 3448:     }
1.188     www      3449:     if (!$namespace) { 
1.620     albertel 3450:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3451:           return ''; 
                   3452:        } 
                   3453:     }
1.620     albertel 3454:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3455:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3456:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3457:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3458: 
1.12      www      3459:     my %returnhash=();
1.800     albertel 3460:     foreach my $line (split(/\&/,$answer)) {
                   3461: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3462:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3463:     }
1.75      www      3464:     my $version;
                   3465:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3466:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3467:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3468:        }
1.75      www      3469:     }
1.13      www      3470:     return %returnhash;
1.34      www      3471: }
                   3472: 
                   3473: # ---------------------------------------------------------- Course Description
                   3474: 
                   3475: sub coursedescription {
1.731     albertel 3476:     my ($courseid,$args)=@_;
1.34      www      3477:     $courseid=~s/^\///;
1.49      www      3478:     $courseid=~s/\_/\//g;
1.34      www      3479:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3480:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3481:     my $normalid=$cdomain.'_'.$cnum;
                   3482:     # need to always cache even if we get errors otherwise we keep 
                   3483:     # trying and trying and trying to get the course description.
                   3484:     my %envhash=();
                   3485:     my %returnhash=();
1.731     albertel 3486:     
                   3487:     my $expiretime=600;
                   3488:     if ($env{'request.course.id'} eq $normalid) {
                   3489: 	$expiretime=120;
                   3490:     }
                   3491: 
                   3492:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3493:     if (!$args->{'freshen_cache'}
                   3494: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3495: 	foreach my $key (keys(%env)) {
                   3496: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3497: 	    my ($setting) = $1;
                   3498: 	    $returnhash{$setting} = $env{$key};
                   3499: 	}
                   3500: 	return %returnhash;
                   3501:     }
                   3502: 
                   3503:     # get the data agin
                   3504:     if (!$args->{'one_time'}) {
                   3505: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3506:     }
1.811     albertel 3507: 
1.34      www      3508:     if ($chome ne 'no_host') {
1.302     albertel 3509:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3510:        if (!exists($returnhash{'con_lost'})) {
                   3511:            $returnhash{'home'}= $chome;
                   3512: 	   $returnhash{'domain'} = $cdomain;
                   3513: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3514:            if (!defined($returnhash{'type'})) {
                   3515:                $returnhash{'type'} = 'Course';
                   3516:            }
1.130     albertel 3517:            while (my ($name,$value) = each %returnhash) {
1.53      www      3518:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3519:            }
1.270     www      3520:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3521:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3522: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3523:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3524:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3525:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3526:        }
                   3527:     }
1.731     albertel 3528:     if (!$args->{'one_time'}) {
1.949     raeburn  3529: 	&appenv(\%envhash);
1.731     albertel 3530:     }
1.302     albertel 3531:     return %returnhash;
1.461     www      3532: }
                   3533: 
                   3534: # -------------------------------------------------See if a user is privileged
                   3535: 
                   3536: sub privileged {
                   3537:     my ($username,$domain)=@_;
                   3538:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3539: 			&homeserver($username,$domain));
                   3540:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3541:     my $now=time;
                   3542:     if ($rolesdump ne '') {
1.800     albertel 3543:         foreach my $entry (split(/&/,$rolesdump)) {
                   3544: 	    if ($entry!~/^rolesdef_/) {
                   3545: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3546: 		$area=~s/\_\w\w$//;
                   3547: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3548: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3549: 		    my $active=1;
                   3550: 		    if ($tend) {
                   3551: 			if ($tend<$now) { $active=0; }
                   3552: 		    }
                   3553: 		    if ($tstart) {
                   3554: 			if ($tstart>$now) { $active=0; }
                   3555: 		    }
                   3556: 		    if ($active) { return 1; }
                   3557: 		}
                   3558: 	    }
                   3559: 	}
                   3560:     }
                   3561:     return 0;
1.9       www      3562: }
1.1       albertel 3563: 
1.103     harris41 3564: # -------------------------------------------------------- Get user privileges
1.11      www      3565: 
                   3566: sub rolesinit {
                   3567:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3568:     my %userroles;
1.11      www      3569:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3570:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3571:     my %allroles=();
1.678     raeburn  3572:     my %allgroups=();   
1.11      www      3573:     my $now=time;
1.966     raeburn  3574:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3575:     my $group_privs;
1.11      www      3576: 
                   3577:     if ($rolesdump ne '') {
1.800     albertel 3578:         foreach my $entry (split(/&/,$rolesdump)) {
                   3579: 	  if ($entry!~/^rolesdef_/) {
                   3580:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3581: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3582:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3583: 	    if ($role=~/^cr/) { 
1.807     albertel 3584: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3585: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3586: 		    ($tend,$tstart)=split('_',$trest);
                   3587: 		} else {
                   3588: 		    $trole=$role;
                   3589: 		}
1.678     raeburn  3590:             } elsif ($role =~ m|^gr/|) {
                   3591:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3592:                 ($trole,$group_privs) = split(/\//,$trole);
                   3593:                 $group_privs = &unescape($group_privs);
1.587     albertel 3594: 	    } else {
                   3595: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3596: 	    }
1.743     albertel 3597: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3598: 					 $username);
                   3599: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3600:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3601:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3602:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3603: 		my $spec=$trole.'.'.$area;
                   3604: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3605: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3606:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3607:                 } elsif ($trole eq 'gr') {
                   3608:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3609: 		} else {
1.567     raeburn  3610:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3611: 		}
1.12      www      3612:             }
1.662     raeburn  3613:           }
1.191     harris41 3614:         }
1.743     albertel 3615:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3616:         $userroles{'user.adv'}    = $adv;
                   3617: 	$userroles{'user.author'} = $author;
1.620     albertel 3618:         $env{'user.adv'}=$adv;
1.11      www      3619:     }
1.743     albertel 3620:     return \%userroles;  
1.11      www      3621: }
                   3622: 
1.567     raeburn  3623: sub set_arearole {
                   3624:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3625: # log the associated role with the area
                   3626:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3627:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3628: }
                   3629: 
                   3630: sub custom_roleprivs {
                   3631:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3632:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3633:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3634:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3635:         my ($rdummy,$roledef)=
                   3636:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3637:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3638:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3639:             if (defined($syspriv)) {
                   3640:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3641:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3642:             }
                   3643:             if ($tdomain ne '') {
                   3644:                 if (defined($dompriv)) {
                   3645:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3646:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3647:                 }
                   3648:                 if (($trest ne '') && (defined($coursepriv))) {
                   3649:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3650:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3651:                 }
                   3652:             }
                   3653:         }
                   3654:     }
                   3655: }
                   3656: 
1.678     raeburn  3657: sub group_roleprivs {
                   3658:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3659:     my $access = 1;
                   3660:     my $now = time;
                   3661:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3662:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3663:     if ($access) {
1.811     albertel 3664:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3665:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3666:     }
                   3667: }
1.567     raeburn  3668: 
                   3669: sub standard_roleprivs {
                   3670:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3671:     if (defined($pr{$trole.':s'})) {
                   3672:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3673:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3674:     }
                   3675:     if ($tdomain ne '') {
                   3676:         if (defined($pr{$trole.':d'})) {
                   3677:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3678:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3679:         }
                   3680:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3681:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3682:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3683:         }
                   3684:     }
                   3685: }
                   3686: 
                   3687: sub set_userprivs {
1.678     raeburn  3688:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3689:     my $author=0;
                   3690:     my $adv=0;
1.678     raeburn  3691:     my %grouproles = ();
                   3692:     if (keys(%{$allgroups}) > 0) {
                   3693:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3694:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3695:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3696:                 $trole = $1;
                   3697:                 $area = $2;
1.681     raeburn  3698:                 $sec = $3;
                   3699:                 $extendedarea = $area.$sec;
                   3700:                 if (exists($$allgroups{$area})) {
                   3701:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3702:                         my $spec = $trole.'.'.$extendedarea;
                   3703:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3704:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3705:                     }
                   3706:                 }
                   3707:             }
                   3708:         }
                   3709:     }
1.800     albertel 3710:     foreach my $group (keys(%grouproles)) {
                   3711:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3712:     }
1.800     albertel 3713:     foreach my $role (keys(%{$allroles})) {
                   3714:         my %thesepriv;
1.941     raeburn  3715:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3716:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3717:             if ($item ne '') {
                   3718:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3719:                 if ($restrictions eq '') {
                   3720:                     $thesepriv{$privilege}='F';
                   3721:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3722:                     $thesepriv{$privilege}.=$restrictions;
                   3723:                 }
                   3724:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3725:             }
                   3726:         }
                   3727:         my $thesestr='';
1.800     albertel 3728:         foreach my $priv (keys(%thesepriv)) {
                   3729: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3730: 	}
                   3731:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3732:     }
                   3733:     return ($author,$adv);
                   3734: }
                   3735: 
1.12      www      3736: # --------------------------------------------------------------- get interface
                   3737: 
                   3738: sub get {
1.131     albertel 3739:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3740:    my $items='';
1.800     albertel 3741:    foreach my $item (@$storearr) {
                   3742:        $items.=&escape($item).'&';
1.191     harris41 3743:    }
1.12      www      3744:    $items=~s/\&$//;
1.620     albertel 3745:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3746:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3747:    my $uhome=&homeserver($uname,$udomain);
                   3748: 
1.133     albertel 3749:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3750:    my @pairs=split(/\&/,$rep);
1.273     albertel 3751:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3752:      return @pairs;
                   3753:    }
1.15      www      3754:    my %returnhash=();
1.42      www      3755:    my $i=0;
1.800     albertel 3756:    foreach my $item (@$storearr) {
                   3757:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3758:       $i++;
1.191     harris41 3759:    }
1.15      www      3760:    return %returnhash;
1.27      www      3761: }
                   3762: 
                   3763: # --------------------------------------------------------------- del interface
                   3764: 
                   3765: sub del {
1.133     albertel 3766:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3767:    my $items='';
1.800     albertel 3768:    foreach my $item (@$storearr) {
                   3769:        $items.=&escape($item).'&';
1.191     harris41 3770:    }
1.27      www      3771:    $items=~s/\&$//;
1.620     albertel 3772:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3773:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3774:    my $uhome=&homeserver($uname,$udomain);
                   3775: 
                   3776:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3777: }
                   3778: 
                   3779: # -------------------------------------------------------------- dump interface
                   3780: 
                   3781: sub dump {
1.755     albertel 3782:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3783:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3784:     if (!$uname) { $uname=$env{'user.name'}; }
                   3785:     my $uhome=&homeserver($uname,$udomain);
                   3786:     if ($regexp) {
                   3787: 	$regexp=&escape($regexp);
                   3788:     } else {
                   3789: 	$regexp='.';
                   3790:     }
                   3791:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3792:     my @pairs=split(/\&/,$rep);
                   3793:     my %returnhash=();
                   3794:     foreach my $item (@pairs) {
                   3795: 	my ($key,$value)=split(/=/,$item,2);
                   3796: 	$key = &unescape($key);
                   3797: 	next if ($key =~ /^error: 2 /);
                   3798: 	$returnhash{$key}=&thaw_unescape($value);
                   3799:     }
                   3800:     return %returnhash;
1.407     www      3801: }
                   3802: 
1.717     albertel 3803: # --------------------------------------------------------- dumpstore interface
                   3804: 
                   3805: sub dumpstore {
                   3806:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3807:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3808:    if (!$uname) { $uname=$env{'user.name'}; }
                   3809:    my $uhome=&homeserver($uname,$udomain);
                   3810:    if ($regexp) {
                   3811:        $regexp=&escape($regexp);
                   3812:    } else {
                   3813:        $regexp='.';
                   3814:    }
                   3815:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3816:    my @pairs=split(/\&/,$rep);
                   3817:    my %returnhash=();
                   3818:    foreach my $item (@pairs) {
                   3819:        my ($key,$value)=split(/=/,$item,2);
                   3820:        next if ($key =~ /^error: 2 /);
                   3821:        $returnhash{$key}=&thaw_unescape($value);
                   3822:    }
                   3823:    return %returnhash;
1.717     albertel 3824: }
                   3825: 
1.407     www      3826: # -------------------------------------------------------------- keys interface
                   3827: 
                   3828: sub getkeys {
                   3829:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3830:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3831:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3832:    my $uhome=&homeserver($uname,$udomain);
                   3833:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3834:    my @keyarray=();
1.800     albertel 3835:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3836:       next if ($key =~ /^error: 2 /);
1.800     albertel 3837:       push(@keyarray,&unescape($key));
1.407     www      3838:    }
                   3839:    return @keyarray;
1.318     matthew  3840: }
                   3841: 
1.319     matthew  3842: # --------------------------------------------------------------- currentdump
                   3843: sub currentdump {
1.328     matthew  3844:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3845:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3846:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3847:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3848:    my $uhome = &homeserver($sname,$sdom);
                   3849:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3850:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3851:    #
1.318     matthew  3852:    my %returnhash=();
1.319     matthew  3853:    #
                   3854:    if ($rep eq "unknown_cmd") { 
                   3855:        # an old lond will not know currentdump
                   3856:        # Do a dump and make it look like a currentdump
1.822     albertel 3857:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3858:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3859:        my %hash = @tmp;
                   3860:        @tmp=();
1.424     matthew  3861:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3862:    } else {
                   3863:        my @pairs=split(/\&/,$rep);
1.800     albertel 3864:        foreach my $pair (@pairs) {
                   3865:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3866:            my ($symb,$param) = split(/:/,$key);
                   3867:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3868:                                                         &thaw_unescape($value);
1.319     matthew  3869:        }
1.191     harris41 3870:    }
1.12      www      3871:    return %returnhash;
1.424     matthew  3872: }
                   3873: 
                   3874: sub convert_dump_to_currentdump{
                   3875:     my %hash = %{shift()};
                   3876:     my %returnhash;
                   3877:     # Code ripped from lond, essentially.  The only difference
                   3878:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3879:     # we might run in to problems with parameter names =~ /^v\./
                   3880:     while (my ($key,$value) = each(%hash)) {
                   3881:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3882: 	$symb  = &unescape($symb);
                   3883: 	$param = &unescape($param);
1.424     matthew  3884:         next if ($v eq 'version' || $symb eq 'keys');
                   3885:         next if (exists($returnhash{$symb}) &&
                   3886:                  exists($returnhash{$symb}->{$param}) &&
                   3887:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3888:         $returnhash{$symb}->{$param}=$value;
                   3889:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3890:     }
                   3891:     #
                   3892:     # Remove all of the keys in the hashes which keep track of
                   3893:     # the version of the parameter.
                   3894:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3895:         # use a foreach because we are going to delete from the hash.
                   3896:         foreach my $key (keys(%$param_hash)) {
                   3897:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3898:         }
                   3899:     }
                   3900:     return \%returnhash;
1.12      www      3901: }
                   3902: 
1.627     albertel 3903: # ------------------------------------------------------ critical inc interface
                   3904: 
                   3905: sub cinc {
                   3906:     return &inc(@_,'critical');
                   3907: }
                   3908: 
1.449     matthew  3909: # --------------------------------------------------------------- inc interface
                   3910: 
                   3911: sub inc {
1.627     albertel 3912:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3913:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3914:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3915:     my $uhome=&homeserver($uname,$udomain);
                   3916:     my $items='';
                   3917:     if (! ref($store)) {
                   3918:         # got a single value, so use that instead
                   3919:         $items = &escape($store).'=&';
                   3920:     } elsif (ref($store) eq 'SCALAR') {
                   3921:         $items = &escape($$store).'=&';        
                   3922:     } elsif (ref($store) eq 'ARRAY') {
                   3923:         $items = join('=&',map {&escape($_);} @{$store});
                   3924:     } elsif (ref($store) eq 'HASH') {
                   3925:         while (my($key,$value) = each(%{$store})) {
                   3926:             $items.= &escape($key).'='.&escape($value).'&';
                   3927:         }
                   3928:     }
                   3929:     $items=~s/\&$//;
1.627     albertel 3930:     if ($critical) {
                   3931: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3932:     } else {
                   3933: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3934:     }
1.449     matthew  3935: }
                   3936: 
1.12      www      3937: # --------------------------------------------------------------- put interface
                   3938: 
                   3939: sub put {
1.134     albertel 3940:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3941:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3942:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3943:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3944:    my $items='';
1.800     albertel 3945:    foreach my $item (keys(%$storehash)) {
                   3946:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3947:    }
1.12      www      3948:    $items=~s/\&$//;
1.134     albertel 3949:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3950: }
                   3951: 
1.631     albertel 3952: # ------------------------------------------------------------ newput interface
                   3953: 
                   3954: sub newput {
                   3955:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3956:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3957:    if (!$uname) { $uname=$env{'user.name'}; }
                   3958:    my $uhome=&homeserver($uname,$udomain);
                   3959:    my $items='';
                   3960:    foreach my $key (keys(%$storehash)) {
                   3961:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3962:    }
                   3963:    $items=~s/\&$//;
                   3964:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3965: }
                   3966: 
                   3967: # ---------------------------------------------------------  putstore interface
                   3968: 
1.524     raeburn  3969: sub putstore {
1.715     albertel 3970:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3971:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3972:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3973:    my $uhome=&homeserver($uname,$udomain);
                   3974:    my $items='';
1.715     albertel 3975:    foreach my $key (keys(%$storehash)) {
                   3976:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3977:    }
1.715     albertel 3978:    $items=~s/\&$//;
1.716     albertel 3979:    my $esc_symb=&escape($symb);
                   3980:    my $esc_v=&escape($version);
1.715     albertel 3981:    my $reply =
1.716     albertel 3982:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3983: 	      $uhome);
                   3984:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3985:        # gfall back to way things use to be done
1.715     albertel 3986:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3987: 			    $uname);
1.524     raeburn  3988:    }
1.715     albertel 3989:    return $reply;
                   3990: }
                   3991: 
                   3992: sub old_putstore {
1.716     albertel 3993:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3994:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3995:     if (!$uname) { $uname=$env{'user.name'}; }
                   3996:     my $uhome=&homeserver($uname,$udomain);
                   3997:     my %newstorehash;
1.800     albertel 3998:     foreach my $item (keys(%$storehash)) {
                   3999: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4000: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4001:     }
                   4002:     my $items='';
                   4003:     my %allitems = ();
1.800     albertel 4004:     foreach my $item (keys(%newstorehash)) {
                   4005: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4006: 	    my $key = $1.':keys:'.$2;
                   4007: 	    $allitems{$key} .= $3.':';
                   4008: 	}
1.800     albertel 4009: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4010:     }
1.800     albertel 4011:     foreach my $item (keys(%allitems)) {
                   4012: 	$allitems{$item} =~ s/\:$//;
                   4013: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4014:     }
                   4015:     $items=~s/\&$//;
                   4016:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4017: }
                   4018: 
1.47      www      4019: # ------------------------------------------------------ critical put interface
                   4020: 
                   4021: sub cput {
1.134     albertel 4022:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4023:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4024:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4025:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4026:    my $items='';
1.800     albertel 4027:    foreach my $item (keys(%$storehash)) {
                   4028:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4029:    }
1.47      www      4030:    $items=~s/\&$//;
1.134     albertel 4031:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4032: }
                   4033: 
                   4034: # -------------------------------------------------------------- eget interface
                   4035: 
                   4036: sub eget {
1.133     albertel 4037:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4038:    my $items='';
1.800     albertel 4039:    foreach my $item (@$storearr) {
                   4040:        $items.=&escape($item).'&';
1.191     harris41 4041:    }
1.12      www      4042:    $items=~s/\&$//;
1.620     albertel 4043:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4044:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4045:    my $uhome=&homeserver($uname,$udomain);
                   4046:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4047:    my @pairs=split(/\&/,$rep);
                   4048:    my %returnhash=();
1.42      www      4049:    my $i=0;
1.800     albertel 4050:    foreach my $item (@$storearr) {
                   4051:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4052:       $i++;
1.191     harris41 4053:    }
1.12      www      4054:    return %returnhash;
                   4055: }
                   4056: 
1.667     albertel 4057: # ------------------------------------------------------------ tmpput interface
                   4058: sub tmpput {
1.802     raeburn  4059:     my ($storehash,$server,$context)=@_;
1.667     albertel 4060:     my $items='';
1.800     albertel 4061:     foreach my $item (keys(%$storehash)) {
                   4062: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4063:     }
                   4064:     $items=~s/\&$//;
1.802     raeburn  4065:     if (defined($context)) {
                   4066:         $items .= ':'.&escape($context);
                   4067:     }
1.667     albertel 4068:     return &reply("tmpput:$items",$server);
                   4069: }
                   4070: 
                   4071: # ------------------------------------------------------------ tmpget interface
                   4072: sub tmpget {
1.688     albertel 4073:     my ($token,$server)=@_;
                   4074:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4075:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4076:     my %returnhash;
                   4077:     foreach my $item (split(/\&/,$rep)) {
                   4078: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4079:         next if ($key =~ /^error: 2 /);
1.667     albertel 4080: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4081:     }
                   4082:     return %returnhash;
                   4083: }
                   4084: 
1.688     albertel 4085: # ------------------------------------------------------------ tmpget interface
                   4086: sub tmpdel {
                   4087:     my ($token,$server)=@_;
                   4088:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4089:     return &reply("tmpdel:$token",$server);
                   4090: }
                   4091: 
1.765     albertel 4092: # -------------------------------------------------- portfolio access checking
                   4093: 
                   4094: sub portfolio_access {
1.766     albertel 4095:     my ($requrl) = @_;
1.765     albertel 4096:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4097:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4098:     if ($result) {
                   4099:         my %setters;
                   4100:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4101:             my ($startblock,$endblock) =
                   4102:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4103:             if ($startblock && $endblock) {
                   4104:                 return 'B';
                   4105:             }
                   4106:         } else {
                   4107:             my ($startblock,$endblock) =
                   4108:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4109:             if ($startblock && $endblock) {
                   4110:                 return 'B';
                   4111:             }
                   4112:         }
                   4113:     }
1.765     albertel 4114:     if ($result eq 'ok') {
1.766     albertel 4115:        return 'F';
1.765     albertel 4116:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4117:        return 'A';
1.765     albertel 4118:     }
1.766     albertel 4119:     return '';
1.765     albertel 4120: }
                   4121: 
                   4122: sub get_portfolio_access {
1.767     albertel 4123:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4124: 
                   4125:     if (!ref($access_hash)) {
                   4126: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4127: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4128: 						   $file_name);
                   4129: 	$access_hash = $access_controls{$file_name};
                   4130:     }
                   4131: 
1.765     albertel 4132:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4133:     my $now = time;
                   4134:     if (ref($access_hash) eq 'HASH') {
                   4135:         foreach my $key (keys(%{$access_hash})) {
                   4136:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4137:             if ($start > $now) {
                   4138:                 next;
                   4139:             }
                   4140:             if ($end && $end<$now) {
                   4141:                 next;
                   4142:             }
                   4143:             if ($scope eq 'public') {
                   4144:                 $public = $key;
                   4145:                 last;
                   4146:             } elsif ($scope eq 'guest') {
                   4147:                 $guest = $key;
                   4148:             } elsif ($scope eq 'domains') {
                   4149:                 push(@domains,$key);
                   4150:             } elsif ($scope eq 'users') {
                   4151:                 push(@users,$key);
                   4152:             } elsif ($scope eq 'course') {
                   4153:                 push(@courses,$key);
                   4154:             } elsif ($scope eq 'group') {
                   4155:                 push(@groups,$key);
                   4156:             }
                   4157:         }
                   4158:         if ($public) {
                   4159:             return 'ok';
                   4160:         }
                   4161:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4162:             if ($guest) {
                   4163:                 return $guest;
                   4164:             }
                   4165:         } else {
                   4166:             if (@domains > 0) {
                   4167:                 foreach my $domkey (@domains) {
                   4168:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4169:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4170:                             return 'ok';
                   4171:                         }
                   4172:                     }
                   4173:                 }
                   4174:             }
                   4175:             if (@users > 0) {
                   4176:                 foreach my $userkey (@users) {
1.865     raeburn  4177:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4178:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4179:                             if (ref($item) eq 'HASH') {
                   4180:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4181:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4182:                                     return 'ok';
                   4183:                                 }
                   4184:                             }
                   4185:                         }
                   4186:                     } 
1.765     albertel 4187:                 }
                   4188:             }
                   4189:             my %roleshash;
                   4190:             my @courses_and_groups = @courses;
                   4191:             push(@courses_and_groups,@groups); 
                   4192:             if (@courses_and_groups > 0) {
                   4193:                 my (%allgroups,%allroles); 
                   4194:                 my ($start,$end,$role,$sec,$group);
                   4195:                 foreach my $envkey (%env) {
1.811     albertel 4196:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4197:                         my $cid = $2.'_'.$3; 
                   4198:                         if ($1 eq 'gr') {
                   4199:                             $group = $4;
                   4200:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4201:                         } else {
                   4202:                             if ($4 eq '') {
                   4203:                                 $sec = 'none';
                   4204:                             } else {
                   4205:                                 $sec = $4;
                   4206:                             }
                   4207:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4208:                         }
1.811     albertel 4209:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4210:                         my $cid = $2.'_'.$3;
                   4211:                         if ($4 eq '') {
                   4212:                             $sec = 'none';
                   4213:                         } else {
                   4214:                             $sec = $4;
                   4215:                         }
                   4216:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4217:                     }
                   4218:                 }
                   4219:                 if (keys(%allroles) == 0) {
                   4220:                     return;
                   4221:                 }
                   4222:                 foreach my $key (@courses_and_groups) {
                   4223:                     my %content = %{$$access_hash{$key}};
                   4224:                     my $cnum = $content{'number'};
                   4225:                     my $cdom = $content{'domain'};
                   4226:                     my $cid = $cdom.'_'.$cnum;
                   4227:                     if (!exists($allroles{$cid})) {
                   4228:                         next;
                   4229:                     }    
                   4230:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4231:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4232:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4233:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4234:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4235:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4236:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4237:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4238:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4239:                                         if (grep/^all$/,@sections) {
                   4240:                                             return 'ok';
                   4241:                                         } else {
                   4242:                                             if (grep/^$sec$/,@sections) {
                   4243:                                                 return 'ok';
                   4244:                                             }
                   4245:                                         }
                   4246:                                     }
                   4247:                                 }
                   4248:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4249:                                     if (grep/^none$/,@groups) {
                   4250:                                         return 'ok';
                   4251:                                     }
                   4252:                                 } else {
                   4253:                                     if (grep/^all$/,@groups) {
                   4254:                                         return 'ok';
                   4255:                                     } 
                   4256:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4257:                                         if (grep/^$group$/,@groups) {
                   4258:                                             return 'ok';
                   4259:                                         }
                   4260:                                     }
                   4261:                                 } 
                   4262:                             }
                   4263:                         }
                   4264:                     }
                   4265:                 }
                   4266:             }
                   4267:             if ($guest) {
                   4268:                 return $guest;
                   4269:             }
                   4270:         }
                   4271:     }
                   4272:     return;
                   4273: }
                   4274: 
                   4275: sub course_group_datechecker {
                   4276:     my ($dates,$now,$status) = @_;
                   4277:     my ($start,$end) = split(/\./,$dates);
                   4278:     if (!$start && !$end) {
                   4279:         return 'ok';
                   4280:     }
                   4281:     if (grep/^active$/,@{$status}) {
                   4282:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4283:             return 'ok';
                   4284:         }
                   4285:     }
                   4286:     if (grep/^previous$/,@{$status}) {
                   4287:         if ($end > $now ) {
                   4288:             return 'ok';
                   4289:         }
                   4290:     }
                   4291:     if (grep/^future$/,@{$status}) {
                   4292:         if ($start > $now) {
                   4293:             return 'ok';
                   4294:         }
                   4295:     }
                   4296:     return; 
                   4297: }
                   4298: 
                   4299: sub parse_portfolio_url {
                   4300:     my ($url) = @_;
                   4301: 
                   4302:     my ($type,$udom,$unum,$group,$file_name);
                   4303:     
1.823     albertel 4304:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4305: 	$type = 1;
                   4306:         $udom = $1;
                   4307:         $unum = $2;
                   4308:         $file_name = $3;
1.823     albertel 4309:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4310: 	$type = 2;
                   4311:         $udom = $1;
                   4312:         $unum = $2;
                   4313:         $group = $3;
                   4314:         $file_name = $3.'/'.$4;
                   4315:     }
                   4316:     if (wantarray) {
                   4317: 	return ($type,$udom,$unum,$file_name,$group);
                   4318:     }
                   4319:     return $type;
                   4320: }
                   4321: 
                   4322: sub is_portfolio_url {
                   4323:     my ($url) = @_;
                   4324:     return scalar(&parse_portfolio_url($url));
                   4325: }
                   4326: 
1.798     raeburn  4327: sub is_portfolio_file {
                   4328:     my ($file) = @_;
1.820     raeburn  4329:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4330:         return 1;
                   4331:     }
                   4332:     return;
                   4333: }
                   4334: 
                   4335: 
1.341     www      4336: # ---------------------------------------------- Custom access rule evaluation
                   4337: 
                   4338: sub customaccess {
                   4339:     my ($priv,$uri)=@_;
1.807     albertel 4340:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4341:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4342:     $udom = &LONCAPA::clean_domain($udom);
                   4343:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4344:     my $access=0;
1.800     albertel 4345:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4346: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4347: 	if ($type eq 'user') {
                   4348: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4349: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4350: 		if ($tdom) {
                   4351: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4352: 		}
1.896     albertel 4353: 		if ($tuname) {
                   4354: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4355: 		}
                   4356: 		$access=($effect eq 'allow');
                   4357: 		last;
                   4358: 	    }
                   4359: 	} else {
                   4360: 	    if ($role) {
                   4361: 		if ($role ne $urole) { next; }
                   4362: 	    }
                   4363: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4364: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4365: 		if ($tdom) {
                   4366: 		    if ($tdom ne $udom) { next; }
                   4367: 		}
                   4368: 		if ($tcrs) {
                   4369: 		    if ($tcrs ne $ucrs) { next; }
                   4370: 		}
                   4371: 		if ($tsec) {
                   4372: 		    if ($tsec ne $usec) { next; }
                   4373: 		}
                   4374: 		$access=($effect eq 'allow');
                   4375: 		last;
                   4376: 	    }
                   4377: 	    if ($realm eq '' && $role eq '') {
                   4378: 		$access=($effect eq 'allow');
                   4379: 	    }
1.402     bowersj2 4380: 	}
1.341     www      4381:     }
                   4382:     return $access;
                   4383: }
                   4384: 
1.103     harris41 4385: # ------------------------------------------------- Check for a user privilege
1.12      www      4386: 
                   4387: sub allowed {
1.810     raeburn  4388:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4389:     my $ver_orguri=$uri;
1.439     www      4390:     $uri=&deversion($uri);
1.152     www      4391:     my $orguri=$uri;
1.52      www      4392:     $uri=&declutter($uri);
1.809     raeburn  4393: 
1.810     raeburn  4394:     if ($priv eq 'evb') {
                   4395: # Evade communication block restrictions for specified role in a course
                   4396:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4397:             return $1;
                   4398:         } else {
                   4399:             return;
                   4400:         }
                   4401:     }
                   4402: 
1.620     albertel 4403:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4404: # Free bre access to adm and meta resources
1.775     albertel 4405:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4406: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4407: 	&& ($priv eq 'bre')) {
1.14      www      4408: 	return 'F';
1.159     www      4409:     }
                   4410: 
1.545     banghart 4411: # Free bre access to user's own portfolio contents
1.714     raeburn  4412:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4413:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4414: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4415:         my %setters;
                   4416:         my ($startblock,$endblock) = 
                   4417:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4418:         if ($startblock && $endblock) {
                   4419:             return 'B';
                   4420:         } else {
                   4421:             return 'F';
                   4422:         }
1.545     banghart 4423:     }
                   4424: 
1.762     raeburn  4425: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4426:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4427:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4428:         if (exists($env{'request.course.id'})) {
                   4429:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4430:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4431:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4432:                 my $courseprivid=$env{'request.course.id'};
                   4433:                 $courseprivid=~s/\_/\//;
                   4434:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4435:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4436:                     return $1; 
1.762     raeburn  4437:                 } else {
                   4438:                     if ($env{'request.course.sec'}) {
                   4439:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4440:                     }
                   4441:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4442:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4443:                         return $2;
                   4444:                     }
1.714     raeburn  4445:                 }
                   4446:             }
                   4447:         }
                   4448:     }
                   4449: 
1.159     www      4450: # Free bre to public access
                   4451: 
                   4452:     if ($priv eq 'bre') {
1.238     www      4453:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4454: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4455:            return 'F'; 
                   4456:         }
1.238     www      4457:         if ($copyright eq 'priv') {
                   4458:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4459: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4460: 		return '';
                   4461:             }
                   4462:         }
                   4463:         if ($copyright eq 'domain') {
                   4464:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4465: 	    unless (($env{'user.domain'} eq $1) ||
                   4466:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4467: 		return '';
                   4468:             }
1.262     matthew  4469:         }
1.620     albertel 4470:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4471:             # Library role, so allow browsing of resources in this domain.
                   4472:             return 'F';
1.238     www      4473:         }
1.341     www      4474:         if ($copyright eq 'custom') {
                   4475: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4476:         }
1.14      www      4477:     }
1.264     matthew  4478:     # Domain coordinator is trying to create a course
1.620     albertel 4479:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4480:         # uri is the requested domain in this case.
                   4481:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4482:         # a role of dc for the domain in question.
1.620     albertel 4483:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4484:     }
1.29      www      4485: 
1.52      www      4486:     my $thisallowed='';
                   4487:     my $statecond=0;
                   4488:     my $courseprivid='';
                   4489: 
                   4490: # Course
                   4491: 
1.620     albertel 4492:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4493:        $thisallowed.=$1;
                   4494:     }
1.29      www      4495: 
1.52      www      4496: # Domain
                   4497: 
1.620     albertel 4498:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4499:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4500:        $thisallowed.=$1;
                   4501:     }
1.52      www      4502: 
                   4503: # Course: uri itself is a course
1.66      www      4504:     my $courseuri=$uri;
                   4505:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4506:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4507: 
1.620     albertel 4508:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4509:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4510:        $thisallowed.=$1;
                   4511:     }
1.29      www      4512: 
1.665     albertel 4513: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4514: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4515:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4516: 	$thisallowed='';
1.671     raeburn  4517:         my ($match)=&is_on_map($uri);
                   4518:         if ($match) {
                   4519:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4520:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4521:                 $thisallowed.=$1;
                   4522:             }
                   4523:         } else {
1.705     albertel 4524:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4525:             if ($refuri) {
                   4526:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4527:                     $thisallowed='F';
1.671     raeburn  4528:                 } else {
                   4529:                     $refuri=&declutter($refuri);
                   4530:                     my ($match) = &is_on_map($refuri);
                   4531:                     if ($match) {
                   4532:                         $thisallowed='F';
                   4533:                     }
1.669     raeburn  4534:                 }
1.671     raeburn  4535:             }
                   4536:         }
1.314     www      4537:     }
1.492     albertel 4538: 
1.766     albertel 4539:     if ($priv eq 'bre'
                   4540: 	&& $thisallowed ne 'F' 
                   4541: 	&& $thisallowed ne '2'
                   4542: 	&& &is_portfolio_url($uri)) {
                   4543: 	$thisallowed = &portfolio_access($uri);
                   4544:     }
                   4545:     
1.52      www      4546: # Full access at system, domain or course-wide level? Exit.
1.29      www      4547:     if ($thisallowed=~/F/) {
                   4548: 	return 'F';
                   4549:     }
                   4550: 
1.52      www      4551: # If this is generating or modifying users, exit with special codes
1.29      www      4552: 
1.643     www      4553:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4554: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4555: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4556: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4557: 	    unless ($auname) { return $thisallowed; }
                   4558: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4559: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4560: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4561: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4562: 	}
1.52      www      4563: 	return $thisallowed;
                   4564:     }
                   4565: #
1.103     harris41 4566: # Gathered so far: system, domain and course wide privileges
1.52      www      4567: #
                   4568: # Course: See if uri or referer is an individual resource that is part of 
                   4569: # the course
                   4570: 
1.620     albertel 4571:     if ($env{'request.course.id'}) {
1.232     www      4572: 
1.620     albertel 4573:        $courseprivid=$env{'request.course.id'};
                   4574:        if ($env{'request.course.sec'}) {
                   4575:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4576:        }
                   4577:        $courseprivid=~s/\_/\//;
                   4578:        my $checkreferer=1;
1.232     www      4579:        my ($match,$cond)=&is_on_map($uri);
                   4580:        if ($match) {
                   4581:            $statecond=$cond;
1.620     albertel 4582:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4583:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4584:                $thisallowed.=$1;
                   4585:                $checkreferer=0;
                   4586:            }
1.29      www      4587:        }
1.83      www      4588:        
1.148     www      4589:        if ($checkreferer) {
1.620     albertel 4590: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4591:             unless ($refuri) {
1.800     albertel 4592:                 foreach my $key (keys(%env)) {
                   4593: 		    if ($key=~/^httpref\..*\*/) {
                   4594: 			my $pattern=$key;
1.156     www      4595:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4596:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4597:                         $pattern=~s/\//\\\//g;
1.152     www      4598:                         if ($orguri=~/$pattern/) {
1.800     albertel 4599: 			    $refuri=$env{$key};
1.148     www      4600:                         }
                   4601:                     }
1.191     harris41 4602:                 }
1.148     www      4603:             }
1.232     www      4604: 
1.148     www      4605:          if ($refuri) { 
1.152     www      4606: 	  $refuri=&declutter($refuri);
1.232     www      4607:           my ($match,$cond)=&is_on_map($refuri);
                   4608:             if ($match) {
                   4609:               my $refstatecond=$cond;
1.620     albertel 4610:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4611:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4612:                   $thisallowed.=$1;
1.53      www      4613:                   $uri=$refuri;
                   4614:                   $statecond=$refstatecond;
1.52      www      4615:               }
                   4616:           }
1.148     www      4617:         }
1.29      www      4618:        }
1.52      www      4619:    }
1.29      www      4620: 
1.52      www      4621: #
1.103     harris41 4622: # Gathered now: all privileges that could apply, and condition number
1.52      www      4623: # 
                   4624: #
                   4625: # Full or no access?
                   4626: #
1.29      www      4627: 
1.52      www      4628:     if ($thisallowed=~/F/) {
                   4629: 	return 'F';
                   4630:     }
1.29      www      4631: 
1.52      www      4632:     unless ($thisallowed) {
                   4633:         return '';
                   4634:     }
1.29      www      4635: 
1.52      www      4636: # Restrictions exist, deal with them
                   4637: #
                   4638: #   C:according to course preferences
                   4639: #   R:according to resource settings
                   4640: #   L:unless locked
                   4641: #   X:according to user session state
                   4642: #
                   4643: 
                   4644: # Possibly locked functionality, check all courses
1.54      www      4645: # Locks might take effect only after 10 minutes cache expiration for other
                   4646: # courses, and 2 minutes for current course
1.52      www      4647: 
                   4648:     my $envkey;
                   4649:     if ($thisallowed=~/L/) {
1.620     albertel 4650:         foreach $envkey (keys %env) {
1.54      www      4651:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4652:                my $courseid=$2;
                   4653:                my $roleid=$1.'.'.$2;
1.92      www      4654:                $courseid=~s/^\///;
1.54      www      4655:                my $expiretime=600;
1.620     albertel 4656:                if ($env{'request.role'} eq $roleid) {
1.54      www      4657: 		  $expiretime=120;
                   4658:                }
                   4659: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4660:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4661:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4662: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4663:                }
1.620     albertel 4664:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4665:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4666: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4667:                        &log($env{'user.domain'},$env{'user.name'},
                   4668:                             $env{'user.home'},
1.57      www      4669:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4670:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4671:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4672: 		       return '';
                   4673:                    }
                   4674:                }
1.620     albertel 4675:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4676:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4677: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4678:                        &log($env{'user.domain'},$env{'user.name'},
                   4679:                             $env{'user.home'},
1.57      www      4680:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4681:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4682:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4683: 		       return '';
                   4684:                    }
                   4685:                }
                   4686: 	   }
1.29      www      4687:        }
1.52      www      4688:     }
                   4689:    
                   4690: #
                   4691: # Rest of the restrictions depend on selected course
                   4692: #
                   4693: 
1.620     albertel 4694:     unless ($env{'request.course.id'}) {
1.766     albertel 4695: 	if ($thisallowed eq 'A') {
                   4696: 	    return 'A';
1.814     raeburn  4697:         } elsif ($thisallowed eq 'B') {
                   4698:             return 'B';
1.766     albertel 4699: 	} else {
                   4700: 	    return '1';
                   4701: 	}
1.52      www      4702:     }
1.29      www      4703: 
1.52      www      4704: #
                   4705: # Now user is definitely in a course
                   4706: #
1.53      www      4707: 
                   4708: 
                   4709: # Course preferences
                   4710: 
                   4711:    if ($thisallowed=~/C/) {
1.620     albertel 4712:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4713:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4714:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4715: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4716: 	   if ($priv ne 'pch') { 
                   4717: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4718: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4719: 			$env{'request.course.id'});
                   4720: 	   }
1.237     www      4721:            return '';
                   4722:        }
                   4723: 
1.620     albertel 4724:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4725: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4726: 	   if ($priv ne 'pch') { 
                   4727: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4728: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4729: 			$env{'request.course.id'});
                   4730: 	   }
1.54      www      4731:            return '';
                   4732:        }
1.53      www      4733:    }
                   4734: 
                   4735: # Resource preferences
                   4736: 
                   4737:    if ($thisallowed=~/R/) {
1.620     albertel 4738:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4739:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4740: 	   if ($priv ne 'pch') { 
                   4741: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4742: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4743: 	   }
                   4744: 	   return '';
1.54      www      4745:        }
1.53      www      4746:    }
1.30      www      4747: 
1.246     www      4748: # Restricted by state or randomout?
1.30      www      4749: 
1.52      www      4750:    if ($thisallowed=~/X/) {
1.620     albertel 4751:       if ($env{'acc.randomout'}) {
1.579     albertel 4752: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4753:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4754:             return ''; 
                   4755:          }
1.247     www      4756:       }
                   4757:       if (&condval($statecond)) {
1.52      www      4758: 	 return '2';
                   4759:       } else {
                   4760:          return '';
                   4761:       }
                   4762:    }
1.30      www      4763: 
1.766     albertel 4764:     if ($thisallowed eq 'A') {
                   4765: 	return 'A';
1.814     raeburn  4766:     } elsif ($thisallowed eq 'B') {
                   4767:         return 'B';
1.766     albertel 4768:     }
1.52      www      4769:    return 'F';
1.232     www      4770: }
                   4771: 
1.710     albertel 4772: sub split_uri_for_cond {
                   4773:     my $uri=&deversion(&declutter(shift));
                   4774:     my @uriparts=split(/\//,$uri);
                   4775:     my $filename=pop(@uriparts);
                   4776:     my $pathname=join('/',@uriparts);
                   4777:     return ($pathname,$filename);
                   4778: }
1.232     www      4779: # --------------------------------------------------- Is a resource on the map?
                   4780: 
                   4781: sub is_on_map {
1.710     albertel 4782:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4783:     #Trying to find the conditional for the file
1.620     albertel 4784:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4785: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4786:     if ($match) {
1.289     bowersj2 4787: 	return (1,$1);
                   4788:     } else {
1.434     www      4789: 	return (0,0);
1.289     bowersj2 4790:     }
1.12      www      4791: }
                   4792: 
1.427     www      4793: # --------------------------------------------------------- Get symb from alias
                   4794: 
                   4795: sub get_symb_from_alias {
                   4796:     my $symb=shift;
                   4797:     my ($map,$resid,$url)=&decode_symb($symb);
                   4798: # Already is a symb
                   4799:     if ($url) { return $symb; }
                   4800: # Must be an alias
                   4801:     my $aliassymb='';
                   4802:     my %bighash;
1.620     albertel 4803:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4804:                             &GDBM_READER(),0640)) {
                   4805:         my $rid=$bighash{'mapalias_'.$symb};
                   4806: 	if ($rid) {
                   4807: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4808: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4809: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4810: 	}
                   4811:         untie %bighash;
                   4812:     }
                   4813:     return $aliassymb;
                   4814: }
                   4815: 
1.12      www      4816: # ----------------------------------------------------------------- Define Role
                   4817: 
                   4818: sub definerole {
                   4819:   if (allowed('mcr','/')) {
                   4820:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4821:     foreach my $role (split(':',$sysrole)) {
                   4822: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4823:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4824:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4825: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4826:                return "refused:s:$crole&$cqual"; 
                   4827:             }
                   4828:         }
1.191     harris41 4829:     }
1.800     albertel 4830:     foreach my $role (split(':',$domrole)) {
                   4831: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4832:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4833:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4834: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4835:                return "refused:d:$crole&$cqual"; 
                   4836:             }
                   4837:         }
1.191     harris41 4838:     }
1.800     albertel 4839:     foreach my $role (split(':',$courole)) {
                   4840: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4841:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4842:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4843: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4844:                return "refused:c:$crole&$cqual"; 
                   4845:             }
                   4846:         }
1.191     harris41 4847:     }
1.620     albertel 4848:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4849:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4850: 	        "rolesdef_$rolename=".
                   4851:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4852:     return reply($command,$env{'user.home'});
1.12      www      4853:   } else {
                   4854:     return 'refused';
                   4855:   }
1.105     harris41 4856: }
                   4857: 
                   4858: # ---------------- Make a metadata query against the network of library servers
                   4859: 
                   4860: sub metadata_query {
1.244     matthew  4861:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4862:     my %rhash;
1.845     albertel 4863:     my %libserv = &all_library();
1.244     matthew  4864:     my @server_list = (defined($server_array) ? @$server_array
                   4865:                                               : keys(%libserv) );
                   4866:     for my $server (@server_list) {
1.118     harris41 4867: 	unless ($custom or $customshow) {
                   4868: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4869: 	    $rhash{$server}=$reply;
                   4870: 	}
                   4871: 	else {
                   4872: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4873: 			     &escape($custom).':'.&escape($customshow),
                   4874: 			     $server);
                   4875: 	    $rhash{$server}=$reply;
                   4876: 	}
1.112     harris41 4877:     }
1.118     harris41 4878:     return \%rhash;
1.240     www      4879: }
                   4880: 
                   4881: # ----------------------------------------- Send log queries and wait for reply
                   4882: 
                   4883: sub log_query {
                   4884:     my ($uname,$udom,$query,%filters)=@_;
                   4885:     my $uhome=&homeserver($uname,$udom);
                   4886:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4887:     my $uhost=&hostname($uhome);
1.800     albertel 4888:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4889:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4890:                        $uhome);
1.479     albertel 4891:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4892:     return get_query_reply($queryid);
                   4893: }
                   4894: 
1.818     raeburn  4895: # -------------------------- Update MySQL table for portfolio file
                   4896: 
                   4897: sub update_portfolio_table {
1.821     raeburn  4898:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4899:     my $homeserver = &homeserver($uname,$udom);
                   4900:     my $queryid=
1.821     raeburn  4901:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4902:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4903:     my $reply = &get_query_reply($queryid);
                   4904:     return $reply;
                   4905: }
                   4906: 
1.899     raeburn  4907: # -------------------------- Update MySQL allusers table
                   4908: 
                   4909: sub update_allusers_table {
                   4910:     my ($uname,$udom,$names) = @_;
                   4911:     my $homeserver = &homeserver($uname,$udom);
                   4912:     my $queryid=
                   4913:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4914:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4915:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4916:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4917:                'generation='.&escape($names->{'generation'}).'%%'.
                   4918:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4919:                'id='.&escape($names->{'id'}),$homeserver);
                   4920:     my $reply = &get_query_reply($queryid);
                   4921:     return $reply;
                   4922: }
                   4923: 
1.508     raeburn  4924: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4925: 
                   4926: sub fetch_enrollment_query {
1.511     raeburn  4927:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4928:     my $homeserver;
1.547     raeburn  4929:     my $maxtries = 1;
1.508     raeburn  4930:     if ($context eq 'automated') {
                   4931:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4932:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4933:     } else {
                   4934:         $homeserver = &homeserver($cnum,$dom);
                   4935:     }
1.838     albertel 4936:     my $host=&hostname($homeserver);
1.506     raeburn  4937:     my $cmd = '';
1.800     albertel 4938:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4939:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4940:     }
                   4941:     $cmd =~ s/%%$//;
                   4942:     $cmd = &escape($cmd);
                   4943:     my $query = 'fetchenrollment';
1.620     albertel 4944:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4945:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4946:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4947:         return 'error: '.$queryid;
                   4948:     }
1.506     raeburn  4949:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4950:     my $tries = 1;
                   4951:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4952:         $reply = &get_query_reply($queryid);
                   4953:         $tries ++;
                   4954:     }
1.526     raeburn  4955:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4956:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4957:     } else {
1.901     albertel 4958:         my @responses = split(/:/,$reply);
1.515     raeburn  4959:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4960:             foreach my $line (@responses) {
                   4961:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4962:                 $$replyref{$key} = $value;
                   4963:             }
                   4964:         } else {
1.506     raeburn  4965:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4966:             foreach my $line (@responses) {
                   4967:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4968:                 $$replyref{$key} = $value;
                   4969:                 if ($value > 0) {
1.800     albertel 4970:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4971:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4972:                         my $destname = $pathname.'/'.$filename;
                   4973:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4974:                         if ($xml_classlist =~ /^error/) {
                   4975:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4976:                         } else {
1.506     raeburn  4977:                             if ( open(FILE,">$destname") ) {
                   4978:                                 print FILE &unescape($xml_classlist);
                   4979:                                 close(FILE);
1.526     raeburn  4980:                             } else {
                   4981:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4982:                             }
                   4983:                         }
                   4984:                     }
                   4985:                 }
                   4986:             }
                   4987:         }
                   4988:         return 'ok';
                   4989:     }
                   4990:     return 'error';
                   4991: }
                   4992: 
1.242     www      4993: sub get_query_reply {
                   4994:     my $queryid=shift;
1.240     www      4995:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4996:     my $reply='';
                   4997:     for (1..100) {
                   4998: 	sleep 2;
                   4999:         if (-e $replyfile.'.end') {
1.448     albertel 5000: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5001: 		$reply = join('',<$fh>);
                   5002: 		close($fh);
1.240     www      5003: 	   } else { return 'error: reply_file_error'; }
1.242     www      5004:            return &unescape($reply);
                   5005: 	}
1.240     www      5006:     }
1.242     www      5007:     return 'timeout:'.$queryid;
1.240     www      5008: }
                   5009: 
                   5010: sub courselog_query {
1.241     www      5011: #
                   5012: # possible filters:
                   5013: # url: url or symb
                   5014: # username
                   5015: # domain
                   5016: # action: view, submit, grade
                   5017: # start: timestamp
                   5018: # end: timestamp
                   5019: #
1.240     www      5020:     my (%filters)=@_;
1.620     albertel 5021:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5022:     if ($filters{'url'}) {
                   5023: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5024:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5025:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5026:     }
1.620     albertel 5027:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5028:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5029:     return &log_query($cname,$cdom,'courselog',%filters);
                   5030: }
                   5031: 
                   5032: sub userlog_query {
1.858     raeburn  5033: #
                   5034: # possible filters:
                   5035: # action: log check role
                   5036: # start: timestamp
                   5037: # end: timestamp
                   5038: #
1.240     www      5039:     my ($uname,$udom,%filters)=@_;
                   5040:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5041: }
                   5042: 
1.506     raeburn  5043: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5044: 
                   5045: sub auto_run {
1.508     raeburn  5046:     my ($cnum,$cdom) = @_;
1.876     raeburn  5047:     my $response = 0;
                   5048:     my $settings;
                   5049:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5050:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5051:         $settings = $domconfig{'autoenroll'};
                   5052:         if ($settings->{'run'} eq '1') {
                   5053:             $response = 1;
                   5054:         }
                   5055:     } else {
1.934     raeburn  5056:         my $homeserver;
                   5057:         if (&is_course($cdom,$cnum)) {
                   5058:             $homeserver = &homeserver($cnum,$cdom);
                   5059:         } else {
                   5060:             $homeserver = &domain($cdom,'primary');
                   5061:         }
                   5062:         if ($homeserver ne 'no_host') {
                   5063:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5064:         }
1.876     raeburn  5065:     }
1.506     raeburn  5066:     return $response;
                   5067: }
1.776     albertel 5068: 
1.506     raeburn  5069: sub auto_get_sections {
1.508     raeburn  5070:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5071:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5072:     my @secs = ();
1.511     raeburn  5073:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5074:     unless ($response eq 'refused') {
1.901     albertel 5075:         @secs = split(/:/,$response);
1.506     raeburn  5076:     }
                   5077:     return @secs;
                   5078: }
1.776     albertel 5079: 
1.506     raeburn  5080: sub auto_new_course {
1.508     raeburn  5081:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5082:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5083:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5084:     return $response;
                   5085: }
1.776     albertel 5086: 
1.506     raeburn  5087: sub auto_validate_courseID {
1.508     raeburn  5088:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5089:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5090:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5091:     return $response;
                   5092: }
1.776     albertel 5093: 
1.506     raeburn  5094: sub auto_create_password {
1.873     raeburn  5095:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5096:     my ($homeserver,$response);
1.506     raeburn  5097:     my $create_passwd = 0;
                   5098:     my $authchk = '';
1.873     raeburn  5099:     if ($udom =~ /^$match_domain$/) {
                   5100:         $homeserver = &domain($udom,'primary');
                   5101:     }
                   5102:     if ($homeserver eq '') {
                   5103:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5104:             $homeserver = &homeserver($cnum,$cdom);
                   5105:         }
                   5106:     }
                   5107:     if ($homeserver eq '') {
                   5108:         $authchk = 'nodomain';
1.506     raeburn  5109:     } else {
1.873     raeburn  5110:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5111:         if ($response eq 'refused') {
                   5112:             $authchk = 'refused';
                   5113:         } else {
1.901     albertel 5114:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5115:         }
1.506     raeburn  5116:     }
                   5117:     return ($authparam,$create_passwd,$authchk);
                   5118: }
                   5119: 
1.706     raeburn  5120: sub auto_photo_permission {
                   5121:     my ($cnum,$cdom,$students) = @_;
                   5122:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5123:     my ($outcome,$perm_reqd,$conditions) = 
                   5124: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5125:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5126: 	return (undef,undef);
                   5127:     }
1.706     raeburn  5128:     return ($outcome,$perm_reqd,$conditions);
                   5129: }
                   5130: 
                   5131: sub auto_checkphotos {
                   5132:     my ($uname,$udom,$pid) = @_;
                   5133:     my $homeserver = &homeserver($uname,$udom);
                   5134:     my ($result,$resulttype);
                   5135:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5136: 				   &escape($uname).':'.&escape($pid),
                   5137: 				   $homeserver));
1.709     albertel 5138:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5139: 	return (undef,undef);
                   5140:     }
1.706     raeburn  5141:     if ($outcome) {
                   5142:         ($result,$resulttype) = split(/:/,$outcome);
                   5143:     } 
                   5144:     return ($result,$resulttype);
                   5145: }
                   5146: 
                   5147: sub auto_photochoice {
                   5148:     my ($cnum,$cdom) = @_;
                   5149:     my $homeserver = &homeserver($cnum,$cdom);
                   5150:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5151: 						       &escape($cdom),
                   5152: 						       $homeserver)));
1.709     albertel 5153:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5154: 	return (undef,undef);
                   5155:     }
1.706     raeburn  5156:     return ($update,$comment);
                   5157: }
                   5158: 
                   5159: sub auto_photoupdate {
                   5160:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5161:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5162:     my $host=&hostname($homeserver);
1.706     raeburn  5163:     my $cmd = '';
                   5164:     my $maxtries = 1;
1.800     albertel 5165:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5166:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5167:     }
                   5168:     $cmd =~ s/%%$//;
                   5169:     $cmd = &escape($cmd);
                   5170:     my $query = 'institutionalphotos';
                   5171:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5172:     unless ($queryid=~/^\Q$host\E\_/) {
                   5173:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5174:         return 'error: '.$queryid;
                   5175:     }
                   5176:     my $reply = &get_query_reply($queryid);
                   5177:     my $tries = 1;
                   5178:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5179:         $reply = &get_query_reply($queryid);
                   5180:         $tries ++;
                   5181:     }
                   5182:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5183:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5184:     } else {
                   5185:         my @responses = split(/:/,$reply);
                   5186:         my $outcome = shift(@responses); 
                   5187:         foreach my $item (@responses) {
                   5188:             my ($key,$value) = split(/=/,$item);
                   5189:             $$photo{$key} = $value;
                   5190:         }
                   5191:         return $outcome;
                   5192:     }
                   5193:     return 'error';
                   5194: }
                   5195: 
1.521     raeburn  5196: sub auto_instcode_format {
1.793     albertel 5197:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5198: 	$cat_order) = @_;
1.521     raeburn  5199:     my $courses = '';
1.772     raeburn  5200:     my @homeservers;
1.521     raeburn  5201:     if ($caller eq 'global') {
1.841     albertel 5202: 	my %servers = &get_servers($codedom,'library');
                   5203: 	foreach my $tryserver (keys(%servers)) {
                   5204: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5205: 		push(@homeservers,$tryserver);
                   5206: 	    }
1.584     raeburn  5207:         }
1.521     raeburn  5208:     } else {
1.772     raeburn  5209:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5210:     }
1.793     albertel 5211:     foreach my $code (keys(%{$instcodes})) {
                   5212:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5213:     }
                   5214:     chop($courses);
1.772     raeburn  5215:     my $ok_response = 0;
                   5216:     my $response;
                   5217:     while (@homeservers > 0 && $ok_response == 0) {
                   5218:         my $server = shift(@homeservers); 
                   5219:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5220:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5221:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5222: 		split(/:/,$response);
1.772     raeburn  5223:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5224:             push(@{$codetitles},&str2array($codetitles_str));
                   5225:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5226:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5227:             $ok_response = 1;
                   5228:         }
                   5229:     }
                   5230:     if ($ok_response) {
1.521     raeburn  5231:         return 'ok';
1.772     raeburn  5232:     } else {
                   5233:         return $response;
1.521     raeburn  5234:     }
                   5235: }
                   5236: 
1.792     raeburn  5237: sub auto_instcode_defaults {
                   5238:     my ($domain,$returnhash,$code_order) = @_;
                   5239:     my @homeservers;
1.841     albertel 5240: 
                   5241:     my %servers = &get_servers($domain,'library');
                   5242:     foreach my $tryserver (keys(%servers)) {
                   5243: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5244: 	    push(@homeservers,$tryserver);
                   5245: 	}
1.792     raeburn  5246:     }
1.841     albertel 5247: 
1.792     raeburn  5248:     my $response;
1.841     albertel 5249:     foreach my $server (@homeservers) {
1.792     raeburn  5250:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5251:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5252: 	
                   5253: 	foreach my $pair (split(/\&/,$response)) {
                   5254: 	    my ($name,$value)=split(/\=/,$pair);
                   5255: 	    if ($name eq 'code_order') {
                   5256: 		@{$code_order} = split(/\&/,&unescape($value));
                   5257: 	    } else {
                   5258: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5259: 	    }
                   5260: 	}
                   5261: 	return 'ok';
1.792     raeburn  5262:     }
1.841     albertel 5263: 
                   5264:     return $response;
1.792     raeburn  5265: } 
                   5266: 
1.777     albertel 5267: sub auto_validate_class_sec {
1.918     raeburn  5268:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5269:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5270:     my $ownerlist;
                   5271:     if (ref($owners) eq 'ARRAY') {
                   5272:         $ownerlist = join(',',@{$owners});
                   5273:     } else {
                   5274:         $ownerlist = $owners;
                   5275:     }
1.773     raeburn  5276:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5277:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5278:     return $response;
                   5279: }
                   5280: 
1.679     raeburn  5281: # ------------------------------------------------------- Course Group routines
                   5282: 
                   5283: sub get_coursegroups {
1.809     raeburn  5284:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5285:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5286: }
                   5287: 
1.679     raeburn  5288: sub modify_coursegroup {
                   5289:     my ($cdom,$cnum,$groupsettings) = @_;
                   5290:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5291: }
                   5292: 
1.809     raeburn  5293: sub toggle_coursegroup_status {
                   5294:     my ($cdom,$cnum,$group,$action) = @_;
                   5295:     my ($from_namespace,$to_namespace);
                   5296:     if ($action eq 'delete') {
                   5297:         $from_namespace = 'coursegroups';
                   5298:         $to_namespace = 'deleted_groups';
                   5299:     } else {
                   5300:         $from_namespace = 'deleted_groups';
                   5301:         $to_namespace = 'coursegroups';
                   5302:     }
                   5303:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5304:     if (my $tmp = &error(%curr_group)) {
                   5305:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5306:         return ('read error',$tmp);
                   5307:     } else {
                   5308:         my %savedsettings = %curr_group; 
1.809     raeburn  5309:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5310:         my $deloutcome;
                   5311:         if ($result eq 'ok') {
1.809     raeburn  5312:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5313:         } else {
                   5314:             return ('write error',$result);
                   5315:         }
                   5316:         if ($deloutcome eq 'ok') {
                   5317:             return 'ok';
                   5318:         } else {
                   5319:             return ('delete error',$deloutcome);
                   5320:         }
                   5321:     }
                   5322: }
                   5323: 
1.679     raeburn  5324: sub modify_group_roles {
1.957     raeburn  5325:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5326:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5327:     my $role = 'gr/'.&escape($userprivs);
                   5328:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5329:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5330:     if ($result eq 'ok') {
                   5331:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5332:     }
1.679     raeburn  5333:     return $result;
                   5334: }
                   5335: 
                   5336: sub modify_coursegroup_membership {
                   5337:     my ($cdom,$cnum,$membership) = @_;
                   5338:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5339:     return $result;
                   5340: }
                   5341: 
1.682     raeburn  5342: sub get_active_groups {
                   5343:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5344:     my $now = time;
                   5345:     my %groups = ();
                   5346:     foreach my $key (keys(%env)) {
1.811     albertel 5347:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5348:             my ($start,$end) = split(/\./,$env{$key});
                   5349:             if (($end!=0) && ($end<$now)) { next; }
                   5350:             if (($start!=0) && ($start>$now)) { next; }
                   5351:             if ($1 eq $cdom && $2 eq $cnum) {
                   5352:                 $groups{$3} = $env{$key} ;
                   5353:             }
                   5354:         }
                   5355:     }
                   5356:     return %groups;
                   5357: }
                   5358: 
1.683     raeburn  5359: sub get_group_membership {
                   5360:     my ($cdom,$cnum,$group) = @_;
                   5361:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5362: }
                   5363: 
                   5364: sub get_users_groups {
                   5365:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5366:     my @usersgroups;
1.683     raeburn  5367:     my $cachetime=1800;
                   5368: 
                   5369:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5370:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5371:     if (defined($cached)) {
1.734     albertel 5372:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5373:     } else {  
                   5374:         $grouplist = '';
1.816     raeburn  5375:         my $courseurl = &courseid_to_courseurl($courseid);
                   5376:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5377:         my $access_end = $env{'course.'.$courseid.
                   5378:                               '.default_enrollment_end_date'};
                   5379:         my $now = time;
                   5380:         foreach my $key (keys(%roleshash)) {
                   5381:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5382:                 my $group = $1;
                   5383:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5384:                     my $start = $2;
                   5385:                     my $end = $1;
                   5386:                     if ($start == -1) { next; } # deleted from group
                   5387:                     if (($start!=0) && ($start>$now)) { next; }
                   5388:                     if (($end!=0) && ($end<$now)) {
                   5389:                         if ($access_end && $access_end < $now) {
                   5390:                             if ($access_end - $end < 86400) {
                   5391:                                 push(@usersgroups,$group);
1.733     raeburn  5392:                             }
                   5393:                         }
1.817     raeburn  5394:                         next;
1.733     raeburn  5395:                     }
1.817     raeburn  5396:                     push(@usersgroups,$group);
1.683     raeburn  5397:                 }
                   5398:             }
                   5399:         }
1.817     raeburn  5400:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5401:         $grouplist = join(':',@usersgroups);
                   5402:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5403:     }
1.733     raeburn  5404:     return @usersgroups;
1.683     raeburn  5405: }
                   5406: 
                   5407: sub devalidate_getgroups_cache {
                   5408:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5409:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5410: 
1.683     raeburn  5411:     my $hashid="$udom:$uname:$courseid";
                   5412:     &devalidate_cache_new('getgroups',$hashid);
                   5413: }
                   5414: 
1.12      www      5415: # ------------------------------------------------------------------ Plain Text
                   5416: 
                   5417: sub plaintext {
1.742     raeburn  5418:     my ($short,$type,$cid) = @_;
1.758     albertel 5419:     if ($short =~ /^cr/) {
                   5420: 	return (split('/',$short))[-1];
                   5421:     }
1.742     raeburn  5422:     if (!defined($cid)) {
                   5423:         $cid = $env{'request.course.id'};
                   5424:     }
                   5425:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5426:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5427:                                           '.plaintext'});
                   5428:     }
                   5429:     my %rolenames = (
                   5430:                       Course => 'std',
                   5431:                       Group => 'alt1',
                   5432:                     );
                   5433:     if (defined($type) && 
                   5434:          defined($rolenames{$type}) && 
                   5435:          defined($prp{$short}{$rolenames{$type}})) {
                   5436:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5437:     } else {
                   5438:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5439:     }
1.12      www      5440: }
                   5441: 
                   5442: # ----------------------------------------------------------------- Assign Role
                   5443: 
                   5444: sub assignrole {
1.957     raeburn  5445:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5446:         $context)=@_;
1.21      www      5447:     my $mrole;
                   5448:     if ($role =~ /^cr\//) {
1.393     www      5449:         my $cwosec=$url;
1.811     albertel 5450:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5451: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5452:            &logthis('Refused custom assignrole: '.
                   5453:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5454: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5455:            return 'refused'; 
                   5456:         }
1.21      www      5457:         $mrole='cr';
1.678     raeburn  5458:     } elsif ($role =~ /^gr\//) {
                   5459:         my $cwogrp=$url;
1.811     albertel 5460:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5461:         unless (&allowed('mdg',$cwogrp)) {
                   5462:             &logthis('Refused group assignrole: '.
                   5463:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5464:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5465:             return 'refused';
                   5466:         }
                   5467:         $mrole='gr';
1.21      www      5468:     } else {
1.82      www      5469:         my $cwosec=$url;
1.811     albertel 5470:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5471:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5472:             my $refused;
                   5473:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5474:                 if (!(&allowed('c'.$role,$url))) {
                   5475:                     $refused = 1;
                   5476:                 }
                   5477:             } else {
                   5478:                 $refused = 1;
                   5479:             }
1.947     raeburn  5480:             if ($refused) {
                   5481:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5482:                     $refused = '';
                   5483:                 } else {
                   5484:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5485:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5486: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5487:                     return 'refused';
                   5488:                 }
1.932     raeburn  5489:             }
1.104     www      5490:         }
1.21      www      5491:         $mrole=$role;
                   5492:     }
1.620     albertel 5493:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5494:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5495:     if ($end) { $command.='_'.$end; }
1.21      www      5496:     if ($start) {
                   5497: 	if ($end) { 
1.81      www      5498:            $command.='_'.$start; 
1.21      www      5499:         } else {
1.81      www      5500:            $command.='_0_'.$start;
1.21      www      5501:         }
                   5502:     }
1.739     raeburn  5503:     my $origstart = $start;
                   5504:     my $origend = $end;
1.957     raeburn  5505:     my $delflag;
1.357     www      5506: # actually delete
                   5507:     if ($deleteflag) {
1.373     www      5508: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5509: # modify command to delete the role
1.620     albertel 5510:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5511:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5512: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5513: # set start and finish to negative values for userrolelog
                   5514:            $start=-1;
                   5515:            $end=-1;
1.957     raeburn  5516:            $delflag = 1;
1.357     www      5517:         }
                   5518:     }
                   5519: # send command
1.349     www      5520:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5521: # log new user role if status is ok
1.349     www      5522:     if ($answer eq 'ok') {
1.663     raeburn  5523: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5524: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5525:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5526:         unless ($role =~ /^gr/) {
                   5527:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5528:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5529:         }
1.349     www      5530:     }
                   5531:     return $answer;
1.169     harris41 5532: }
                   5533: 
                   5534: # -------------------------------------------------- Modify user authentication
1.197     www      5535: # Overrides without validation
                   5536: 
1.169     harris41 5537: sub modifyuserauth {
                   5538:     my ($udom,$uname,$umode,$upass)=@_;
                   5539:     my $uhome=&homeserver($uname,$udom);
1.197     www      5540:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5541:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5542:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5543:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5544:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5545: 		     &escape($upass),$uhome);
1.620     albertel 5546:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5547:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5548:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5549:     &log($udom,,$uname,$uhome,
1.620     albertel 5550:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5551:                                      $env{'user.name'}.', '.$umode.
1.197     www      5552:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5553:     unless ($reply eq 'ok') {
1.197     www      5554:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5555: 	return 'error: '.$reply;
                   5556:     }   
1.170     harris41 5557:     return 'ok';
1.80      www      5558: }
                   5559: 
1.81      www      5560: # --------------------------------------------------------------- Modify a user
1.80      www      5561: 
1.81      www      5562: sub modifyuser {
1.206     matthew  5563:     my ($udom,    $uname, $uid,
                   5564:         $umode,   $upass, $first,
                   5565:         $middle,  $last,  $gene,
1.963     raeburn  5566:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5567:     $udom= &LONCAPA::clean_domain($udom);
                   5568:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5569:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5570:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5571: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5572:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5573:                                      ' desiredhome not specified'). 
1.620     albertel 5574:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5575:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5576:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5577: # ----------------------------------------------------------------- Create User
1.406     albertel 5578:     if (($uhome eq 'no_host') && 
                   5579: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5580:         my $unhome='';
1.844     albertel 5581:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5582:             $unhome = $desiredhome;
1.620     albertel 5583: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5584: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5585:         } else { # load balancing routine for determining $unhome
1.81      www      5586:             my $loadm=10000000;
1.841     albertel 5587: 	    my %servers = &get_servers($udom,'library');
                   5588: 	    foreach my $tryserver (keys(%servers)) {
                   5589: 		my $answer=reply('load',$tryserver);
                   5590: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5591: 		    $loadm=$answer;
                   5592: 		    $unhome=$tryserver;
                   5593: 		}
1.80      www      5594: 	    }
                   5595:         }
                   5596:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5597: 	    return 'error: unable to find a home server for '.$uname.
                   5598:                    ' in domain '.$udom;
1.80      www      5599:         }
                   5600:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5601:                          &escape($upass),$unhome);
                   5602: 	unless ($reply eq 'ok') {
                   5603:             return 'error: '.$reply;
                   5604:         }   
1.230     stredwic 5605:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5606:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5607: 	    return 'error: unable verify users home machine.';
1.80      www      5608:         }
1.209     matthew  5609:     }   # End of creation of new user
1.80      www      5610: # ---------------------------------------------------------------------- Add ID
                   5611:     if ($uid) {
                   5612:        $uid=~tr/A-Z/a-z/;
                   5613:        my %uidhash=&idrget($udom,$uname);
1.196     www      5614:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5615:          && (!$forceid)) {
1.80      www      5616: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5617: 	      return 'error: user id "'.$uid.'" does not match '.
                   5618:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5619:           }
                   5620:        } else {
                   5621: 	  &idput($udom,($uname => $uid));
                   5622:        }
                   5623:     }
                   5624: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5625:     my @tmp=&get('environment',
1.899     raeburn  5626: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5627:                     'permanentemail','inststatus'],
1.134     albertel 5628: 		   $udom,$uname);
1.313     matthew  5629:     my %names;
                   5630:     if ($tmp[0] =~ m/^error:.*/) { 
                   5631:         %names=(); 
                   5632:     } else {
                   5633:         %names = @tmp;
                   5634:     }
1.388     www      5635: #
                   5636: # Make sure to not trash student environment if instructor does not bother
                   5637: # to supply name and email information
                   5638: #
                   5639:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5640:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5641:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5642:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5643:     if ($email) {
                   5644:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5645:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5646:     }
1.899     raeburn  5647:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5648:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5649:     my $reply = &put('environment', \%names, $udom,$uname);
                   5650:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5651:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5652:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5653:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5654:                  $umode.', '.$first.', '.$middle.', '.
                   5655: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5656:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5657:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5658:     } else {
                   5659:         $logmsg .= ' during self creation';
                   5660:     }
                   5661:     &logthis($logmsg);
1.134     albertel 5662:     return 'ok';
1.80      www      5663: }
                   5664: 
1.81      www      5665: # -------------------------------------------------------------- Modify student
1.80      www      5666: 
1.81      www      5667: sub modifystudent {
                   5668:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5669:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5670:         $selfenroll,$context)=@_;
1.455     albertel 5671:     if (!$cid) {
1.620     albertel 5672: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5673: 	    return 'not_in_class';
                   5674: 	}
1.80      www      5675:     }
                   5676: # --------------------------------------------------------------- Make the user
1.81      www      5677:     my $reply=&modifyuser
1.209     matthew  5678: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5679:          $desiredhome,$email);
1.80      www      5680:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5681:     # This will cause &modify_student_enrollment to get the uid from the
                   5682:     # students environment
                   5683:     $uid = undef if (!$forceid);
1.455     albertel 5684:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5685: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5686:     return $reply;
                   5687: }
                   5688: 
                   5689: sub modify_student_enrollment {
1.957     raeburn  5690:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5691:     my ($cdom,$cnum,$chome);
                   5692:     if (!$cid) {
1.620     albertel 5693: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5694: 	    return 'not_in_class';
                   5695: 	}
1.620     albertel 5696: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5697: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5698:     } else {
                   5699: 	($cdom,$cnum)=split(/_/,$cid);
                   5700:     }
1.620     albertel 5701:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5702:     if (!$chome) {
1.457     raeburn  5703: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5704:     }
1.455     albertel 5705:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5706:     # Make sure the user exists
1.81      www      5707:     my $uhome=&homeserver($uname,$udom);
                   5708:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5709: 	return 'error: no such user';
                   5710:     }
1.297     matthew  5711:     # Get student data if we were not given enough information
                   5712:     if (!defined($first)  || $first  eq '' || 
                   5713:         !defined($last)   || $last   eq '' || 
                   5714:         !defined($uid)    || $uid    eq '' || 
                   5715:         !defined($middle) || $middle eq '' || 
                   5716:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5717:         # They did not supply us with enough data to enroll the student, so
                   5718:         # we need to pick up more information.
1.297     matthew  5719:         my %tmp = &get('environment',
1.294     matthew  5720:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5721:                        ,$udom,$uname);
                   5722: 
1.800     albertel 5723:         #foreach my $key (keys(%tmp)) {
                   5724:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5725:         #}
1.294     matthew  5726:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5727:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5728:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5729:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5730:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5731:     }
1.556     albertel 5732:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5733:     my $reply=cput('classlist',
                   5734: 		   {"$uname:$udom" => 
1.515     raeburn  5735: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5736: 		   $cdom,$cnum);
1.81      www      5737:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5738: 	return 'error: '.$reply;
1.652     albertel 5739:     } else {
                   5740: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5741:     }
1.297     matthew  5742:     # Add student role to user
1.83      www      5743:     my $uurl='/'.$cid;
1.81      www      5744:     $uurl=~s/\_/\//g;
                   5745:     if ($usec) {
                   5746: 	$uurl.='/'.$usec;
                   5747:     }
1.957     raeburn  5748:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5749: }
                   5750: 
1.556     albertel 5751: sub format_name {
                   5752:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5753:     my $name;
                   5754:     if ($first ne 'lastname') {
                   5755: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5756:     } else {
                   5757: 	if ($lastname=~/\S/) {
                   5758: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5759: 	    $name=~s/\s+,/,/;
                   5760: 	} else {
                   5761: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5762: 	}
                   5763:     }
                   5764:     $name=~s/^\s+//;
                   5765:     $name=~s/\s+$//;
                   5766:     $name=~s/\s+/ /g;
                   5767:     return $name;
                   5768: }
                   5769: 
1.84      www      5770: # ------------------------------------------------- Write to course preferences
                   5771: 
                   5772: sub writecoursepref {
                   5773:     my ($courseid,%prefs)=@_;
                   5774:     $courseid=~s/^\///;
                   5775:     $courseid=~s/\_/\//g;
                   5776:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5777:     my $chome=homeserver($cnum,$cdomain);
                   5778:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5779: 	return 'error: no such course';
                   5780:     }
                   5781:     my $cstring='';
1.800     albertel 5782:     foreach my $pref (keys(%prefs)) {
                   5783: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5784:     }
1.84      www      5785:     $cstring=~s/\&$//;
                   5786:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5787: }
                   5788: 
                   5789: # ---------------------------------------------------------- Make/modify course
                   5790: 
                   5791: sub createcourse {
1.741     raeburn  5792:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5793:         $course_owner,$crstype)=@_;
1.84      www      5794:     $url=&declutter($url);
                   5795:     my $cid='';
1.264     matthew  5796:     unless (&allowed('ccc',$udom)) {
1.84      www      5797:         return 'refused';
                   5798:     }
                   5799: # ------------------------------------------------------------------- Create ID
1.674     www      5800:    my $uname=int(1+rand(9)).
                   5801:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5802:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5803:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5804: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5805:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5806:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5807:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5808:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5809:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5810:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5811:            return 'error: unable to generate unique course-ID';
                   5812:        } 
                   5813:    }
1.264     matthew  5814: # ------------------------------------------------ Check supplied server name
1.620     albertel 5815:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5816:     if (! &is_library($course_server)) {
1.264     matthew  5817:         return 'error:bad server name '.$course_server;
                   5818:     }
1.84      www      5819: # ------------------------------------------------------------- Make the course
                   5820:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5821:                       $course_server);
1.84      www      5822:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5823:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5824:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5825: 	return 'error: no such course';
                   5826:     }
1.271     www      5827: # ----------------------------------------------------------------- Course made
1.516     raeburn  5828: # log existence
1.918     raeburn  5829:     my $newcourse = {
                   5830:                     $udom.'_'.$uname => {
1.921     raeburn  5831:                                      description => $description,
                   5832:                                      inst_code   => $inst_code,
                   5833:                                      owner       => $course_owner,
                   5834:                                      type        => $crstype,
1.918     raeburn  5835:                                                 },
                   5836:                     };
1.921     raeburn  5837:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5838: # set toplevel url
1.271     www      5839:     my $topurl=$url;
                   5840:     unless ($nonstandard) {
                   5841: # ------------------------------------------ For standard courses, make top url
                   5842:         my $mapurl=&clutter($url);
1.278     www      5843:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5844:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5845: <map>
                   5846: <resource id="1" type="start"></resource>
                   5847: <resource id="2" src="$mapurl"></resource>
                   5848: <resource id="3" type="finish"></resource>
                   5849: <link index="1" from="1" to="2"></link>
                   5850: <link index="2" from="2" to="3"></link>
                   5851: </map>
                   5852: ENDINITMAP
                   5853:         $topurl=&declutter(
1.638     albertel 5854:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5855:                           );
                   5856:     }
                   5857: # ----------------------------------------------------------- Write preferences
1.84      www      5858:     &writecoursepref($udom.'_'.$uname,
                   5859:                      ('description' => $description,
1.271     www      5860:                       'url'         => $topurl));
1.84      www      5861:     return '/'.$udom.'/'.$uname;
                   5862: }
                   5863: 
1.813     albertel 5864: sub is_course {
                   5865:     my ($cdom,$cnum) = @_;
                   5866:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5867: 				undef,'.');
1.813     albertel 5868:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5869:         return 1;
                   5870:     }
                   5871:     return 0;
                   5872: }
                   5873: 
1.21      www      5874: # ---------------------------------------------------------- Assign Custom Role
                   5875: 
                   5876: sub assigncustomrole {
1.957     raeburn  5877:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5878:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  5879:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      5880: }
                   5881: 
                   5882: # ----------------------------------------------------------------- Revoke Role
                   5883: 
                   5884: sub revokerole {
1.957     raeburn  5885:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5886:     my $now=time;
1.965     raeburn  5887:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      5888: }
                   5889: 
                   5890: # ---------------------------------------------------------- Revoke Custom Role
                   5891: 
                   5892: sub revokecustomrole {
1.957     raeburn  5893:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      5894:     my $now=time;
1.357     www      5895:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  5896:            $deleteflag,$selfenroll,$context);
1.17      www      5897: }
                   5898: 
1.533     banghart 5899: # ------------------------------------------------------------ Disk usage
1.535     albertel 5900: sub diskusage {
1.955     raeburn  5901:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   5902:     $directorypath =~ s/\/$//;
                   5903:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   5904:                        .&escape($getpropath).':'.&escape($uname).':'
                   5905:                        .&escape($udom),homeserver($uname,$udom));
                   5906:     if ($listing eq 'unknown_cmd') {
                   5907:         if ($getpropath) {
                   5908:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   5909:         }
                   5910:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   5911:     }
1.514     albertel 5912:     return $listing;
1.512     banghart 5913: }
                   5914: 
1.566     banghart 5915: sub is_locked {
                   5916:     my ($file_name, $domain, $user) = @_;
                   5917:     my @check;
                   5918:     my $is_locked;
                   5919:     push @check, $file_name;
1.613     albertel 5920:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5921: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5922:     my ($tmp)=keys(%locked);
                   5923:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5924:     
1.566     banghart 5925:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5926:         $is_locked = 'false';
                   5927:         foreach my $entry (@{$locked{$file_name}}) {
                   5928:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5929:                $is_locked = 'true';
                   5930:                last;
1.745     raeburn  5931:            }
                   5932:        }
1.566     banghart 5933:     } else {
                   5934:         $is_locked = 'false';
                   5935:     }
                   5936: }
                   5937: 
1.759     albertel 5938: sub declutter_portfile {
                   5939:     my ($file) = @_;
1.833     albertel 5940:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5941:     return $file;
                   5942: }
                   5943: 
1.559     banghart 5944: # ------------------------------------------------------------- Mark as Read Only
                   5945: 
                   5946: sub mark_as_readonly {
                   5947:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5948:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5949:     my ($tmp)=keys(%current_permissions);
                   5950:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5951:     foreach my $file (@{$files}) {
1.759     albertel 5952: 	$file = &declutter_portfile($file);
1.561     banghart 5953:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5954:     }
1.613     albertel 5955:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5956:     return;
                   5957: }
                   5958: 
1.572     banghart 5959: # ------------------------------------------------------------Save Selected Files
                   5960: 
                   5961: sub save_selected_files {
                   5962:     my ($user, $path, @files) = @_;
                   5963:     my $filename = $user."savedfiles";
1.573     banghart 5964:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5965:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5966:     foreach my $file (@files) {
1.620     albertel 5967:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5968:     }
                   5969:     foreach my $file (@other_files) {
1.574     banghart 5970:         print (OUT $file."\n");
1.572     banghart 5971:     }
1.574     banghart 5972:     close (OUT);
1.572     banghart 5973:     return 'ok';
                   5974: }
                   5975: 
1.574     banghart 5976: sub clear_selected_files {
                   5977:     my ($user) = @_;
                   5978:     my $filename = $user."savedfiles";
                   5979:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5980:     print (OUT undef);
                   5981:     close (OUT);
                   5982:     return ("ok");    
                   5983: }
                   5984: 
1.572     banghart 5985: sub files_in_path {
                   5986:     my ($user, $path) = @_;
                   5987:     my $filename = $user."savedfiles";
                   5988:     my %return_files;
1.574     banghart 5989:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5990:     while (my $line_in = <IN>) {
1.574     banghart 5991:         chomp ($line_in);
                   5992:         my @paths_and_file = split (m!/!, $line_in);
                   5993:         my $file_part = pop (@paths_and_file);
                   5994:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5995:         $path_part.='/';
                   5996:         my $path_and_file = $path_part.$file_part;
                   5997:         if ($path_part eq $path) {
                   5998:             $return_files{$file_part}= 'selected';
                   5999:         }
                   6000:     }
1.574     banghart 6001:     close (IN);
                   6002:     return (\%return_files);
1.572     banghart 6003: }
                   6004: 
                   6005: # called in portfolio select mode, to show files selected NOT in current directory
                   6006: sub files_not_in_path {
                   6007:     my ($user, $path) = @_;
                   6008:     my $filename = $user."savedfiles";
                   6009:     my @return_files;
                   6010:     my $path_part;
1.800     albertel 6011:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6012:     while (my $line = <IN>) {
1.572     banghart 6013:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6014:         my @paths_and_file = split(m|/|, $line);
                   6015:         my $file_part = pop(@paths_and_file);
                   6016:         chomp($file_part);
                   6017:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6018:         $path_part .= '/';
                   6019:         my $path_and_file = $path_part.$file_part;
                   6020:         if ($path_part ne $path) {
1.800     albertel 6021:             push(@return_files, ($path_and_file));
1.572     banghart 6022:         }
                   6023:     }
1.800     albertel 6024:     close(OUT);
1.574     banghart 6025:     return (@return_files);
1.572     banghart 6026: }
                   6027: 
1.745     raeburn  6028: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6029: 
1.745     raeburn  6030: sub get_portfile_permissions {
                   6031:     my ($domain,$user) = @_;
1.613     albertel 6032:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6033:     my ($tmp)=keys(%current_permissions);
                   6034:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6035:     return \%current_permissions;
                   6036: }
                   6037: 
                   6038: #---------------------------------------------Get portfolio file access controls
                   6039: 
1.749     raeburn  6040: sub get_access_controls {
1.745     raeburn  6041:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6042:     my %access;
                   6043:     my $real_file = $file;
                   6044:     $file =~ s/\.meta$//;
1.745     raeburn  6045:     if (defined($file)) {
1.749     raeburn  6046:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6047:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6048:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6049:             }
                   6050:         }
1.745     raeburn  6051:     } else {
1.749     raeburn  6052:         foreach my $key (keys(%{$current_permissions})) {
                   6053:             if ($key =~ /\0accesscontrol$/) {
                   6054:                 if (defined($group)) {
                   6055:                     if ($key !~ m-^\Q$group\E/-) {
                   6056:                         next;
                   6057:                     }
                   6058:                 }
                   6059:                 my ($fullpath) = split(/\0/,$key);
                   6060:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6061:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6062:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6063:                     }
                   6064:                 }
                   6065:             }
                   6066:         }
                   6067:     }
                   6068:     return %access;
                   6069: }
                   6070: 
                   6071: sub modify_access_controls {
                   6072:     my ($file_name,$changes,$domain,$user)=@_;
                   6073:     my ($outcome,$deloutcome);
                   6074:     my %store_permissions;
                   6075:     my %new_values;
                   6076:     my %new_control;
                   6077:     my %translation;
                   6078:     my @deletions = ();
                   6079:     my $now = time;
                   6080:     if (exists($$changes{'activate'})) {
                   6081:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6082:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6083:             my $numnew = scalar(@newitems);
                   6084:             for (my $i=0; $i<$numnew; $i++) {
                   6085:                 my $newkey = $newitems[$i];
                   6086:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6087:                 if ($newkey =~ /^\d+:/) { 
                   6088:                     $newkey =~ s/^(\d+)/$newid/;
                   6089:                     $translation{$1} = $newid;
                   6090:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6091:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6092:                     $translation{$1} = $newid;
                   6093:                 }
1.749     raeburn  6094:                 $new_values{$file_name."\0".$newkey} = 
                   6095:                                           $$changes{'activate'}{$newitems[$i]};
                   6096:                 $new_control{$newkey} = $now;
                   6097:             }
                   6098:         }
                   6099:     }
                   6100:     my %todelete;
                   6101:     my %changed_items;
                   6102:     foreach my $action ('delete','update') {
                   6103:         if (exists($$changes{$action})) {
                   6104:             if (ref($$changes{$action}) eq 'HASH') {
                   6105:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6106:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6107:                     if ($action eq 'delete') { 
                   6108:                         $todelete{$itemnum} = 1;
                   6109:                     } else {
                   6110:                         $changed_items{$itemnum} = $key;
                   6111:                     }
                   6112:                 }
1.745     raeburn  6113:             }
                   6114:         }
1.749     raeburn  6115:     }
                   6116:     # get lock on access controls for file.
                   6117:     my $lockhash = {
                   6118:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6119:                                                        ':'.$env{'user.domain'},
                   6120:                    }; 
                   6121:     my $tries = 0;
                   6122:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6123:    
                   6124:     while (($gotlock ne 'ok') && $tries <3) {
                   6125:         $tries ++;
                   6126:         sleep 1;
                   6127:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6128:     }
                   6129:     if ($gotlock eq 'ok') {
                   6130:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6131:         my ($tmp)=keys(%curr_permissions);
                   6132:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6133:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6134:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6135:             if (ref($curr_controls) eq 'HASH') {
                   6136:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6137:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6138:                     if (defined($todelete{$itemnum})) {
                   6139:                         push(@deletions,$file_name."\0".$control_item);
                   6140:                     } else {
                   6141:                         if (defined($changed_items{$itemnum})) {
                   6142:                             $new_control{$changed_items{$itemnum}} = $now;
                   6143:                             push(@deletions,$file_name."\0".$control_item);
                   6144:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6145:                         } else {
                   6146:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6147:                         }
                   6148:                     }
1.745     raeburn  6149:                 }
                   6150:             }
                   6151:         }
1.749     raeburn  6152:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6153:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6154:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6155:         #  remove lock
                   6156:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6157:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6158:         my ($file,$group);
                   6159:         if (&is_course($domain,$user)) {
                   6160:             ($group,$file) = split(/\//,$file_name,2);
                   6161:         } else {
                   6162:             $file = $file_name;
                   6163:         }
                   6164:         my $sqlresult =
                   6165:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6166:                                     $group);
1.749     raeburn  6167:     } else {
                   6168:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6169:     }
1.749     raeburn  6170:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6171: }
                   6172: 
1.827     raeburn  6173: sub make_public_indefinitely {
                   6174:     my ($requrl) = @_;
                   6175:     my $now = time;
                   6176:     my $action = 'activate';
                   6177:     my $aclnum = 0;
                   6178:     if (&is_portfolio_url($requrl)) {
                   6179:         my (undef,$udom,$unum,$file_name,$group) =
                   6180:             &parse_portfolio_url($requrl);
                   6181:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6182:         my %access_controls = &get_access_controls($current_perms,
                   6183:                                                    $group,$file_name);
                   6184:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6185:             my ($num,$scope,$end,$start) = 
                   6186:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6187:             if ($scope eq 'public') {
                   6188:                 if ($start <= $now && $end == 0) {
                   6189:                     $action = 'none';
                   6190:                 } else {
                   6191:                     $action = 'update';
                   6192:                     $aclnum = $num;
                   6193:                 }
                   6194:                 last;
                   6195:             }
                   6196:         }
                   6197:         if ($action eq 'none') {
                   6198:              return 'ok';
                   6199:         } else {
                   6200:             my %changes;
                   6201:             my $newend = 0;
                   6202:             my $newstart = $now;
                   6203:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6204:             $changes{$action}{$newkey} = {
                   6205:                 type => 'public',
                   6206:                 time => {
                   6207:                     start => $newstart,
                   6208:                     end   => $newend,
                   6209:                 },
                   6210:             };
                   6211:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6212:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6213:             return $outcome;
                   6214:         }
                   6215:     } else {
                   6216:         return 'invalid';
                   6217:     }
                   6218: }
                   6219: 
1.745     raeburn  6220: #------------------------------------------------------Get Marked as Read Only
                   6221: 
                   6222: sub get_marked_as_readonly {
                   6223:     my ($domain,$user,$what,$group) = @_;
                   6224:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6225:     my @readonly_files;
1.629     banghart 6226:     my $cmp1=$what;
                   6227:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6228:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6229:         if (defined($group)) {
                   6230:             if ($file_name !~ m-^\Q$group\E/-) {
                   6231:                 next;
                   6232:             }
                   6233:         }
1.561     banghart 6234:         if (ref($value) eq "ARRAY"){
                   6235:             foreach my $stored_what (@{$value}) {
1.629     banghart 6236:                 my $cmp2=$stored_what;
1.759     albertel 6237:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6238:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6239:                 }
1.629     banghart 6240:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6241:                     push(@readonly_files, $file_name);
1.745     raeburn  6242:                     last;
1.563     banghart 6243:                 } elsif (!defined($what)) {
                   6244:                     push(@readonly_files, $file_name);
1.745     raeburn  6245:                     last;
1.561     banghart 6246:                 }
                   6247:             }
1.745     raeburn  6248:         }
1.561     banghart 6249:     }
                   6250:     return @readonly_files;
                   6251: }
1.577     banghart 6252: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6253: 
1.577     banghart 6254: sub get_marked_as_readonly_hash {
1.745     raeburn  6255:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6256:     my %readonly_files;
1.745     raeburn  6257:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6258:         if (defined($group)) {
                   6259:             if ($file_name !~ m-^\Q$group\E/-) {
                   6260:                 next;
                   6261:             }
                   6262:         }
1.577     banghart 6263:         if (ref($value) eq "ARRAY"){
                   6264:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6265:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6266:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6267:                         if ($lock_descriptor eq 'graded') {
                   6268:                             $readonly_files{$file_name} = 'graded';
                   6269:                         } elsif ($lock_descriptor eq 'handback') {
                   6270:                             $readonly_files{$file_name} = 'handback';
                   6271:                         } else {
                   6272:                             if (!exists($readonly_files{$file_name})) {
                   6273:                                 $readonly_files{$file_name} = 'locked';
                   6274:                             }
                   6275:                         }
1.745     raeburn  6276:                     }
1.750     banghart 6277:                 } 
1.577     banghart 6278:             }
                   6279:         } 
                   6280:     }
                   6281:     return %readonly_files;
                   6282: }
1.559     banghart 6283: # ------------------------------------------------------------ Unmark as Read Only
                   6284: 
                   6285: sub unmark_as_readonly {
1.629     banghart 6286:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6287:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6288:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6289:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6290:     my $symb_crs = $what;
                   6291:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6292:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6293:     my ($tmp)=keys(%current_permissions);
                   6294:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6295:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6296:     foreach my $file (@readonly_files) {
1.759     albertel 6297: 	my $clean_file = &declutter_portfile($file);
                   6298: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6299: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6300:         my @new_locks;
                   6301:         my @del_keys;
                   6302:         if (ref($current_locks) eq "ARRAY"){
                   6303:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6304:                 my $compare=$locker;
1.749     raeburn  6305:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6306:                     $compare=join('',@{$locker});
1.746     raeburn  6307:                     if ($compare ne $symb_crs) {
                   6308:                         push(@new_locks, $locker);
                   6309:                     }
1.563     banghart 6310:                 }
                   6311:             }
1.650     albertel 6312:             if (scalar(@new_locks) > 0) {
1.563     banghart 6313:                 $current_permissions{$file} = \@new_locks;
                   6314:             } else {
                   6315:                 push(@del_keys, $file);
1.613     albertel 6316:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6317:                 delete($current_permissions{$file});
1.563     banghart 6318:             }
                   6319:         }
1.561     banghart 6320:     }
1.613     albertel 6321:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6322:     return;
                   6323: }
1.512     banghart 6324: 
1.17      www      6325: # ------------------------------------------------------------ Directory lister
                   6326: 
                   6327: sub dirlist {
1.955     raeburn  6328:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6329:     $uri=~s/^\///;
                   6330:     $uri=~s/\/$//;
1.253     stredwic 6331:     my ($udom, $uname);
1.955     raeburn  6332:     if ($getuserdir) {
1.253     stredwic 6333:         $udom = $userdomain;
                   6334:         $uname = $username;
1.955     raeburn  6335:     } else {
                   6336:         (undef,$udom,$uname)=split(/\//,$uri);
                   6337:         if(defined($userdomain)) {
                   6338:             $udom = $userdomain;
                   6339:         }
                   6340:         if(defined($username)) {
                   6341:             $uname = $username;
                   6342:         }
1.253     stredwic 6343:     }
1.955     raeburn  6344:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6345: 
1.955     raeburn  6346:     $dirRoot = $perlvar{'lonDocRoot'};
                   6347:     if (defined($getpropath)) {
                   6348:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6349:         $dirRoot =~ s/\/$//;
1.955     raeburn  6350:     } elsif (defined($getuserdir)) {
                   6351:         my $subdir=$uname.'__';
                   6352:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6353:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6354:                    ."/$udom/$subdir/$uname";
                   6355:     } elsif (defined($alternateRoot)) {
                   6356:         $dirRoot = $alternateRoot;
1.751     banghart 6357:     }
1.253     stredwic 6358: 
                   6359:     if($udom) {
                   6360:         if($uname) {
1.955     raeburn  6361:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6362:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6363:                               .':'.&escape($uname).':'.&escape($udom),
                   6364:                               &homeserver($uname,$udom));
                   6365:             if ($listing eq 'unknown_cmd') {
                   6366:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6367:                                   &homeserver($uname,$udom));
                   6368:             } else {
                   6369:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6370:             }
1.605     matthew  6371:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6372:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6373: 				  &homeserver($uname,$udom));
1.605     matthew  6374:                 @listing_results = split(/:/,$listing);
                   6375:             } else {
                   6376:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6377:             }
                   6378:             return @listing_results;
1.955     raeburn  6379:         } elsif(!$alternateRoot) {
1.800     albertel 6380:             my %allusers;
1.841     albertel 6381: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6382:  	    foreach my $tryserver (keys(%servers)) {
                   6383:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6384:                                   &escape($udom),$tryserver);
                   6385:                 if ($listing eq 'unknown_cmd') {
                   6386: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6387: 				      $udom, $tryserver);
                   6388:                 } else {
                   6389:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6390:                 }
1.841     albertel 6391: 		if ($listing eq 'unknown_cmd') {
                   6392: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6393: 				      $udom, $tryserver);
                   6394: 		    @listing_results = split(/:/,$listing);
                   6395: 		} else {
                   6396: 		    @listing_results =
                   6397: 			map { &unescape($_); } split(/:/,$listing);
                   6398: 		}
                   6399: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6400: 		    $listing_results[0] ne 'empty'       &&
                   6401: 		    $listing_results[0] ne 'con_lost') {
                   6402: 		    foreach my $line (@listing_results) {
                   6403: 			my ($entry) = split(/&/,$line,2);
                   6404: 			$allusers{$entry} = 1;
                   6405: 		    }
                   6406: 		}
1.253     stredwic 6407:             }
                   6408:             my $alluserstr='';
1.800     albertel 6409:             foreach my $user (sort(keys(%allusers))) {
                   6410:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6411:             }
                   6412:             $alluserstr=~s/:$//;
                   6413:             return split(/:/,$alluserstr);
                   6414:         } else {
1.800     albertel 6415:             return ('missing user name');
1.253     stredwic 6416:         }
1.955     raeburn  6417:     } elsif(!defined($getpropath)) {
1.841     albertel 6418:         my @all_domains = sort(&all_domains());
1.955     raeburn  6419:         foreach my $domain (@all_domains) {
                   6420:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6421:         }
                   6422:         return @all_domains;
                   6423:     } else {
1.800     albertel 6424:         return ('missing domain');
1.275     stredwic 6425:     }
                   6426: }
                   6427: 
                   6428: # --------------------------------------------- GetFileTimestamp
                   6429: # This function utilizes dirlist and returns the date stamp for
                   6430: # when it was last modified.  It will also return an error of -1
                   6431: # if an error occurs
                   6432: 
                   6433: sub GetFileTimestamp {
1.955     raeburn  6434:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6435:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6436:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6437:     my ($fileStat) = 
                   6438:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6439:                                  undef,$getuserdir);
1.275     stredwic 6440:     my @stats = split('&', $fileStat);
                   6441:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6442:         # @stats contains first the filename, then the stat output
                   6443:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6444:     } else {
                   6445:         return -1;
1.253     stredwic 6446:     }
1.26      www      6447: }
                   6448: 
1.712     albertel 6449: sub stat_file {
                   6450:     my ($uri) = @_;
1.787     albertel 6451:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6452: 
1.955     raeburn  6453:     my ($udom,$uname,$file);
1.712     albertel 6454:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6455: 	($udom,$uname,$file) =
1.811     albertel 6456: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6457: 	$file = 'userfiles/'.$file;
                   6458:     }
                   6459:     if ($uri =~ m-^/res/-) {
                   6460: 	($udom,$uname) = 
1.807     albertel 6461: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6462: 	$file = $uri;
                   6463:     }
                   6464: 
                   6465:     if (!$udom || !$uname || !$file) {
                   6466: 	# unable to handle the uri
                   6467: 	return ();
                   6468:     }
1.956     raeburn  6469:     my $getpropath;
                   6470:     if ($file =~ /^userfiles\//) {
                   6471:         $getpropath = 1;
                   6472:     }
1.955     raeburn  6473:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6474:     my @stats = split('&', $result);
1.721     banghart 6475:     
1.712     albertel 6476:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6477: 	shift(@stats); #filename is first
                   6478: 	return @stats;
                   6479:     }
                   6480:     return ();
                   6481: }
                   6482: 
1.26      www      6483: # -------------------------------------------------------- Value of a Condition
                   6484: 
1.713     albertel 6485: # gets the value of a specific preevaluated condition
                   6486: #    stored in the string  $env{user.state.<cid>}
                   6487: # or looks up a condition reference in the bighash and if if hasn't
                   6488: # already been evaluated recurses into docondval to get the value of
                   6489: # the condition, then memoizing it to 
                   6490: #   $env{user.state.<cid>.<condition>}
1.40      www      6491: sub directcondval {
                   6492:     my $number=shift;
1.620     albertel 6493:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6494: 	&Apache::lonuserstate::evalstate();
                   6495:     }
1.713     albertel 6496:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6497: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6498:     } elsif ($number =~ /^_/) {
                   6499: 	my $sub_condition;
                   6500: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6501: 		&GDBM_READER(),0640)) {
                   6502: 	    $sub_condition=$bighash{'conditions'.$number};
                   6503: 	    untie(%bighash);
                   6504: 	}
                   6505: 	my $value = &docondval($sub_condition);
1.949     raeburn  6506: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6507: 	return $value;
                   6508:     }
1.620     albertel 6509:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6510:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6511:     } else {
                   6512:        return 2;
                   6513:     }
                   6514: }
                   6515: 
1.713     albertel 6516: # get the collection of conditions for this resource
1.26      www      6517: sub condval {
                   6518:     my $condidx=shift;
1.54      www      6519:     my $allpathcond='';
1.713     albertel 6520:     foreach my $cond (split(/\|/,$condidx)) {
                   6521: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6522: 	    $allpathcond.=
                   6523: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6524: 	}
1.191     harris41 6525:     }
1.54      www      6526:     $allpathcond=~s/\|$//;
1.713     albertel 6527:     return &docondval($allpathcond);
                   6528: }
                   6529: 
                   6530: #evaluates an expression of conditions
                   6531: sub docondval {
                   6532:     my ($allpathcond) = @_;
                   6533:     my $result=0;
                   6534:     if ($env{'request.course.id'}
                   6535: 	&& defined($allpathcond)) {
                   6536: 	my $operand='|';
                   6537: 	my @stack;
                   6538: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6539: 	    if ($chunk eq '(') {
                   6540: 		push @stack,($operand,$result);
                   6541: 	    } elsif ($chunk eq ')') {
                   6542: 		my $before=pop @stack;
                   6543: 		if (pop @stack eq '&') {
                   6544: 		    $result=$result>$before?$before:$result;
                   6545: 		} else {
                   6546: 		    $result=$result>$before?$result:$before;
                   6547: 		}
                   6548: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6549: 		$operand=$chunk;
                   6550: 	    } else {
                   6551: 		my $new=directcondval($chunk);
                   6552: 		if ($operand eq '&') {
                   6553: 		    $result=$result>$new?$new:$result;
                   6554: 		} else {
                   6555: 		    $result=$result>$new?$result:$new;
                   6556: 		}
                   6557: 	    }
                   6558: 	}
1.26      www      6559:     }
                   6560:     return $result;
1.421     albertel 6561: }
                   6562: 
                   6563: # ---------------------------------------------------- Devalidate courseresdata
                   6564: 
                   6565: sub devalidatecourseresdata {
                   6566:     my ($coursenum,$coursedomain)=@_;
                   6567:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6568:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6569: }
                   6570: 
1.763     www      6571: 
1.200     www      6572: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6573: #
                   6574: #  Parameters:
                   6575: #      $coursenum    - Number of the course.
                   6576: #      $coursedomain - Domain at which the course was created.
                   6577: #  Returns:
                   6578: #     A hash of the course parameters along (I think) with timestamps
                   6579: #     and version info.
1.877     foxr     6580: 
1.624     albertel 6581: sub get_courseresdata {
                   6582:     my ($coursenum,$coursedomain)=@_;
1.200     www      6583:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6584:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6585:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6586:     my %dumpreply;
1.417     albertel 6587:     unless (defined($cached)) {
1.624     albertel 6588: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6589: 	$result=\%dumpreply;
1.251     albertel 6590: 	my ($tmp) = keys(%dumpreply);
                   6591: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6592: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6593: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6594: 	    return $tmp;
1.416     albertel 6595: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6596: 	    $result=undef;
1.599     albertel 6597: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6598: 	}
                   6599:     }
1.624     albertel 6600:     return $result;
                   6601: }
                   6602: 
1.633     albertel 6603: sub devalidateuserresdata {
                   6604:     my ($uname,$udom)=@_;
                   6605:     my $hashid="$udom:$uname";
                   6606:     &devalidate_cache_new('userres',$hashid);
                   6607: }
                   6608: 
1.624     albertel 6609: sub get_userresdata {
                   6610:     my ($uname,$udom)=@_;
                   6611:     #most student don\'t have any data set, check if there is some data
                   6612:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6613: 
                   6614:     my $hashid="$udom:$uname";
                   6615:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6616:     if (!defined($cached)) {
                   6617: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6618: 	$result=\%resourcedata;
                   6619: 	&do_cache_new('userres',$hashid,$result,600);
                   6620:     }
                   6621:     my ($tmp)=keys(%$result);
                   6622:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6623: 	return $result;
                   6624:     }
                   6625:     #error 2 occurs when the .db doesn't exist
                   6626:     if ($tmp!~/error: 2 /) {
1.672     albertel 6627: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6628: 		 " Trying to get resource data for ".
                   6629: 		 $uname." at ".$udom.": ".
                   6630: 		 $tmp."</font>");
                   6631:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6632: 	#&EXT_cache_set($udom,$uname);
                   6633: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6634: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6635:     }
                   6636:     return $tmp;
                   6637: }
1.879     foxr     6638: #----------------------------------------------- resdata - return resource data
                   6639: #  Purpose:
                   6640: #    Return resource data for either users or for a course.
                   6641: #  Parameters:
                   6642: #     $name      - Course/user name.
                   6643: #     $domain    - Name of the domain the user/course is registered on.
                   6644: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6645: #     @which     - Array of names of resources desired.
                   6646: #  Returns:
                   6647: #     The value of the first reasource in @which that is found in the
                   6648: #     resource hash.
                   6649: #  Exceptional Conditions:
                   6650: #     If the $type passed in is not valid (not the string 'course' or 
                   6651: #     'user', an undefined  reference is returned.
                   6652: #     If none of the resources are found, an undef is returned
1.624     albertel 6653: sub resdata {
                   6654:     my ($name,$domain,$type,@which)=@_;
                   6655:     my $result;
                   6656:     if ($type eq 'course') {
                   6657: 	$result=&get_courseresdata($name,$domain);
                   6658:     } elsif ($type eq 'user') {
                   6659: 	$result=&get_userresdata($name,$domain);
                   6660:     }
                   6661:     if (!ref($result)) { return $result; }    
1.251     albertel 6662:     foreach my $item (@which) {
1.927     albertel 6663: 	if (defined($result->{$item->[0]})) {
                   6664: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6665: 	}
1.250     albertel 6666:     }
1.291     albertel 6667:     return undef;
1.200     www      6668: }
                   6669: 
1.379     matthew  6670: #
                   6671: # EXT resource caching routines
                   6672: #
                   6673: 
                   6674: sub clear_EXT_cache_status {
1.383     albertel 6675:     &delenv('cache.EXT.');
1.379     matthew  6676: }
                   6677: 
                   6678: sub EXT_cache_status {
                   6679:     my ($target_domain,$target_user) = @_;
1.383     albertel 6680:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6681:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6682:         # We know already the user has no data
                   6683:         return 1;
                   6684:     } else {
                   6685:         return 0;
                   6686:     }
                   6687: }
                   6688: 
                   6689: sub EXT_cache_set {
                   6690:     my ($target_domain,$target_user) = @_;
1.383     albertel 6691:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6692:     #&appenv({$cachename => time});
1.379     matthew  6693: }
                   6694: 
1.28      www      6695: # --------------------------------------------------------- Value of a Variable
1.58      www      6696: sub EXT {
1.715     albertel 6697: 
1.395     albertel 6698:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6699:     unless ($varname) { return ''; }
1.218     albertel 6700:     #get real user name/domain, courseid and symb
                   6701:     my $courseid;
1.359     albertel 6702:     my $publicuser;
1.427     www      6703:     if ($symbparm) {
                   6704: 	$symbparm=&get_symb_from_alias($symbparm);
                   6705:     }
1.218     albertel 6706:     if (!($uname && $udom)) {
1.790     albertel 6707:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6708:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6709:     } else {
1.620     albertel 6710: 	$courseid=$env{'request.course.id'};
1.218     albertel 6711:     }
1.48      www      6712:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6713:     my $rest;
1.320     albertel 6714:     if (defined($therest[0])) {
1.48      www      6715:        $rest=join('.',@therest);
                   6716:     } else {
                   6717:        $rest='';
                   6718:     }
1.320     albertel 6719: 
1.57      www      6720:     my $qualifierrest=$qualifier;
                   6721:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6722:     my $spacequalifierrest=$space;
                   6723:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6724:     if ($realm eq 'user') {
1.48      www      6725: # --------------------------------------------------------------- user.resource
                   6726: 	if ($space eq 'resource') {
1.651     albertel 6727: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6728: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6729: 		 &&
1.744     albertel 6730: 		 ($symbparm eq &symbread()) ) {	
                   6731: 		# if we are in the middle of processing the resource the
                   6732: 		# get the value we are planning on committing
                   6733:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6734:                     return $Apache::lonhomework::results{$qualifierrest};
                   6735:                 } else {
                   6736:                     return $Apache::lonhomework::history{$qualifierrest};
                   6737:                 }
1.335     albertel 6738: 	    } else {
1.359     albertel 6739: 		my %restored;
1.620     albertel 6740: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6741: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6742: 		} else {
                   6743: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6744: 		}
1.335     albertel 6745: 		return $restored{$qualifierrest};
                   6746: 	    }
1.48      www      6747: # ----------------------------------------------------------------- user.access
                   6748:         } elsif ($space eq 'access') {
1.218     albertel 6749: 	    # FIXME - not supporting calls for a specific user
1.48      www      6750:             return &allowed($qualifier,$rest);
                   6751: # ------------------------------------------ user.preferences, user.environment
                   6752:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6753: 	    if (($uname eq $env{'user.name'}) &&
                   6754: 		($udom eq $env{'user.domain'})) {
                   6755: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6756: 	    } else {
1.359     albertel 6757: 		my %returnhash;
                   6758: 		if (!$publicuser) {
                   6759: 		    %returnhash=&userenvironment($udom,$uname,
                   6760: 						 $qualifierrest);
                   6761: 		}
1.218     albertel 6762: 		return $returnhash{$qualifierrest};
                   6763: 	    }
1.48      www      6764: # ----------------------------------------------------------------- user.course
                   6765:         } elsif ($space eq 'course') {
1.218     albertel 6766: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6767:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6768: # ------------------------------------------------------------------- user.role
                   6769:         } elsif ($space eq 'role') {
1.218     albertel 6770: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6771:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6772:             if ($qualifier eq 'value') {
                   6773: 		return $role;
                   6774:             } elsif ($qualifier eq 'extent') {
                   6775:                 return $where;
                   6776:             }
                   6777: # ----------------------------------------------------------------- user.domain
                   6778:         } elsif ($space eq 'domain') {
1.218     albertel 6779:             return $udom;
1.48      www      6780: # ------------------------------------------------------------------- user.name
                   6781:         } elsif ($space eq 'name') {
1.218     albertel 6782:             return $uname;
1.48      www      6783: # ---------------------------------------------------- Any other user namespace
1.29      www      6784:         } else {
1.359     albertel 6785: 	    my %reply;
                   6786: 	    if (!$publicuser) {
                   6787: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6788: 	    }
                   6789: 	    return $reply{$qualifierrest};
1.48      www      6790:         }
1.236     www      6791:     } elsif ($realm eq 'query') {
                   6792: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6793:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6794: 						[$spacequalifierrest]);
1.620     albertel 6795: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6796:    } elsif ($realm eq 'request') {
1.48      www      6797: # ------------------------------------------------------------- request.browser
                   6798:         if ($space eq 'browser') {
1.430     www      6799: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6800: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6801: 		    return 1;
                   6802: 		} else {
                   6803: 		    return 0;
                   6804: 		}
                   6805: 	    } else {
1.620     albertel 6806: 		return $env{'browser.'.$qualifier};
1.430     www      6807: 	    }
1.57      www      6808: # ------------------------------------------------------------ request.filename
                   6809:         } else {
1.620     albertel 6810:             return $env{'request.'.$spacequalifierrest};
1.29      www      6811:         }
1.28      www      6812:     } elsif ($realm eq 'course') {
1.48      www      6813: # ---------------------------------------------------------- course.description
1.620     albertel 6814:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6815:     } elsif ($realm eq 'resource') {
1.165     www      6816: 
1.620     albertel 6817: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6818: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6819: 	}
1.693     albertel 6820: 
                   6821: 	if ($space eq 'title') {
                   6822: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6823: 	    return &gettitle($symbparm);
                   6824: 	}
                   6825: 	
                   6826: 	if ($space eq 'map') {
                   6827: 	    my ($map) = &decode_symb($symbparm);
                   6828: 	    return &symbread($map);
                   6829: 	}
1.905     albertel 6830: 	if ($space eq 'filename') {
                   6831: 	    if ($symbparm) {
                   6832: 		return &clutter((&decode_symb($symbparm))[2]);
                   6833: 	    }
                   6834: 	    return &hreflocation('',$env{'request.filename'});
                   6835: 	}
1.693     albertel 6836: 
                   6837: 	my ($section, $group, @groups);
1.593     albertel 6838: 	my ($courselevelm,$courselevel);
1.539     albertel 6839: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6840: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6841: 
1.218     albertel 6842: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6843: 
1.60      www      6844: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6845: 	    my $symbp=$symbparm;
1.735     albertel 6846: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6847: 
                   6848: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6849: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6850: 
1.620     albertel 6851: 	    if (($env{'user.name'} eq $uname) &&
                   6852: 		($env{'user.domain'} eq $udom)) {
                   6853: 		$section=$env{'request.course.sec'};
1.733     raeburn  6854:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6855:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6856: 	    } else {
1.539     albertel 6857: 		if (! defined($usection)) {
1.551     albertel 6858: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6859: 		} else {
                   6860: 		    $section = $usection;
                   6861: 		}
1.733     raeburn  6862:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6863: 	    }
                   6864: 
                   6865: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6866: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6867: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6868: 
1.593     albertel 6869: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6870: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6871: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6872: 
1.60      www      6873: # ----------------------------------------------------------- first, check user
1.624     albertel 6874: 
                   6875: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6876: 				       ([$courselevelr,'resource'],
                   6877: 					[$courselevelm,'map'     ],
                   6878: 					[$courselevel, 'course'  ]));
1.931     albertel 6879: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6880: 
1.594     albertel 6881: # ------------------------------------------------ second, check some of course
1.684     raeburn  6882:             my $coursereply;
1.691     raeburn  6883:             if (@groups > 0) {
                   6884:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6885:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6886:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6887:             }
1.96      www      6888: 
1.684     raeburn  6889: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6890: 				  $env{'course.'.$courseid.'.domain'},
                   6891: 				  'course',
                   6892: 				  ([$seclevelr,   'resource'],
                   6893: 				   [$seclevelm,   'map'     ],
                   6894: 				   [$seclevel,    'course'  ],
                   6895: 				   [$courselevelr,'resource']));
                   6896: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6897: 
1.60      www      6898: # ------------------------------------------------------ third, check map parms
1.218     albertel 6899: 	    my %parmhash=();
                   6900: 	    my $thisparm='';
                   6901: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6902: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6903: 		    &GDBM_READER(),0640)) {
1.218     albertel 6904: 		$thisparm=$parmhash{$symbparm};
                   6905: 		untie(%parmhash);
                   6906: 	    }
1.927     albertel 6907: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6908: 	}
1.594     albertel 6909: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6910: 
1.218     albertel 6911: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6912: 	my $filename;
                   6913: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6914: 	if ($symbparm) {
1.409     www      6915: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6916: 	} else {
1.620     albertel 6917: 	    $filename=$env{'request.filename'};
1.282     albertel 6918: 	}
                   6919: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6920: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6921: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6922: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6923: 
1.927     albertel 6924: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6925: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6926: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6927: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6928: 				     $env{'course.'.$courseid.'.domain'},
                   6929: 				     'course',
1.927     albertel 6930: 				     ([$courselevelm,'map'   ],
                   6931: 				      [$courselevel, 'course']));
                   6932: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6933: 	}
1.145     www      6934: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6935: 	unless ($space eq '0') {
1.336     albertel 6936: 	    my @parts=split(/_/,$space);
                   6937: 	    my $id=pop(@parts);
                   6938: 	    my $part=join('_',@parts);
                   6939: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6940: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6941: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6942: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6943: 	}
1.395     albertel 6944: 	if ($recurse) { return undef; }
                   6945: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6946: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6947: # ---------------------------------------------------- Any other user namespace
                   6948:     } elsif ($realm eq 'environment') {
                   6949: # ----------------------------------------------------------------- environment
1.620     albertel 6950: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6951: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6952: 	} else {
1.770     albertel 6953: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6954: 		return '';
                   6955: 	    }
1.219     albertel 6956: 	    my %returnhash=&userenvironment($udom,$uname,
                   6957: 					    $spacequalifierrest);
                   6958: 	    return $returnhash{$spacequalifierrest};
                   6959: 	}
1.28      www      6960:     } elsif ($realm eq 'system') {
1.48      www      6961: # ----------------------------------------------------------------- system.time
                   6962: 	if ($space eq 'time') {
                   6963: 	    return time;
                   6964:         }
1.696     albertel 6965:     } elsif ($realm eq 'server') {
                   6966: # ----------------------------------------------------------------- system.time
                   6967: 	if ($space eq 'name') {
                   6968: 	    return $ENV{'SERVER_NAME'};
                   6969:         }
1.28      www      6970:     }
1.48      www      6971:     return '';
1.61      www      6972: }
                   6973: 
1.927     albertel 6974: sub get_reply {
                   6975:     my ($reply_value) = @_;
1.940     raeburn  6976:     if (ref($reply_value) eq 'ARRAY') {
                   6977:         if (wantarray) {
                   6978: 	    return @$reply_value;
                   6979:         }
                   6980:         return $reply_value->[0];
                   6981:     } else {
                   6982:         return $reply_value;
1.927     albertel 6983:     }
                   6984: }
                   6985: 
1.691     raeburn  6986: sub check_group_parms {
                   6987:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6988:     my @groupitems = ();
                   6989:     my $resultitem;
1.927     albertel 6990:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6991:     foreach my $group (@{$groups}) {
                   6992:         foreach my $level (@levels) {
1.927     albertel 6993:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6994:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6995:         }
                   6996:     }
                   6997:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6998:                             $env{'course.'.$courseid.'.domain'},
                   6999:                                      'course',@groupitems);
                   7000:     return $coursereply;
                   7001: }
                   7002: 
                   7003: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7004:     my ($courseid,@groups) = @_;
                   7005:     @groups = sort(@groups);
1.691     raeburn  7006:     return @groups;
                   7007: }
                   7008: 
1.395     albertel 7009: sub packages_tab_default {
                   7010:     my ($uri,$varname)=@_;
                   7011:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7012: 
                   7013:     my (@extension,@specifics,$do_default);
                   7014:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7015: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7016: 	if ($pack_type eq 'default') {
                   7017: 	    $do_default=1;
                   7018: 	} elsif ($pack_type eq 'extension') {
                   7019: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7020: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7021: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7022: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7023: 	}
                   7024:     }
                   7025:     # first look for a package that matches the requested part id
                   7026:     foreach my $package (@specifics) {
                   7027: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7028: 	next if ($pack_part ne $part);
                   7029: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7030: 	    return $packagetab{"$pack_type&$name&default"};
                   7031: 	}
                   7032:     }
                   7033:     # look for any possible matching non extension_ package
                   7034:     foreach my $package (@specifics) {
                   7035: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7036: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7037: 	    return $packagetab{"$pack_type&$name&default"};
                   7038: 	}
1.585     albertel 7039: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7040: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7041: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7042: 	}
                   7043:     }
1.738     albertel 7044:     # look for any posible extension_ match
                   7045:     foreach my $package (@extension) {
                   7046: 	my ($package,$pack_type)=@{$package};
                   7047: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7048: 	    return $packagetab{"$pack_type&$name&default"};
                   7049: 	}
                   7050: 	if (defined($packagetab{$package."&$name&default"})) {
                   7051: 	    return $packagetab{$package."&$name&default"};
                   7052: 	}
                   7053:     }
                   7054:     # look for a global default setting
                   7055:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7056: 	return $packagetab{"default&$name&default"};
                   7057:     }
1.395     albertel 7058:     return undef;
                   7059: }
                   7060: 
1.334     albertel 7061: sub add_prefix_and_part {
                   7062:     my ($prefix,$part)=@_;
                   7063:     my $keyroot;
                   7064:     if (defined($prefix) && $prefix !~ /^__/) {
                   7065: 	# prefix that has a part already
                   7066: 	$keyroot=$prefix;
                   7067:     } elsif (defined($prefix)) {
                   7068: 	# prefix that is missing a part
                   7069: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7070:     } else {
                   7071: 	# no prefix at all
                   7072: 	if (defined($part)) { $keyroot='_'.$part; }
                   7073:     }
                   7074:     return $keyroot;
                   7075: }
                   7076: 
1.71      www      7077: # ---------------------------------------------------------------- Get metadata
                   7078: 
1.599     albertel 7079: my %metaentry;
1.71      www      7080: sub metadata {
1.176     www      7081:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7082:     $uri=&declutter($uri);
1.288     albertel 7083:     # if it is a non metadata possible uri return quickly
1.529     albertel 7084:     if (($uri eq '') || 
                   7085: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7086: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7087:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7088: 	return undef;
                   7089:     }
                   7090:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7091: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7092: 	return undef;
1.288     albertel 7093:     }
1.73      www      7094:     my $filename=$uri;
                   7095:     $uri=~s/\.meta$//;
1.172     www      7096: #
                   7097: # Is the metadata already cached?
1.177     www      7098: # Look at timestamp of caching
1.172     www      7099: # Everything is cached by the main uri, libraries are never directly cached
                   7100: #
1.428     albertel 7101:     if (!defined($liburi)) {
1.599     albertel 7102: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7103: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7104:     }
                   7105:     {
1.172     www      7106: #
                   7107: # Is this a recursive call for a library?
                   7108: #
1.599     albertel 7109: #	if (! exists($metacache{$uri})) {
                   7110: #	    $metacache{$uri}={};
                   7111: #	}
1.924     albertel 7112: 	my $cachetime = 60*60;
1.171     www      7113:         if ($liburi) {
                   7114: 	    $liburi=&declutter($liburi);
                   7115:             $filename=$liburi;
1.401     bowersj2 7116:         } else {
1.599     albertel 7117: 	    &devalidate_cache_new('meta',$uri);
                   7118: 	    undef(%metaentry);
1.401     bowersj2 7119: 	}
1.140     www      7120:         my %metathesekeys=();
1.73      www      7121:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7122: 	my $metastring;
1.924     albertel 7123: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7124: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7125: 	    $metastring = 
1.929     albertel 7126: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7127: 					  ('grade_target' => 'meta'));
                   7128: 	    $cachetime = 1; # only want this cached in the child not long term
                   7129: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7130: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7131: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7132: 	    $metastring=&getfile($file);
1.489     albertel 7133: 	}
1.208     albertel 7134:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7135:         my $token;
1.140     www      7136:         undef %metathesekeys;
1.71      www      7137:         while ($token=$parser->get_token) {
1.339     albertel 7138: 	    if ($token->[0] eq 'S') {
                   7139: 		if (defined($token->[2]->{'package'})) {
1.172     www      7140: #
                   7141: # This is a package - get package info
                   7142: #
1.339     albertel 7143: 		    my $package=$token->[2]->{'package'};
                   7144: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7145: 		    if (defined($token->[2]->{'id'})) { 
                   7146: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7147: 		    }
1.599     albertel 7148: 		    if ($metaentry{':packages'}) {
                   7149: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7150: 		    } else {
1.599     albertel 7151: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7152: 		    }
1.736     albertel 7153: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7154: 			my $part=$keyroot;
                   7155: 			$part=~s/^\_//;
1.736     albertel 7156: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7157: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7158: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7159: 			    # ignore package.tab specified default values
                   7160:                             # here &package_tab_default() will fetch those
                   7161: 			    if ($subp eq 'default') { next; }
1.736     albertel 7162: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7163: 			    my $unikey;
                   7164: 			    if ($pack =~ /_0$/) {
                   7165: 				$unikey='parameter_0_'.$name;
                   7166: 				$part=0;
                   7167: 			    } else {
                   7168: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7169: 			    }
1.339     albertel 7170: 			    if ($subp eq 'display') {
                   7171: 				$value.=' [Part: '.$part.']';
                   7172: 			    }
1.599     albertel 7173: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7174: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7175: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7176: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7177: 			    }
1.599     albertel 7178: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7179: 				$metaentry{':'.$unikey}=
                   7180: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7181: 			    }
1.339     albertel 7182: 			}
                   7183: 		    }
                   7184: 		} else {
1.172     www      7185: #
                   7186: # This is not a package - some other kind of start tag
1.339     albertel 7187: #
                   7188: 		    my $entry=$token->[1];
                   7189: 		    my $unikey;
                   7190: 		    if ($entry eq 'import') {
                   7191: 			$unikey='';
                   7192: 		    } else {
                   7193: 			$unikey=$entry;
                   7194: 		    }
                   7195: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7196: 
                   7197: 		    if (defined($token->[2]->{'id'})) { 
                   7198: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7199: 		    }
1.175     www      7200: 
1.339     albertel 7201: 		    if ($entry eq 'import') {
1.175     www      7202: #
                   7203: # Importing a library here
1.339     albertel 7204: #
                   7205: 			if ($depthcount<20) {
                   7206: 			    my $location=$parser->get_text('/import');
                   7207: 			    my $dir=$filename;
                   7208: 			    $dir=~s|[^/]*$||;
                   7209: 			    $location=&filelocation($dir,$location);
1.736     albertel 7210: 			    my $metadata = 
                   7211: 				&metadata($uri,'keys', $location,$unikey,
                   7212: 					  $depthcount+1);
                   7213: 			    foreach my $meta (split(',',$metadata)) {
                   7214: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7215: 				$metathesekeys{$meta}=1;
1.339     albertel 7216: 			    }
                   7217: 			}
                   7218: 		    } else { 
                   7219: 			
                   7220: 			if (defined($token->[2]->{'name'})) { 
                   7221: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7222: 			}
                   7223: 			$metathesekeys{$unikey}=1;
1.736     albertel 7224: 			foreach my $param (@{$token->[3]}) {
                   7225: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7226: 				$token->[2]->{$param};
1.339     albertel 7227: 			}
                   7228: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7229: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7230: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7231: 		 # only ws inside the tag, and not in default, so use default
                   7232: 		 # as value
1.599     albertel 7233: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7234: 			} elsif ( $internaltext =~ /\S/ ) {
                   7235: 		  # something interesting inside the tag
                   7236: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7237: 			} else {
1.908     albertel 7238: 		  # no interesting values, don't set a default
1.339     albertel 7239: 			}
1.172     www      7240: # end of not-a-package not-a-library import
1.339     albertel 7241: 		    }
1.172     www      7242: # end of not-a-package start tag
1.339     albertel 7243: 		}
1.172     www      7244: # the next is the end of "start tag"
1.339     albertel 7245: 	    }
                   7246: 	}
1.483     albertel 7247: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7248: 	$extension = lc($extension);
                   7249: 	if ($extension eq 'htm') { $extension='html'; }
                   7250: 
1.737     albertel 7251: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7252: 	    #no specific packages #how's our extension
                   7253: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7254: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7255: 					 \%metathesekeys);
                   7256: 	}
1.883     albertel 7257: 
                   7258: 	if (!exists($metaentry{':packages'})
                   7259: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7260: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7261: 		#no specific packages well let's get default then
                   7262: 		if ($key!~/^default&/) { next; }
1.488     albertel 7263: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7264: 					     \%metathesekeys);
                   7265: 	    }
                   7266: 	}
1.338     www      7267: # are there custom rights to evaluate
1.599     albertel 7268: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7269: 
1.338     www      7270:     #
                   7271:     # Importing a rights file here
1.339     albertel 7272:     #
                   7273: 	    unless ($depthcount) {
1.599     albertel 7274: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7275: 		my $dir=$filename;
                   7276: 		$dir=~s|[^/]*$||;
                   7277: 		$location=&filelocation($dir,$location);
1.736     albertel 7278: 		my $rights_metadata =
                   7279: 		    &metadata($uri,'keys',$location,'_rights',
                   7280: 			      $depthcount+1);
                   7281: 		foreach my $rights (split(',',$rights_metadata)) {
                   7282: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7283: 		    $metathesekeys{$rights}=1;
1.339     albertel 7284: 		}
                   7285: 	    }
                   7286: 	}
1.737     albertel 7287: 	# uniqifiy package listing
                   7288: 	my %seen;
                   7289: 	my @uniq_packages =
                   7290: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7291: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7292: 
                   7293: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7294: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7295: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7296: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7297: # this is the end of "was not already recently cached
1.71      www      7298:     }
1.599     albertel 7299:     return $metaentry{':'.$what};
1.261     albertel 7300: }
                   7301: 
1.488     albertel 7302: sub metadata_create_package_def {
1.483     albertel 7303:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7304:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7305:     if ($subp eq 'default') { next; }
                   7306:     
1.599     albertel 7307:     if (defined($metaentry{':packages'})) {
                   7308: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7309:     } else {
1.599     albertel 7310: 	$metaentry{':packages'}=$package;
1.483     albertel 7311:     }
                   7312:     my $value=$packagetab{$key};
                   7313:     my $unikey;
                   7314:     $unikey='parameter_0_'.$name;
1.599     albertel 7315:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7316:     $$metathesekeys{$unikey}=1;
1.599     albertel 7317:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7318: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7319:     }
1.599     albertel 7320:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7321: 	$metaentry{':'.$unikey}=
                   7322: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7323:     }
                   7324: }
                   7325: 
1.261     albertel 7326: sub metadata_generate_part0 {
                   7327:     my ($metadata,$metacache,$uri) = @_;
                   7328:     my %allnames;
1.737     albertel 7329:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7330: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7331: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7332: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7333: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7334: 	    $allnames{$name}=$part;
                   7335: 	  }
                   7336: 	}
                   7337:     }
                   7338:     foreach my $name (keys(%allnames)) {
                   7339:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7340:       my $key=":parameter_0_$name";
1.261     albertel 7341:       $$metacache{"$key.part"}='0';
                   7342:       $$metacache{"$key.name"}=$name;
1.428     albertel 7343:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7344: 					   $allnames{$name}.'_'.$name.
                   7345: 					   '.type'};
1.428     albertel 7346:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7347: 			     '.display'};
1.644     www      7348:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7349:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7350:       $$metacache{"$key.display"}=$olddis;
                   7351:     }
1.71      www      7352: }
                   7353: 
1.764     albertel 7354: # ------------------------------------------------------ Devalidate title cache
                   7355: 
                   7356: sub devalidate_title_cache {
                   7357:     my ($url)=@_;
                   7358:     if (!$env{'request.course.id'}) { return; }
                   7359:     my $symb=&symbread($url);
                   7360:     if (!$symb) { return; }
                   7361:     my $key=$env{'request.course.id'}."\0".$symb;
                   7362:     &devalidate_cache_new('title',$key);
                   7363: }
                   7364: 
1.301     www      7365: # ------------------------------------------------- Get the title of a resource
                   7366: 
                   7367: sub gettitle {
                   7368:     my $urlsymb=shift;
                   7369:     my $symb=&symbread($urlsymb);
1.534     albertel 7370:     if ($symb) {
1.620     albertel 7371: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7372: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7373: 	if (defined($cached)) { 
                   7374: 	    return $result;
                   7375: 	}
1.534     albertel 7376: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7377: 	my $title='';
1.907     albertel 7378: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7379: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7380: 	} else {
                   7381: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7382: 		    &GDBM_READER(),0640)) {
                   7383: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7384: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7385: 		untie(%bighash);
                   7386: 	    }
1.534     albertel 7387: 	}
                   7388: 	$title=~s/\&colon\;/\:/gs;
                   7389: 	if ($title) {
1.599     albertel 7390: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7391: 	}
                   7392: 	$urlsymb=$url;
                   7393:     }
                   7394:     my $title=&metadata($urlsymb,'title');
                   7395:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7396:     return $title;
1.301     www      7397: }
1.613     albertel 7398: 
1.614     albertel 7399: sub get_slot {
                   7400:     my ($which,$cnum,$cdom)=@_;
                   7401:     if (!$cnum || !$cdom) {
1.790     albertel 7402: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7403: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7404: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7405:     }
1.703     albertel 7406:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7407:     my %slotinfo;
                   7408:     if (exists($remembered{$key})) {
                   7409: 	$slotinfo{$which} = $remembered{$key};
                   7410:     } else {
                   7411: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7412: 	&Apache::lonhomework::showhash(%slotinfo);
                   7413: 	my ($tmp)=keys(%slotinfo);
                   7414: 	if ($tmp=~/^error:/) { return (); }
                   7415: 	$remembered{$key} = $slotinfo{$which};
                   7416:     }
1.616     albertel 7417:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7418: 	return %{$slotinfo{$which}};
                   7419:     }
                   7420:     return $slotinfo{$which};
1.614     albertel 7421: }
1.31      www      7422: # ------------------------------------------------- Update symbolic store links
                   7423: 
                   7424: sub symblist {
                   7425:     my ($mapname,%newhash)=@_;
1.438     www      7426:     $mapname=&deversion(&declutter($mapname));
1.31      www      7427:     my %hash;
1.620     albertel 7428:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7429:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7430:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7431: 	    foreach my $url (keys %newhash) {
                   7432: 		next if ($url eq 'last_known'
                   7433: 			 && $env{'form.no_update_last_known'});
                   7434: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7435: 						    $newhash{$url}->[1],
                   7436: 						    $newhash{$url}->[0]);
1.191     harris41 7437:             }
1.31      www      7438:             if (untie(%hash)) {
                   7439: 		return 'ok';
                   7440:             }
                   7441:         }
                   7442:     }
                   7443:     return 'error';
1.212     www      7444: }
                   7445: 
                   7446: # --------------------------------------------------------------- Verify a symb
                   7447: 
                   7448: sub symbverify {
1.510     www      7449:     my ($symb,$thisurl)=@_;
                   7450:     my $thisfn=$thisurl;
1.439     www      7451:     $thisfn=&declutter($thisfn);
1.215     www      7452: # direct jump to resource in page or to a sequence - will construct own symbs
                   7453:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7454: # check URL part
1.409     www      7455:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7456: 
1.431     www      7457:     unless ($url eq $thisfn) { return 0; }
1.213     www      7458: 
1.216     www      7459:     $symb=&symbclean($symb);
1.510     www      7460:     $thisurl=&deversion($thisurl);
1.439     www      7461:     $thisfn=&deversion($thisfn);
1.213     www      7462: 
                   7463:     my %bighash;
                   7464:     my $okay=0;
1.431     www      7465: 
1.620     albertel 7466:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7467:                             &GDBM_READER(),0640)) {
1.510     www      7468:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7469:         unless ($ids) { 
1.510     www      7470:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7471:         }
                   7472:         if ($ids) {
                   7473: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7474: 	    foreach my $id (split(/\,/,$ids)) {
                   7475: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7476:                if (
                   7477:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7478:    eq $symb) { 
1.620     albertel 7479: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7480: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7481: 		       $okay=1; 
                   7482: 		   }
                   7483: 	       }
1.216     www      7484: 	   }
                   7485:         }
1.213     www      7486: 	untie(%bighash);
                   7487:     }
                   7488:     return $okay;
1.31      www      7489: }
                   7490: 
1.210     www      7491: # --------------------------------------------------------------- Clean-up symb
                   7492: 
                   7493: sub symbclean {
                   7494:     my $symb=shift;
1.568     albertel 7495:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7496: # remove version from map
                   7497:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7498: 
1.210     www      7499: # remove version from URL
                   7500:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7501: 
1.507     www      7502: # remove wrapper
                   7503: 
1.510     www      7504:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7505:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7506:     return $symb;
1.409     www      7507: }
                   7508: 
                   7509: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7510: 
                   7511: sub encode_symb {
                   7512:     my ($map,$resid,$url)=@_;
                   7513:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7514: }
1.409     www      7515: 
                   7516: sub decode_symb {
1.568     albertel 7517:     my $symb=shift;
                   7518:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7519:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7520:     return (&fixversion($map),$resid,&fixversion($url));
                   7521: }
                   7522: 
                   7523: sub fixversion {
                   7524:     my $fn=shift;
1.609     banghart 7525:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7526:     my %bighash;
                   7527:     my $uri=&clutter($fn);
1.620     albertel 7528:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7529: # is this cached?
1.599     albertel 7530:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7531:     if (defined($cached)) { return $result; }
                   7532: # unfortunately not cached, or expired
1.620     albertel 7533:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7534: 	    &GDBM_READER(),0640)) {
                   7535:  	if ($bighash{'version_'.$uri}) {
                   7536:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7537:  	    unless (($version eq 'mostrecent') || 
                   7538: 		    ($version==&getversion($uri))) {
1.440     www      7539:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7540:  	    }
                   7541:  	}
                   7542:  	untie %bighash;
1.413     www      7543:     }
1.599     albertel 7544:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7545: }
                   7546: 
                   7547: sub deversion {
                   7548:     my $url=shift;
                   7549:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7550:     return $url;
1.210     www      7551: }
                   7552: 
1.31      www      7553: # ------------------------------------------------------ Return symb list entry
                   7554: 
                   7555: sub symbread {
1.249     www      7556:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7557:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7558:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7559: # no filename provided? try from environment
1.44      www      7560:     unless ($thisfn) {
1.620     albertel 7561:         if ($env{'request.symb'}) {
                   7562: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7563: 	}
1.620     albertel 7564: 	$thisfn=$env{'request.filename'};
1.44      www      7565:     }
1.569     albertel 7566:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7567: # is that filename actually a symb? Verify, clean, and return
                   7568:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7569: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7570: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7571: 	}
1.242     www      7572:     }
1.44      www      7573:     $thisfn=declutter($thisfn);
1.31      www      7574:     my %hash;
1.37      www      7575:     my %bighash;
                   7576:     my $syval='';
1.620     albertel 7577:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7578:         my $targetfn = $thisfn;
1.609     banghart 7579:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7580:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7581:         }
1.687     albertel 7582: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7583: 	    $targetfn=$1;
                   7584: 	}
1.620     albertel 7585:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7586:                       &GDBM_READER(),0640)) {
1.481     raeburn  7587: 	    $syval=$hash{$targetfn};
1.37      www      7588:             untie(%hash);
                   7589:         }
                   7590: # ---------------------------------------------------------- There was an entry
                   7591:         if ($syval) {
1.601     albertel 7592: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7593: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7594: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7595: 		    #return $env{$cache_str}='';
1.601     albertel 7596: 		#}    
                   7597: 		#$syval.=$1;
                   7598: 	    #}
1.37      www      7599:         } else {
                   7600: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7601:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7602:                             &GDBM_READER(),0640)) {
1.37      www      7603: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7604:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7605:               unless ($ids) { 
                   7606:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7607:               }
                   7608:               unless ($ids) {
                   7609: # alias?
                   7610: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7611:               }
1.37      www      7612:               if ($ids) {
                   7613: # ------------------------------------------------------------------- Has ID(s)
                   7614:                  my @possibilities=split(/\,/,$ids);
1.39      www      7615:                  if ($#possibilities==0) {
                   7616: # ----------------------------------------------- There is only one possibility
1.37      www      7617: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7618: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7619: 						    $resid,$thisfn);
1.249     www      7620:                  } elsif (!$donotrecurse) {
1.39      www      7621: # ------------------------------------------ There is more than one possibility
                   7622:                      my $realpossible=0;
1.800     albertel 7623:                      foreach my $id (@possibilities) {
                   7624: 			 my $file=$bighash{'src_'.$id};
1.39      www      7625:                          if (&allowed('bre',$file)) {
1.800     albertel 7626:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7627:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7628: 				$realpossible++;
1.626     albertel 7629:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7630: 						    $resid,$thisfn);
1.39      www      7631:                             }
                   7632: 			 }
1.191     harris41 7633:                      }
1.39      www      7634: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7635:                  } else {
                   7636:                      $syval='';
1.37      www      7637:                  }
                   7638: 	      }
                   7639:               untie(%bighash)
1.481     raeburn  7640:            }
1.31      www      7641:         }
1.62      www      7642:         if ($syval) {
1.620     albertel 7643: 	    return $env{$cache_str}=$syval;
1.62      www      7644:         }
1.31      www      7645:     }
1.949     raeburn  7646:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7647:     return $env{$cache_str}='';
1.31      www      7648: }
                   7649: 
                   7650: # ---------------------------------------------------------- Return random seed
                   7651: 
1.32      www      7652: sub numval {
                   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;
1.564     albertel 7661:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7662:     return int($txt);
1.368     albertel 7663: }
                   7664: 
1.484     albertel 7665: sub numval2 {
                   7666:     my $txt=shift;
                   7667:     $txt=~tr/A-J/0-9/;
                   7668:     $txt=~tr/a-j/0-9/;
                   7669:     $txt=~tr/K-T/0-9/;
                   7670:     $txt=~tr/k-t/0-9/;
                   7671:     $txt=~tr/U-Z/0-5/;
                   7672:     $txt=~tr/u-z/0-5/;
                   7673:     $txt=~s/\D//g;
                   7674:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7675:     my $total;
                   7676:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7677:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7678:     return int($total);
                   7679: }
                   7680: 
1.575     albertel 7681: sub numval3 {
                   7682:     use integer;
                   7683:     my $txt=shift;
                   7684:     $txt=~tr/A-J/0-9/;
                   7685:     $txt=~tr/a-j/0-9/;
                   7686:     $txt=~tr/K-T/0-9/;
                   7687:     $txt=~tr/k-t/0-9/;
                   7688:     $txt=~tr/U-Z/0-5/;
                   7689:     $txt=~tr/u-z/0-5/;
                   7690:     $txt=~s/\D//g;
                   7691:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7692:     my $total;
                   7693:     foreach my $val (@txts) { $total+=$val; }
                   7694:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7695:     return $total;
                   7696: }
                   7697: 
1.675     albertel 7698: sub digest {
                   7699:     my ($data)=@_;
                   7700:     my $digest=&Digest::MD5::md5($data);
                   7701:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7702:     my ($e,$f);
                   7703:     {
                   7704:         use integer;
                   7705:         $e=($a+$b);
                   7706:         $f=($c+$d);
                   7707:         if ($_64bit) {
                   7708:             $e=(($e<<32)>>32);
                   7709:             $f=(($f<<32)>>32);
                   7710:         }
                   7711:     }
                   7712:     if (wantarray) {
                   7713: 	return ($e,$f);
                   7714:     } else {
                   7715: 	my $g;
                   7716: 	{
                   7717: 	    use integer;
                   7718: 	    $g=($e+$f);
                   7719: 	    if ($_64bit) {
                   7720: 		$g=(($g<<32)>>32);
                   7721: 	    }
                   7722: 	}
                   7723: 	return $g;
                   7724:     }
                   7725: }
                   7726: 
1.368     albertel 7727: sub latest_rnd_algorithm_id {
1.675     albertel 7728:     return '64bit5';
1.366     albertel 7729: }
1.32      www      7730: 
1.503     albertel 7731: sub get_rand_alg {
                   7732:     my ($courseid)=@_;
1.790     albertel 7733:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7734:     if ($courseid) {
1.620     albertel 7735: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7736:     }
                   7737:     return &latest_rnd_algorithm_id();
                   7738: }
                   7739: 
1.562     albertel 7740: sub validCODE {
                   7741:     my ($CODE)=@_;
                   7742:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7743:     return 0;
                   7744: }
                   7745: 
1.491     albertel 7746: sub getCODE {
1.620     albertel 7747:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7748:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7749: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7750: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7751: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7752:     }
                   7753:     return undef;
                   7754: }
                   7755: 
1.31      www      7756: sub rndseed {
1.155     albertel 7757:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7758:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7759:     if (!defined($symb)) {
1.366     albertel 7760: 	unless ($symb=$wsymb) { return time; }
                   7761:     }
                   7762:     if (!$courseid) { $courseid=$wcourseid; }
                   7763:     if (!$domain) { $domain=$wdomain; }
                   7764:     if (!$username) { $username=$wusername }
1.503     albertel 7765:     my $which=&get_rand_alg();
1.803     albertel 7766: 
1.491     albertel 7767:     if (defined(&getCODE())) {
1.675     albertel 7768: 	if ($which eq '64bit5') {
                   7769: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7770: 	} elsif ($which eq '64bit4') {
1.575     albertel 7771: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7772: 	} else {
                   7773: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7774: 	}
1.675     albertel 7775:     } elsif ($which eq '64bit5') {
                   7776: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7777:     } elsif ($which eq '64bit4') {
                   7778: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7779:     } elsif ($which eq '64bit3') {
                   7780: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7781:     } elsif ($which eq '64bit2') {
                   7782: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7783:     } elsif ($which eq '64bit') {
                   7784: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7785:     }
                   7786:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7787: }
                   7788: 
                   7789: sub rndseed_32bit {
                   7790:     my ($symb,$courseid,$domain,$username)=@_;
                   7791:     {
                   7792: 	use integer;
                   7793: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7794: 	my $symbseed=numval($symb) << 22;
                   7795: 	my $namechck=unpack("%32C*",$username) << 17;
                   7796: 	my $nameseed=numval($username) << 12;
                   7797: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7798: 	my $courseseed=unpack("%32C*",$courseid);
                   7799: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7800: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7801: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7802: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7803: 	return $num;
                   7804:     }
                   7805: }
                   7806: 
                   7807: sub rndseed_64bit {
                   7808:     my ($symb,$courseid,$domain,$username)=@_;
                   7809:     {
                   7810: 	use integer;
                   7811: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7812: 	my $symbseed=numval($symb) << 10;
                   7813: 	my $namechck=unpack("%32S*",$username);
                   7814: 	
                   7815: 	my $nameseed=numval($username) << 21;
                   7816: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7817: 	my $courseseed=unpack("%32S*",$courseid);
                   7818: 	
                   7819: 	my $num1=$symbchck+$symbseed+$namechck;
                   7820: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7821: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7822: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7823: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7824: 	return "$num1,$num2";
1.155     albertel 7825:     }
1.366     albertel 7826: }
                   7827: 
1.443     albertel 7828: sub rndseed_64bit2 {
                   7829:     my ($symb,$courseid,$domain,$username)=@_;
                   7830:     {
                   7831: 	use integer;
                   7832: 	# strings need to be an even # of cahracters long, it it is odd the
                   7833:         # last characters gets thrown away
                   7834: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7835: 	my $symbseed=numval($symb) << 10;
                   7836: 	my $namechck=unpack("%32S*",$username.' ');
                   7837: 	
                   7838: 	my $nameseed=numval($username) << 21;
1.501     albertel 7839: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7840: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7841: 	
                   7842: 	my $num1=$symbchck+$symbseed+$namechck;
                   7843: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7844: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7845: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7846: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7847: 	return "$num1,$num2";
                   7848:     }
                   7849: }
                   7850: 
                   7851: sub rndseed_64bit3 {
                   7852:     my ($symb,$courseid,$domain,$username)=@_;
                   7853:     {
                   7854: 	use integer;
                   7855: 	# strings need to be an even # of cahracters long, it it is odd the
                   7856:         # last characters gets thrown away
                   7857: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7858: 	my $symbseed=numval2($symb) << 10;
                   7859: 	my $namechck=unpack("%32S*",$username.' ');
                   7860: 	
                   7861: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7862: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7863: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7864: 	
                   7865: 	my $num1=$symbchck+$symbseed+$namechck;
                   7866: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7867: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7868: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7869: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7870: 	
1.503     albertel 7871: 	return "$num1:$num2";
1.443     albertel 7872:     }
                   7873: }
                   7874: 
1.575     albertel 7875: sub rndseed_64bit4 {
                   7876:     my ($symb,$courseid,$domain,$username)=@_;
                   7877:     {
                   7878: 	use integer;
                   7879: 	# strings need to be an even # of cahracters long, it it is odd the
                   7880:         # last characters gets thrown away
                   7881: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7882: 	my $symbseed=numval3($symb) << 10;
                   7883: 	my $namechck=unpack("%32S*",$username.' ');
                   7884: 	
                   7885: 	my $nameseed=numval3($username) << 21;
                   7886: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7887: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7888: 	
                   7889: 	my $num1=$symbchck+$symbseed+$namechck;
                   7890: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7891: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7892: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7893: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7894: 	
                   7895: 	return "$num1:$num2";
                   7896:     }
                   7897: }
                   7898: 
1.675     albertel 7899: sub rndseed_64bit5 {
                   7900:     my ($symb,$courseid,$domain,$username)=@_;
                   7901:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7902:     return "$num1:$num2";
                   7903: }
                   7904: 
1.366     albertel 7905: sub rndseed_CODE_64bit {
                   7906:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7907:     {
1.366     albertel 7908: 	use integer;
1.443     albertel 7909: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7910: 	my $symbseed=numval2($symb);
1.491     albertel 7911: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7912: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7913: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7914: 	my $num1=$symbseed+$CODEchck;
                   7915: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7916: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7917: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7918: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7919: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7920: 	return "$num1:$num2";
1.366     albertel 7921:     }
                   7922: }
                   7923: 
1.575     albertel 7924: sub rndseed_CODE_64bit4 {
                   7925:     my ($symb,$courseid,$domain,$username)=@_;
                   7926:     {
                   7927: 	use integer;
                   7928: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7929: 	my $symbseed=numval3($symb);
                   7930: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7931: 	my $CODEseed=numval3(&getCODE());
                   7932: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7933: 	my $num1=$symbseed+$CODEchck;
                   7934: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7935: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7936: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7937: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7938: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7939: 	return "$num1:$num2";
                   7940:     }
                   7941: }
                   7942: 
1.675     albertel 7943: sub rndseed_CODE_64bit5 {
                   7944:     my ($symb,$courseid,$domain,$username)=@_;
                   7945:     my $code = &getCODE();
                   7946:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7947:     return "$num1:$num2";
                   7948: }
                   7949: 
1.366     albertel 7950: sub setup_random_from_rndseed {
                   7951:     my ($rndseed)=@_;
1.503     albertel 7952:     if ($rndseed =~/([,:])/) {
                   7953: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7954: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7955:     } else {
                   7956: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7957:     }
1.36      albertel 7958: }
                   7959: 
1.474     albertel 7960: sub latest_receipt_algorithm_id {
1.835     albertel 7961:     return 'receipt3';
1.474     albertel 7962: }
                   7963: 
1.480     www      7964: sub recunique {
                   7965:     my $fucourseid=shift;
                   7966:     my $unique;
1.835     albertel 7967:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7968: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7969: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7970:     } else {
                   7971: 	$unique=$perlvar{'lonReceipt'};
                   7972:     }
                   7973:     return unpack("%32C*",$unique);
                   7974: }
                   7975: 
                   7976: sub recprefix {
                   7977:     my $fucourseid=shift;
                   7978:     my $prefix;
1.835     albertel 7979:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7980: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7981: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7982:     } else {
                   7983: 	$prefix=$perlvar{'lonHostID'};
                   7984:     }
                   7985:     return unpack("%32C*",$prefix);
                   7986: }
                   7987: 
1.76      www      7988: sub ireceipt {
1.474     albertel 7989:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7990: 
                   7991:     my $return =&recprefix($fucourseid).'-';
                   7992: 
                   7993:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7994: 	$env{'request.state'} eq 'construct') {
                   7995: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7996: 	return $return;
                   7997:     }
                   7998: 
1.76      www      7999:     my $cuname=unpack("%32C*",$funame);
                   8000:     my $cudom=unpack("%32C*",$fudom);
                   8001:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8002:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8003:     my $cunique=&recunique($fucourseid);
1.474     albertel 8004:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8005:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8006: 
1.790     albertel 8007: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8008: 			       
                   8009: 	$return.= ($cunique%$cuname+
                   8010: 		   $cunique%$cudom+
                   8011: 		   $cusymb%$cuname+
                   8012: 		   $cusymb%$cudom+
                   8013: 		   $cucourseid%$cuname+
                   8014: 		   $cucourseid%$cudom+
                   8015: 		   $cpart%$cuname+
                   8016: 		   $cpart%$cudom);
                   8017:     } else {
                   8018: 	$return.= ($cunique%$cuname+
                   8019: 		   $cunique%$cudom+
                   8020: 		   $cusymb%$cuname+
                   8021: 		   $cusymb%$cudom+
                   8022: 		   $cucourseid%$cuname+
                   8023: 		   $cucourseid%$cudom);
                   8024:     }
                   8025:     return $return;
1.76      www      8026: }
                   8027: 
                   8028: sub receipt {
1.474     albertel 8029:     my ($part)=@_;
1.790     albertel 8030:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8031:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8032: }
1.260     ng       8033: 
1.790     albertel 8034: sub whichuser {
                   8035:     my ($passedsymb)=@_;
                   8036:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8037:     if (defined($env{'form.grade_symb'})) {
                   8038: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8039: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8040: 	if (!$allowed &&
                   8041: 	    exists($env{'request.course.sec'}) &&
                   8042: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8043: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8044: 			      '/'.$env{'request.course.sec'});
                   8045: 	}
                   8046: 	if ($allowed) {
                   8047: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8048: 	    $courseid=$tmp_courseid;
                   8049: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8050: 	    ($name)=&get_env_multiple('form.grade_username');
                   8051: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8052: 	}
                   8053:     }
                   8054:     if (!$passedsymb) {
                   8055: 	$symb=&symbread();
                   8056:     } else {
                   8057: 	$symb=$passedsymb;
                   8058:     }
                   8059:     $courseid=$env{'request.course.id'};
                   8060:     $domain=$env{'user.domain'};
                   8061:     $name=$env{'user.name'};
                   8062:     if ($name eq 'public' && $domain eq 'public') {
                   8063: 	if (!defined($env{'form.username'})) {
                   8064: 	    $env{'form.username'}.=time.rand(10000000);
                   8065: 	}
                   8066: 	$name.=$env{'form.username'};
                   8067:     }
                   8068:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8069: 
                   8070: }
                   8071: 
1.36      albertel 8072: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8073: # returns either the contents of the file or 
                   8074: # -1 if the file doesn't exist
1.481     raeburn  8075: #
                   8076: # if the target is a file that was uploaded via DOCS, 
                   8077: # a check will be made to see if a current copy exists on the local server,
                   8078: # if it does this will be served, otherwise a copy will be retrieved from
                   8079: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8080: # the local server.   
1.472     albertel 8081: 
1.36      albertel 8082: sub getfile {
1.538     albertel 8083:     my ($file) = @_;
1.609     banghart 8084:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8085:     &repcopy($file);
                   8086:     return &readfile($file);
                   8087: }
                   8088: 
                   8089: sub repcopy_userfile {
                   8090:     my ($file)=@_;
1.609     banghart 8091:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8092:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8093:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8094: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8095:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8096:     if (-e "$file") {
1.828     www      8097: # we already have a local copy, check it out
1.538     albertel 8098: 	my @fileinfo = stat($file);
1.828     www      8099: 	my $rtncode;
                   8100: 	my $info;
1.538     albertel 8101: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8102: 	if ($lwpresp ne 'ok') {
1.828     www      8103: # there is no such file anymore, even though we had a local copy
1.482     albertel 8104: 	    if ($rtncode eq '404') {
1.538     albertel 8105: 		unlink($file);
1.482     albertel 8106: 	    }
                   8107: 	    return -1;
                   8108: 	}
                   8109: 	if ($info < $fileinfo[9]) {
1.828     www      8110: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8111: 	    return 'ok';
1.828     www      8112: 	} else {
                   8113: # the file is outdated, get rid of it
                   8114: 	    unlink($file);
1.482     albertel 8115: 	}
1.828     www      8116:     }
                   8117: # one way or the other, at this point, we don't have the file
                   8118: # construct the correct path for the file
                   8119:     my @parts = ($cdom,$cnum); 
                   8120:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8121: 	push @parts, split(/\//,$1);
                   8122:     }
                   8123:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8124:     foreach my $part (@parts) {
                   8125: 	$path .= '/'.$part;
                   8126: 	if (!-e $path) {
                   8127: 	    mkdir($path,0770);
1.482     albertel 8128: 	}
                   8129:     }
1.828     www      8130: # now the path exists for sure
                   8131: # get a user agent
                   8132:     my $ua=new LWP::UserAgent;
                   8133:     my $transferfile=$file.'.in.transfer';
                   8134: # FIXME: this should flock
                   8135:     if (-e $transferfile) { return 'ok'; }
                   8136:     my $request;
                   8137:     $uri=~s/^\///;
1.838     albertel 8138:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8139:     my $response=$ua->request($request,$transferfile);
                   8140: # did it work?
                   8141:     if ($response->is_error()) {
                   8142: 	unlink($transferfile);
                   8143: 	&logthis("Userfile repcopy failed for $uri");
                   8144: 	return -1;
                   8145:     }
                   8146: # worked, rename the transfer file
                   8147:     rename($transferfile,$file);
1.607     raeburn  8148:     return 'ok';
1.481     raeburn  8149: }
                   8150: 
1.517     albertel 8151: sub tokenwrapper {
                   8152:     my $uri=shift;
1.552     albertel 8153:     $uri=~s|^http\://([^/]+)||;
                   8154:     $uri=~s|^/||;
1.620     albertel 8155:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8156:     my $token=$1;
1.552     albertel 8157:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8158:     if ($udom && $uname && $file) {
                   8159: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8160:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8161:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8162:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8163:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8164:     } else {
                   8165:         return '/adm/notfound.html';
                   8166:     }
                   8167: }
                   8168: 
1.828     www      8169: # call with reqtype HEAD: get last modification time
                   8170: # call with reqtype GET: get the file contents
                   8171: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8172: #
1.481     raeburn  8173: sub getuploaded {
                   8174:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8175:     $uri=~s/^\///;
1.838     albertel 8176:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8177:     my $ua=new LWP::UserAgent;
                   8178:     my $request=new HTTP::Request($reqtype,$uri);
                   8179:     my $response=$ua->request($request);
                   8180:     $$rtncode = $response->code;
1.482     albertel 8181:     if (! $response->is_success()) {
                   8182: 	return 'failed';
                   8183:     }      
                   8184:     if ($reqtype eq 'HEAD') {
1.486     www      8185: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8186:     } elsif ($reqtype eq 'GET') {
                   8187: 	$$info = $response->content;
1.472     albertel 8188:     }
1.482     albertel 8189:     return 'ok';
1.36      albertel 8190: }
                   8191: 
1.481     raeburn  8192: sub readfile {
                   8193:     my $file = shift;
                   8194:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8195:     my $fh;
                   8196:     open($fh,"<$file");
                   8197:     my $a='';
1.800     albertel 8198:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8199:     return $a;
                   8200: }
                   8201: 
1.36      albertel 8202: sub filelocation {
1.590     banghart 8203:     my ($dir,$file) = @_;
                   8204:     my $location;
                   8205:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8206: 
                   8207:     if ($file =~ m-^/adm/-) {
                   8208: 	$file=~s-^/adm/wrapper/-/-;
                   8209: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8210:     }
1.882     albertel 8211: 
1.590     banghart 8212:     if ($file=~m:^/~:) { # is a contruction space reference
                   8213:         $location = $file;
                   8214:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8215:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8216: 	# is a correct contruction space reference
                   8217:         $location = $file;
1.956     raeburn  8218:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8219:         $location = $file;
1.609     banghart 8220:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8221:         my ($udom,$uname,$filename)=
1.811     albertel 8222:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8223:         my $home=&homeserver($uname,$udom);
                   8224:         my $is_me=0;
                   8225:         my @ids=&current_machine_ids();
                   8226:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8227:         if ($is_me) {
1.955     raeburn  8228:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8229:         } else {
                   8230:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8231:   	      $udom.'/'.$uname.'/'.$filename;
                   8232:         }
1.882     albertel 8233:     } elsif ($file =~ m-^/adm/-) {
                   8234: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8235:     } else {
                   8236:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8237:         $file=~s:^/res/:/:;
                   8238:         if ( !( $file =~ m:^/:) ) {
                   8239:             $location = $dir. '/'.$file;
                   8240:         } else {
                   8241:             $location = '/home/httpd/html/res'.$file;
                   8242:         }
1.59      albertel 8243:     }
1.590     banghart 8244:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8245:     while ($location=~m{/\.\./}) {
                   8246: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8247: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8248: 	} else {
                   8249: 	    $location=~ s{/\.\./}{/}g;
                   8250: 	}
                   8251:     } #remove dir/..
1.590     banghart 8252:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8253:     return $location;
1.46      www      8254: }
1.36      albertel 8255: 
1.46      www      8256: sub hreflocation {
                   8257:     my ($dir,$file)=@_;
1.460     albertel 8258:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8259: 	$file=filelocation($dir,$file);
1.700     albertel 8260:     } elsif ($file=~m-^/adm/-) {
                   8261: 	$file=~s-^/adm/wrapper/-/-;
                   8262: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8263:     }
                   8264:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8265: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8266:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8267: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8268:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8269: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8270: 	    -/uploaded/$1/$2/-x;
1.46      www      8271:     }
1.913     albertel 8272:     if ($file=~ m{^/userfiles/}) {
                   8273: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8274:     }
1.462     albertel 8275:     return $file;
1.465     albertel 8276: }
                   8277: 
                   8278: sub current_machine_domains {
1.853     albertel 8279:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8280: }
                   8281: 
                   8282: sub machine_domains {
                   8283:     my ($hostname) = @_;
1.465     albertel 8284:     my @domains;
1.838     albertel 8285:     my %hostname = &all_hostnames();
1.465     albertel 8286:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8287: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8288: 	if ($hostname eq $name) {
1.844     albertel 8289: 	    push(@domains,&host_domain($id));
1.465     albertel 8290: 	}
                   8291:     }
                   8292:     return @domains;
                   8293: }
                   8294: 
                   8295: sub current_machine_ids {
1.853     albertel 8296:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8297: }
                   8298: 
                   8299: sub machine_ids {
                   8300:     my ($hostname) = @_;
                   8301:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8302:     my @ids;
1.888     albertel 8303:     my %name_to_host = &all_names();
1.889     albertel 8304:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8305: 	return @{ $name_to_host{$hostname} };
                   8306:     }
                   8307:     return;
1.31      www      8308: }
                   8309: 
1.824     raeburn  8310: sub additional_machine_domains {
                   8311:     my @domains;
                   8312:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8313:     while( my $line = <$fh>) {
                   8314:         $line =~ s/\s//g;
                   8315:         push(@domains,$line);
                   8316:     }
                   8317:     return @domains;
                   8318: }
                   8319: 
                   8320: sub default_login_domain {
                   8321:     my $domain = $perlvar{'lonDefDomain'};
                   8322:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8323:     foreach my $posdom (&current_machine_domains(),
                   8324:                         &additional_machine_domains()) {
                   8325:         if (lc($posdom) eq lc($testdomain)) {
                   8326:             $domain=$posdom;
                   8327:             last;
                   8328:         }
                   8329:     }
                   8330:     return $domain;
                   8331: }
                   8332: 
1.31      www      8333: # ------------------------------------------------------------- Declutters URLs
                   8334: 
                   8335: sub declutter {
                   8336:     my $thisfn=shift;
1.569     albertel 8337:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8338:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8339:     $thisfn=~s/^\///;
1.697     albertel 8340:     $thisfn=~s|^adm/wrapper/||;
                   8341:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8342:     $thisfn=~s/^res\///;
1.235     www      8343:     $thisfn=~s/\?.+$//;
1.268     www      8344:     return $thisfn;
                   8345: }
                   8346: 
                   8347: # ------------------------------------------------------------- Clutter up URLs
                   8348: 
                   8349: sub clutter {
                   8350:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8351:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8352: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8353:        $thisfn='/res'.$thisfn; 
                   8354:     }
1.694     albertel 8355:     if ($thisfn !~m|/adm|) {
1.695     albertel 8356: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8357: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8358: 	} else {
                   8359: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8360: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8361: 	    if ($embstyle eq 'ssi'
                   8362: 		|| ($embstyle eq 'hdn')
                   8363: 		|| ($embstyle eq 'rat')
                   8364: 		|| ($embstyle eq 'prv')
                   8365: 		|| ($embstyle eq 'ign')) {
                   8366: 		#do nothing with these
                   8367: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8368: 		|| ($embstyle eq 'emb')
                   8369: 		|| ($embstyle eq 'wrp')) {
                   8370: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8371: 	    } elsif ($embstyle eq 'unk'
                   8372: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8373: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8374: 	    } else {
1.718     www      8375: #		&logthis("Got a blank emb style");
1.695     albertel 8376: 	    }
1.694     albertel 8377: 	}
                   8378:     }
1.31      www      8379:     return $thisfn;
1.12      www      8380: }
                   8381: 
1.787     albertel 8382: sub clutter_with_no_wrapper {
                   8383:     my $uri = &clutter(shift);
                   8384:     if ($uri =~ m-^/adm/-) {
                   8385: 	$uri =~ s-^/adm/wrapper/-/-;
                   8386: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8387:     }
                   8388:     return $uri;
                   8389: }
                   8390: 
1.557     albertel 8391: sub freeze_escape {
                   8392:     my ($value)=@_;
                   8393:     if (ref($value)) {
                   8394: 	$value=&nfreeze($value);
                   8395: 	return '__FROZEN__'.&escape($value);
                   8396:     }
                   8397:     return &escape($value);
                   8398: }
                   8399: 
1.11      www      8400: 
1.557     albertel 8401: sub thaw_unescape {
                   8402:     my ($value)=@_;
                   8403:     if ($value =~ /^__FROZEN__/) {
                   8404: 	substr($value,0,10,undef);
                   8405: 	$value=&unescape($value);
                   8406: 	return &thaw($value);
                   8407:     }
                   8408:     return &unescape($value);
                   8409: }
                   8410: 
1.436     albertel 8411: sub correct_line_ends {
                   8412:     my ($result)=@_;
                   8413:     $$result =~s/\r\n/\n/mg;
                   8414:     $$result =~s/\r/\n/mg;
1.415     albertel 8415: }
1.1       albertel 8416: # ================================================================ Main Program
                   8417: 
1.184     www      8418: sub goodbye {
1.204     albertel 8419:    &logthis("Starting Shut down");
1.443     albertel 8420: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8421:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8422: #converted
1.599     albertel 8423: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8424:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8425: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8426: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8427: #1.1 only
1.870     albertel 8428: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8429: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8430: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8431: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8432:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8433:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8434:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8435:    &flushcourselogs();
                   8436:    &logthis("Shutting down");
                   8437: }
                   8438: 
1.852     albertel 8439: sub get_dns {
1.869     albertel 8440:     my ($url,$func,$ignore_cache) = @_;
                   8441:     if (!$ignore_cache) {
                   8442: 	my ($content,$cached)=
                   8443: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8444: 	if ($cached) {
                   8445: 	    &$func($content);
                   8446: 	    return;
                   8447: 	}
                   8448:     }
                   8449: 
                   8450:     my %alldns;
1.852     albertel 8451:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8452:     foreach my $dns (<$config>) {
                   8453: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8454: 	$alldns{$1} = 1;
                   8455:     }
                   8456:     while (%alldns) {
                   8457: 	my ($dns) = keys(%alldns);
                   8458: 	delete($alldns{$dns});
1.852     albertel 8459: 	my $ua=new LWP::UserAgent;
                   8460: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8461: 	my $response=$ua->request($request);
                   8462: 	next if ($response->is_error());
                   8463: 	my @content = split("\n",$response->content);
1.869     albertel 8464: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8465: 	&$func(\@content);
1.869     albertel 8466: 	return;
1.852     albertel 8467:     }
                   8468:     close($config);
1.871     albertel 8469:     my $which = (split('/',$url))[3];
                   8470:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8471:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8472:     my @content = <$config>;
                   8473:     &$func(\@content);
                   8474:     return;
1.852     albertel 8475: }
1.327     albertel 8476: # ------------------------------------------------------------ Read domain file
                   8477: {
1.852     albertel 8478:     my $loaded;
1.846     albertel 8479:     my %domain;
                   8480: 
1.852     albertel 8481:     sub parse_domain_tab {
                   8482: 	my ($lines) = @_;
                   8483: 	foreach my $line (@$lines) {
                   8484: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8485: 
1.846     albertel 8486: 	    chomp($line);
1.852     albertel 8487: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8488: 	    my %this_domain;
                   8489: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8490: 			       'lang_def', 'city', 'longi', 'lati',
                   8491: 			       'primary') {
                   8492: 		$this_domain{$field} = shift(@elements);
                   8493: 	    }
                   8494: 	    $domain{$name} = \%this_domain;
1.852     albertel 8495: 	}
                   8496:     }
1.864     albertel 8497: 
                   8498:     sub reset_domain_info {
                   8499: 	undef($loaded);
                   8500: 	undef(%domain);
                   8501:     }
                   8502: 
1.852     albertel 8503:     sub load_domain_tab {
1.869     albertel 8504: 	my ($ignore_cache) = @_;
                   8505: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8506: 	my $fh;
                   8507: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8508: 	    my @lines = <$fh>;
                   8509: 	    &parse_domain_tab(\@lines);
1.448     albertel 8510: 	}
1.852     albertel 8511: 	close($fh);
                   8512: 	$loaded = 1;
1.327     albertel 8513:     }
1.846     albertel 8514: 
                   8515:     sub domain {
1.852     albertel 8516: 	&load_domain_tab() if (!$loaded);
                   8517: 
1.846     albertel 8518: 	my ($name,$what) = @_;
                   8519: 	return if ( !exists($domain{$name}) );
                   8520: 
                   8521: 	if (!$what) {
                   8522: 	    return $domain{$name}{'description'};
                   8523: 	}
                   8524: 	return $domain{$name}{$what};
                   8525:     }
1.327     albertel 8526: }
                   8527: 
                   8528: 
1.1       albertel 8529: # ------------------------------------------------------------- Read hosts file
                   8530: {
1.838     albertel 8531:     my %hostname;
1.844     albertel 8532:     my %hostdom;
1.845     albertel 8533:     my %libserv;
1.852     albertel 8534:     my $loaded;
1.888     albertel 8535:     my %name_to_host;
1.852     albertel 8536: 
                   8537:     sub parse_hosts_tab {
                   8538: 	my ($file) = @_;
                   8539: 	foreach my $configline (@$file) {
                   8540: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8541: 	    next if ($configline =~ /^\^/);
                   8542: 	    chomp($configline);
1.968     raeburn  8543: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8544: 	    $name=~s/\s//g;
                   8545: 	    if ($id && $domain && $role && $name) {
                   8546: 		$hostname{$id}=$name;
1.888     albertel 8547: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8548: 		$hostdom{$id}=$domain;
                   8549: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969   ! raeburn  8550:                 if (defined($protocol)) {
        !          8551:                     if ($protocol eq 'https') {
        !          8552:                         $protocol{$id} = $protocol;
        !          8553:                     } else {
        !          8554:                         $protocol{$id} = 'http'; 
        !          8555:                     }
1.968     raeburn  8556:                 } else {
1.969   ! raeburn  8557:                     $protocol{$id} = 'http';
1.968     raeburn  8558:                 }
1.852     albertel 8559: 	    }
                   8560: 	}
                   8561:     }
1.864     albertel 8562:     
                   8563:     sub reset_hosts_info {
1.897     albertel 8564: 	&purge_remembered();
1.864     albertel 8565: 	&reset_domain_info();
                   8566: 	&reset_hosts_ip_info();
1.892     albertel 8567: 	undef(%name_to_host);
1.864     albertel 8568: 	undef(%hostname);
                   8569: 	undef(%hostdom);
                   8570: 	undef(%libserv);
                   8571: 	undef($loaded);
                   8572:     }
1.1       albertel 8573: 
1.852     albertel 8574:     sub load_hosts_tab {
1.869     albertel 8575: 	my ($ignore_cache) = @_;
                   8576: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8577: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8578: 	my @config = <$config>;
                   8579: 	&parse_hosts_tab(\@config);
                   8580: 	close($config);
                   8581: 	$loaded=1;
1.1       albertel 8582:     }
1.852     albertel 8583: 
1.838     albertel 8584:     sub hostname {
1.852     albertel 8585: 	&load_hosts_tab() if (!$loaded);
                   8586: 
1.838     albertel 8587: 	my ($lonid) = @_;
                   8588: 	return $hostname{$lonid};
                   8589:     }
1.845     albertel 8590: 
1.838     albertel 8591:     sub all_hostnames {
1.852     albertel 8592: 	&load_hosts_tab() if (!$loaded);
                   8593: 
1.838     albertel 8594: 	return %hostname;
                   8595:     }
1.845     albertel 8596: 
1.888     albertel 8597:     sub all_names {
                   8598: 	&load_hosts_tab() if (!$loaded);
                   8599: 
                   8600: 	return %name_to_host;
                   8601:     }
                   8602: 
1.845     albertel 8603:     sub is_library {
1.852     albertel 8604: 	&load_hosts_tab() if (!$loaded);
                   8605: 
1.845     albertel 8606: 	return exists($libserv{$_[0]});
                   8607:     }
                   8608: 
                   8609:     sub all_library {
1.852     albertel 8610: 	&load_hosts_tab() if (!$loaded);
                   8611: 
1.845     albertel 8612: 	return %libserv;
                   8613:     }
                   8614: 
1.841     albertel 8615:     sub get_servers {
1.852     albertel 8616: 	&load_hosts_tab() if (!$loaded);
                   8617: 
1.841     albertel 8618: 	my ($domain,$type) = @_;
                   8619: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8620: 	                                          : %hostname;
                   8621: 	my %result;
1.842     albertel 8622: 	if (ref($domain) eq 'ARRAY') {
                   8623: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8624: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8625: 		    $result{$host} = $hostname;
                   8626: 		}
                   8627: 	    }
                   8628: 	} else {
                   8629: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8630: 		if ($hostdom{$host} eq $domain) {
                   8631: 		    $result{$host} = $hostname;
                   8632: 		}
1.841     albertel 8633: 	    }
                   8634: 	}
                   8635: 	return %result;
                   8636:     }
1.845     albertel 8637: 
1.844     albertel 8638:     sub host_domain {
1.852     albertel 8639: 	&load_hosts_tab() if (!$loaded);
                   8640: 
1.844     albertel 8641: 	my ($lonid) = @_;
                   8642: 	return $hostdom{$lonid};
                   8643:     }
                   8644: 
1.841     albertel 8645:     sub all_domains {
1.852     albertel 8646: 	&load_hosts_tab() if (!$loaded);
                   8647: 
1.841     albertel 8648: 	my %seen;
                   8649: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8650: 	return @uniq;
                   8651:     }
1.1       albertel 8652: }
                   8653: 
1.847     albertel 8654: { 
                   8655:     my %iphost;
1.856     albertel 8656:     my %name_to_ip;
                   8657:     my %lonid_to_ip;
1.869     albertel 8658: 
1.847     albertel 8659:     sub get_hosts_from_ip {
                   8660: 	my ($ip) = @_;
                   8661: 	my %iphosts = &get_iphost();
                   8662: 	if (ref($iphosts{$ip})) {
                   8663: 	    return @{$iphosts{$ip}};
                   8664: 	}
                   8665: 	return;
1.839     albertel 8666:     }
1.864     albertel 8667:     
                   8668:     sub reset_hosts_ip_info {
                   8669: 	undef(%iphost);
                   8670: 	undef(%name_to_ip);
                   8671: 	undef(%lonid_to_ip);
                   8672:     }
1.856     albertel 8673: 
                   8674:     sub get_host_ip {
                   8675: 	my ($lonid) = @_;
                   8676: 	if (exists($lonid_to_ip{$lonid})) {
                   8677: 	    return $lonid_to_ip{$lonid};
                   8678: 	}
                   8679: 	my $name=&hostname($lonid);
                   8680:    	my $ip = gethostbyname($name);
                   8681: 	return if (!$ip || length($ip) ne 4);
                   8682: 	$ip=inet_ntoa($ip);
                   8683: 	$name_to_ip{$name}   = $ip;
                   8684: 	$lonid_to_ip{$lonid} = $ip;
                   8685: 	return $ip;
                   8686:     }
1.847     albertel 8687:     
                   8688:     sub get_iphost {
1.869     albertel 8689: 	my ($ignore_cache) = @_;
1.894     albertel 8690: 
1.869     albertel 8691: 	if (!$ignore_cache) {
                   8692: 	    if (%iphost) {
                   8693: 		return %iphost;
                   8694: 	    }
                   8695: 	    my ($ip_info,$cached)=
                   8696: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8697: 	    if ($cached) {
                   8698: 		%iphost      = %{$ip_info->[0]};
                   8699: 		%name_to_ip  = %{$ip_info->[1]};
                   8700: 		%lonid_to_ip = %{$ip_info->[2]};
                   8701: 		return %iphost;
                   8702: 	    }
                   8703: 	}
1.894     albertel 8704: 
                   8705: 	# get yesterday's info for fallback
                   8706: 	my %old_name_to_ip;
                   8707: 	my ($ip_info,$cached)=
                   8708: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8709: 	if ($cached) {
                   8710: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8711: 	}
                   8712: 
1.888     albertel 8713: 	my %name_to_host = &all_names();
                   8714: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8715: 	    my $ip;
                   8716: 	    if (!exists($name_to_ip{$name})) {
                   8717: 		$ip = gethostbyname($name);
                   8718: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8719: 		    if (defined($old_name_to_ip{$name})) {
                   8720: 			$ip = $old_name_to_ip{$name};
                   8721: 			&logthis("Can't find $name defaulting to old $ip");
                   8722: 		    } else {
                   8723: 			&logthis("Name $name no IP found");
                   8724: 			next;
                   8725: 		    }
                   8726: 		} else {
                   8727: 		    $ip=inet_ntoa($ip);
1.847     albertel 8728: 		}
                   8729: 		$name_to_ip{$name} = $ip;
                   8730: 	    } else {
                   8731: 		$ip = $name_to_ip{$name};
1.653     albertel 8732: 	    }
1.888     albertel 8733: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8734: 		$lonid_to_ip{$id} = $ip;
                   8735: 	    }
                   8736: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8737: 	}
1.869     albertel 8738: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8739: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8740: 				      48*60*60);
1.869     albertel 8741: 
1.847     albertel 8742: 	return %iphost;
1.598     albertel 8743:     }
                   8744: }
                   8745: 
1.862     albertel 8746: BEGIN {
                   8747: 
                   8748: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8749:     unless ($readit) {
                   8750: {
                   8751:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8752:     %perlvar = (%perlvar,%{$configvars});
                   8753: }
                   8754: 
                   8755: 
1.1       albertel 8756: # ------------------------------------------------------ Read spare server file
                   8757: {
1.448     albertel 8758:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8759: 
                   8760:     while (my $configline=<$config>) {
                   8761:        chomp($configline);
1.284     matthew  8762:        if ($configline) {
1.784     albertel 8763: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8764: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8765: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8766:        }
                   8767:     }
1.448     albertel 8768:     close($config);
1.1       albertel 8769: }
1.11      www      8770: # ------------------------------------------------------------ Read permissions
                   8771: {
1.448     albertel 8772:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8773: 
                   8774:     while (my $configline=<$config>) {
1.448     albertel 8775: 	chomp($configline);
                   8776: 	if ($configline) {
                   8777: 	    my ($role,$perm)=split(/ /,$configline);
                   8778: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8779: 	}
1.11      www      8780:     }
1.448     albertel 8781:     close($config);
1.11      www      8782: }
                   8783: 
                   8784: # -------------------------------------------- Read plain texts for permissions
                   8785: {
1.448     albertel 8786:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8787: 
                   8788:     while (my $configline=<$config>) {
1.448     albertel 8789: 	chomp($configline);
                   8790: 	if ($configline) {
1.742     raeburn  8791: 	    my ($short,@plain)=split(/:/,$configline);
                   8792:             %{$prp{$short}} = ();
                   8793: 	    if (@plain > 0) {
                   8794:                 $prp{$short}{'std'} = $plain[0];
                   8795:                 for (my $i=1; $i<@plain; $i++) {
                   8796:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8797:                 }
                   8798:             }
1.448     albertel 8799: 	}
1.135     www      8800:     }
1.448     albertel 8801:     close($config);
1.135     www      8802: }
                   8803: 
                   8804: # ---------------------------------------------------------- Read package table
                   8805: {
1.448     albertel 8806:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8807: 
                   8808:     while (my $configline=<$config>) {
1.483     albertel 8809: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8810: 	chomp($configline);
                   8811: 	my ($short,$plain)=split(/:/,$configline);
                   8812: 	my ($pack,$name)=split(/\&/,$short);
                   8813: 	if ($plain ne '') {
                   8814: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8815: 	    $packagetab{$short}=$plain; 
                   8816: 	}
1.11      www      8817:     }
1.448     albertel 8818:     close($config);
1.329     matthew  8819: }
                   8820: 
                   8821: # ------------- set up temporary directory
                   8822: {
                   8823:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8824: 
1.11      www      8825: }
                   8826: 
1.794     albertel 8827: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8828: 				'compress_threshold'=> 20_000,
                   8829:  			        });
1.185     www      8830: 
1.281     www      8831: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8832: $dumpcount=0;
1.958     www      8833: $locknum=0;
1.22      www      8834: 
1.163     harris41 8835: &logtouch();
1.672     albertel 8836: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8837: $readit=1;
1.564     albertel 8838:     {
                   8839: 	use integer;
                   8840: 	my $test=(2**32)+1;
1.568     albertel 8841: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8842: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8843:     }
1.195     www      8844: }
1.1       albertel 8845: }
1.179     www      8846: 
1.1       albertel 8847: 1;
1.191     harris41 8848: __END__
                   8849: 
1.243     albertel 8850: =pod
                   8851: 
1.191     harris41 8852: =head1 NAME
                   8853: 
1.243     albertel 8854: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8855: 
                   8856: =head1 SYNOPSIS
                   8857: 
1.243     albertel 8858: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8859: 
                   8860:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8861: 
1.243     albertel 8862: Common parameters:
                   8863: 
                   8864: =over 4
                   8865: 
                   8866: =item *
                   8867: 
                   8868: $uname : an internal username (if $cname expecting a course Id specifically)
                   8869: 
                   8870: =item *
                   8871: 
                   8872: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8873: 
                   8874: =item *
                   8875: 
                   8876: $symb : a resource instance identifier
                   8877: 
                   8878: =item *
                   8879: 
                   8880: $namespace : the name of a .db file that contains the data needed or
                   8881: being set.
                   8882: 
                   8883: =back
                   8884: 
1.394     bowersj2 8885: =head1 OVERVIEW
1.191     harris41 8886: 
1.394     bowersj2 8887: lonnet provides subroutines which interact with the
                   8888: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8889: about classes, users, and resources.
1.243     albertel 8890: 
                   8891: For many of these objects you can also use this to store data about
                   8892: them or modify them in various ways.
1.191     harris41 8893: 
1.394     bowersj2 8894: =head2 Symbs
1.191     harris41 8895: 
1.394     bowersj2 8896: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8897: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8898: map, the resource number of the resource in the map, and the URL of
                   8899: the resource itself. The latter is somewhat redundant, but might help
                   8900: if maps change.
                   8901: 
                   8902: An example is
                   8903: 
                   8904:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8905: 
                   8906: The respective map entry is
                   8907: 
                   8908:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8909:   title="Problem 2">
                   8910:  </resource>
                   8911: 
                   8912: Symbs are used by the random number generator, as well as to store and
                   8913: restore data specific to a certain instance of for example a problem.
                   8914: 
                   8915: =head2 Storing And Retrieving Data
                   8916: 
                   8917: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8918: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8919: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8920: is is the non-critical message twin of cstore. These functions are for
                   8921: handlers to store a perl hash to a user's permanent data space in an
                   8922: easy manner, and to retrieve it again on another call. It is expected
                   8923: that a handler would use this once at the beginning to retrieve data,
                   8924: and then again once at the end to send only the new data back.
                   8925: 
                   8926: The data is stored in the user's data directory on the user's
                   8927: homeserver under the ID of the course.
                   8928: 
                   8929: The hash that is returned by restore will have all of the previous
                   8930: value for all of the elements of the hash.
                   8931: 
                   8932: Example:
                   8933: 
                   8934:  #creating a hash
                   8935:  my %hash;
                   8936:  $hash{'foo'}='bar';
                   8937: 
                   8938:  #storing it
                   8939:  &Apache::lonnet::cstore(\%hash);
                   8940: 
                   8941:  #changing a value
                   8942:  $hash{'foo'}='notbar';
                   8943: 
                   8944:  #adding a new value
                   8945:  $hash{'bar'}='foo';
                   8946:  &Apache::lonnet::cstore(\%hash);
                   8947: 
                   8948:  #retrieving the hash
                   8949:  my %history=&Apache::lonnet::restore();
                   8950: 
                   8951:  #print the hash
                   8952:  foreach my $key (sort(keys(%history))) {
                   8953:    print("\%history{$key} = $history{$key}");
                   8954:  }
                   8955: 
                   8956: Will print out:
1.191     harris41 8957: 
1.394     bowersj2 8958:  %history{1:foo} = bar
                   8959:  %history{1:keys} = foo:timestamp
                   8960:  %history{1:timestamp} = 990455579
                   8961:  %history{2:bar} = foo
                   8962:  %history{2:foo} = notbar
                   8963:  %history{2:keys} = foo:bar:timestamp
                   8964:  %history{2:timestamp} = 990455580
                   8965:  %history{bar} = foo
                   8966:  %history{foo} = notbar
                   8967:  %history{timestamp} = 990455580
                   8968:  %history{version} = 2
                   8969: 
                   8970: Note that the special hash entries C<keys>, C<version> and
                   8971: C<timestamp> were added to the hash. C<version> will be equal to the
                   8972: total number of versions of the data that have been stored. The
                   8973: C<timestamp> attribute will be the UNIX time the hash was
                   8974: stored. C<keys> is available in every historical section to list which
                   8975: keys were added or changed at a specific historical revision of a
                   8976: hash.
                   8977: 
                   8978: B<Warning>: do not store the hash that restore returns directly. This
                   8979: will cause a mess since it will restore the historical keys as if the
                   8980: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8981: 
1.394     bowersj2 8982: Calling convention:
1.191     harris41 8983: 
1.394     bowersj2 8984:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8985:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8986: 
1.394     bowersj2 8987: For more detailed information, see lonnet specific documentation.
1.191     harris41 8988: 
1.394     bowersj2 8989: =head1 RETURN MESSAGES
1.191     harris41 8990: 
1.394     bowersj2 8991: =over 4
1.191     harris41 8992: 
1.394     bowersj2 8993: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8994: 
1.394     bowersj2 8995: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8996: when the connection is brought back up
1.191     harris41 8997: 
1.394     bowersj2 8998: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8999: for later delivery
1.191     harris41 9000: 
1.967     bisitz   9001: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9002: 
1.394     bowersj2 9003: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9004: that was requested
1.191     harris41 9005: 
1.243     albertel 9006: =back
1.191     harris41 9007: 
1.243     albertel 9008: =head1 PUBLIC SUBROUTINES
1.191     harris41 9009: 
1.243     albertel 9010: =head2 Session Environment Functions
1.191     harris41 9011: 
1.243     albertel 9012: =over 4
1.191     harris41 9013: 
1.394     bowersj2 9014: =item * 
                   9015: X<appenv()>
1.949     raeburn  9016: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9017: the user envirnoment file, and will be restored for each access this
1.620     albertel 9018: user makes during this session, also modifies the %env for the current
1.949     raeburn  9019: process. Optional rolesarrayref - if defined contains a reference to an array
                   9020: of roles which are exempt from the restriction on modifying user.role entries 
                   9021: in the user's environment.db and in %env.    
1.191     harris41 9022: 
                   9023: =item *
1.394     bowersj2 9024: X<delenv()>
                   9025: B<delenv($regexp)>: removes all items from the session
                   9026: environment file that matches the regular expression in $regexp. The
1.620     albertel 9027: values are also delted from the current processes %env.
1.191     harris41 9028: 
1.795     albertel 9029: =item * get_env_multiple($name) 
                   9030: 
                   9031: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9032: values may be defined and end up as an array ref.
                   9033: 
                   9034: returns an array of values
                   9035: 
1.243     albertel 9036: =back
                   9037: 
                   9038: =head2 User Information
1.191     harris41 9039: 
1.243     albertel 9040: =over 4
1.191     harris41 9041: 
                   9042: =item *
1.394     bowersj2 9043: X<queryauthenticate()>
                   9044: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9045: authentication scheme
                   9046: 
                   9047: =item *
1.394     bowersj2 9048: X<authenticate()>
                   9049: B<authenticate($uname,$upass,$udom)>: try to
                   9050: authenticate user from domain's lib servers (first use the current
                   9051: one). C<$upass> should be the users password.
1.191     harris41 9052: 
                   9053: =item *
1.394     bowersj2 9054: X<homeserver()>
                   9055: B<homeserver($uname,$udom)>: find the server which has
                   9056: the user's directory and files (there must be only one), this caches
                   9057: the answer, and also caches if there is a borken connection.
1.191     harris41 9058: 
                   9059: =item *
1.394     bowersj2 9060: X<idget()>
                   9061: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9062: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9063: username, and only 1 username per ID in a specific domain) (returns
                   9064: hash: id=>name,id=>name)
1.191     harris41 9065: 
                   9066: =item *
1.394     bowersj2 9067: X<idrget()>
                   9068: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9069: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9070: 
                   9071: =item *
1.394     bowersj2 9072: X<idput()>
                   9073: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9074: 
                   9075: =item *
1.394     bowersj2 9076: X<rolesinit()>
                   9077: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9078: 
                   9079: =item *
1.551     albertel 9080: X<getsection()>
                   9081: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9082: course $cname, return section name/number or '' for "not in course"
                   9083: and '-1' for "no section"
                   9084: 
                   9085: =item *
1.394     bowersj2 9086: X<userenvironment()>
                   9087: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9088: passed in @what from the requested user's environment, returns a hash
                   9089: 
1.858     raeburn  9090: =item * 
                   9091: X<userlog_query()>
1.859     albertel 9092: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9093: activity.log file. %filters defines filters applied when parsing the
                   9094: log file. These can be start or end timestamps, or the type of action
                   9095: - log to look for Login or Logout events, check for Checkin or
                   9096: Checkout, role for role selection. The response is in the form
                   9097: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9098: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9099: 
1.243     albertel 9100: =back
                   9101: 
                   9102: =head2 User Roles
                   9103: 
                   9104: =over 4
                   9105: 
                   9106: =item *
                   9107: 
1.810     raeburn  9108: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9109:  F: full access
                   9110:  U,I,K: authentication modes (cxx only)
                   9111:  '': forbidden
                   9112:  1: user needs to choose course
                   9113:  2: browse allowed
1.766     albertel 9114:  A: passphrase authentication needed
1.243     albertel 9115: 
                   9116: =item *
                   9117: 
                   9118: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9119: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9120: and course level
                   9121: 
                   9122: =item *
                   9123: 
                   9124: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9125: explanation of a user role term
                   9126: 
1.832     raeburn  9127: =item *
                   9128: 
1.935     raeburn  9129: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9130: All arguments are optional. Returns a hash of a roles, either for
                   9131: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9132: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9133: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9134: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9135: For each key, value is set to colon-separated start and end times for
                   9136: the role.  If no username and domain are specified, will default to
1.934     raeburn  9137: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9138: of role statuses (active, future or previous), roles 
                   9139: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9140: to restrict the list of roles reported. If no array ref is 
                   9141: provided for types, will default to return only active roles.
1.834     albertel 9142: 
1.243     albertel 9143: =back
                   9144: 
                   9145: =head2 User Modification
                   9146: 
                   9147: =over 4
                   9148: 
                   9149: =item *
                   9150: 
1.957     raeburn  9151: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9152: user for the level given by URL.  Optional start and end dates (leave empty
                   9153: string or zero for "no date")
1.191     harris41 9154: 
                   9155: =item *
                   9156: 
1.243     albertel 9157: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9158: change a users, password, possible return values are: ok,
                   9159: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9160: refused
1.191     harris41 9161: 
                   9162: =item *
                   9163: 
1.243     albertel 9164: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9165: 
                   9166: =item *
                   9167: 
1.963     raeburn  9168: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9169:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9170: modify user
1.191     harris41 9171: 
                   9172: =item *
                   9173: 
1.286     matthew  9174: modifystudent
                   9175: 
1.957     raeburn  9176: modify a student's enrollment and identification information.
1.286     matthew  9177: The course id is resolved based on the current users environment.  
                   9178: This means the envoking user must be a course coordinator or otherwise
                   9179: associated with a course.
                   9180: 
1.297     matthew  9181: This call is essentially a wrapper for lonnet::modifyuser and
                   9182: lonnet::modify_student_enrollment
1.286     matthew  9183: 
                   9184: Inputs: 
                   9185: 
                   9186: =over 4
                   9187: 
1.957     raeburn  9188: =item B<$udom> Student's loncapa domain
1.286     matthew  9189: 
1.957     raeburn  9190: =item B<$uname> Student's loncapa login name
1.286     matthew  9191: 
1.964     bisitz   9192: =item B<$uid> Student/Employee ID
1.286     matthew  9193: 
1.957     raeburn  9194: =item B<$umode> Student's authentication mode
1.286     matthew  9195: 
1.957     raeburn  9196: =item B<$upass> Student's password
1.286     matthew  9197: 
1.957     raeburn  9198: =item B<$first> Student's first name
1.286     matthew  9199: 
1.957     raeburn  9200: =item B<$middle> Student's middle name
1.286     matthew  9201: 
1.957     raeburn  9202: =item B<$last> Student's last name
1.286     matthew  9203: 
1.957     raeburn  9204: =item B<$gene> Student's generation
1.286     matthew  9205: 
1.957     raeburn  9206: =item B<$usec> Student's section in course
1.286     matthew  9207: 
                   9208: =item B<$end> Unix time of the roles expiration
                   9209: 
                   9210: =item B<$start> Unix time of the roles start date
                   9211: 
                   9212: =item B<$forceid> If defined, allow $uid to be changed
                   9213: 
                   9214: =item B<$desiredhome> server to use as home server for student
                   9215: 
1.957     raeburn  9216: =item B<$email> Student's permanent e-mail address
                   9217: 
                   9218: =item B<$type> Type of enrollment (auto or manual)
                   9219: 
1.963     raeburn  9220: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9221: 
                   9222: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9223: 
1.963     raeburn  9224: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9225: 
1.963     raeburn  9226: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9227: 
1.963     raeburn  9228: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9229: 
1.286     matthew  9230: =back
1.297     matthew  9231: 
                   9232: =item *
                   9233: 
                   9234: modify_student_enrollment
                   9235: 
                   9236: Change a students enrollment status in a class.  The environment variable
                   9237: 'role.request.course' must be defined for this function to proceed.
                   9238: 
                   9239: Inputs:
                   9240: 
                   9241: =over 4
                   9242: 
                   9243: =item $udom, students domain
                   9244: 
                   9245: =item $uname, students name
                   9246: 
                   9247: =item $uid, students user id
                   9248: 
                   9249: =item $first, students first name
                   9250: 
                   9251: =item $middle
                   9252: 
                   9253: =item $last
                   9254: 
                   9255: =item $gene
                   9256: 
                   9257: =item $usec
                   9258: 
                   9259: =item $end
                   9260: 
                   9261: =item $start
                   9262: 
1.957     raeburn  9263: =item $type
                   9264: 
                   9265: =item $locktype
                   9266: 
                   9267: =item $cid
                   9268: 
                   9269: =item $selfenroll
                   9270: 
                   9271: =item $context
                   9272: 
1.297     matthew  9273: =back
                   9274: 
1.191     harris41 9275: 
                   9276: =item *
                   9277: 
1.243     albertel 9278: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9279: custom role; give a custom role to a user for the level given by URL.  Specify
                   9280: name and domain of role author, and role name
1.191     harris41 9281: 
                   9282: =item *
                   9283: 
1.243     albertel 9284: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9285: 
                   9286: =item *
                   9287: 
1.243     albertel 9288: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9289: 
                   9290: =back
                   9291: 
                   9292: =head2 Course Infomation
                   9293: 
                   9294: =over 4
1.191     harris41 9295: 
                   9296: =item *
                   9297: 
1.631     albertel 9298: coursedescription($courseid) : returns a hash of information about the
                   9299: specified course id, including all environment settings for the
                   9300: course, the description of the course will be in the hash under the
                   9301: key 'description'
1.191     harris41 9302: 
                   9303: =item *
                   9304: 
1.624     albertel 9305: resdata($name,$domain,$type,@which) : request for current parameter
                   9306: setting for a specific $type, where $type is either 'course' or 'user',
                   9307: @what should be a list of parameters to ask about. This routine caches
                   9308: answers for 5 minutes.
1.243     albertel 9309: 
1.877     foxr     9310: =item *
                   9311: 
                   9312: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9313: data base, returning a hash that is keyed by the resource name and has
                   9314: values that are the resource value.  I believe that the timestamps and
                   9315: versions are also returned.
                   9316: 
                   9317: 
1.243     albertel 9318: =back
                   9319: 
                   9320: =head2 Course Modification
                   9321: 
                   9322: =over 4
1.191     harris41 9323: 
                   9324: =item *
                   9325: 
1.243     albertel 9326: writecoursepref($courseid,%prefs) : write preferences (environment
                   9327: database) for a course
1.191     harris41 9328: 
                   9329: =item *
                   9330: 
1.243     albertel 9331: createcourse($udom,$description,$url) : make/modify course
                   9332: 
                   9333: =back
                   9334: 
                   9335: =head2 Resource Subroutines
                   9336: 
                   9337: =over 4
1.191     harris41 9338: 
                   9339: =item *
                   9340: 
1.243     albertel 9341: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9342: 
                   9343: =item *
                   9344: 
1.243     albertel 9345: repcopy($filename) : subscribes to the requested file, and attempts to
                   9346: replicate from the owning library server, Might return
1.607     raeburn  9347: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9348: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9349: resource. Expects the local filesystem pathname
                   9350: (/home/httpd/html/res/....)
                   9351: 
                   9352: =back
                   9353: 
                   9354: =head2 Resource Information
                   9355: 
                   9356: =over 4
1.191     harris41 9357: 
                   9358: =item *
                   9359: 
1.243     albertel 9360: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9361: a vairety of different possible values, $varname should be a request
                   9362: string, and the other parameters can be used to specify who and what
                   9363: one is asking about.
                   9364: 
                   9365: Possible values for $varname are environment.lastname (or other item
                   9366: from the envirnment hash), user.name (or someother aspect about the
                   9367: user), resource.0.maxtries (or some other part and parameter of a
                   9368: resource)
1.204     albertel 9369: 
                   9370: =item *
                   9371: 
1.243     albertel 9372: directcondval($number) : get current value of a condition; reads from a state
                   9373: string
1.204     albertel 9374: 
                   9375: =item *
                   9376: 
1.243     albertel 9377: condval($condidx) : value of condition index based on state
1.204     albertel 9378: 
                   9379: =item *
                   9380: 
1.243     albertel 9381: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9382: resource's metadata, $what should be either a specific key, or either
                   9383: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9384: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9385: 
                   9386: this function automatically caches all requests
1.191     harris41 9387: 
                   9388: =item *
                   9389: 
1.243     albertel 9390: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9391: network of library servers; returns file handle of where SQL and regex results
                   9392: will be stored for query
1.191     harris41 9393: 
                   9394: =item *
                   9395: 
1.243     albertel 9396: symbread($filename) : return symbolic list entry (filename argument optional);
                   9397: returns the data handle
1.191     harris41 9398: 
                   9399: =item *
                   9400: 
1.243     albertel 9401: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9402: a possible symb for the URL in $thisfn, and if is an encryypted
                   9403: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9404: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9405: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9406: 
1.191     harris41 9407: 
                   9408: =item *
                   9409: 
1.243     albertel 9410: symbclean($symb) : removes versions numbers from a symb, returns the
                   9411: cleaned symb
1.191     harris41 9412: 
                   9413: =item *
                   9414: 
1.243     albertel 9415: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9416: course map, user must be in a course for it to work.
1.191     harris41 9417: 
                   9418: =item *
                   9419: 
1.243     albertel 9420: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9421: 
                   9422: =item *
                   9423: 
1.243     albertel 9424: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9425: a random seed, all arguments are optional, if they aren't sent it uses the
                   9426: environment to derive them. Note: if symb isn't sent and it can't get one
                   9427: from &symbread it will use the current time as its return value
1.191     harris41 9428: 
                   9429: =item *
                   9430: 
1.243     albertel 9431: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9432: unfakeable, receipt
1.191     harris41 9433: 
                   9434: =item *
                   9435: 
1.620     albertel 9436: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9437: 
                   9438: =item *
                   9439: 
1.243     albertel 9440: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9441: 
                   9442: =item *
                   9443: 
1.243     albertel 9444: 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 9445: 
                   9446: =item *
                   9447: 
1.243     albertel 9448: 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 9449: 
                   9450: =item *
                   9451: 
1.243     albertel 9452: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9453: 
                   9454: =item *
                   9455: 
1.243     albertel 9456: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9457: forcing spreadsheet to reevaluate the resource scores next time.
                   9458: 
                   9459: =back
                   9460: 
                   9461: =head2 Storing/Retreiving Data
                   9462: 
                   9463: =over 4
1.191     harris41 9464: 
                   9465: =item *
                   9466: 
1.243     albertel 9467: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9468: for this url; hashref needs to be given and should be a \%hashname; the
                   9469: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9470: be derived from the env
1.191     harris41 9471: 
                   9472: =item *
                   9473: 
1.243     albertel 9474: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9475: uses critical subroutine
1.191     harris41 9476: 
                   9477: =item *
                   9478: 
1.243     albertel 9479: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9480: all args are optional
1.191     harris41 9481: 
                   9482: =item *
                   9483: 
1.717     albertel 9484: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9485: dumps the complete (or key matching regexp) namespace into a hash
                   9486: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9487: normally &store()ed into
                   9488: 
                   9489: $range should be either an integer '100' (give me the first 100
                   9490:                                            matching records)
                   9491:               or be  two integers sperated by a - with no spaces
                   9492:                  '30-50' (give me the 30th through the 50th matching
                   9493:                           records)
                   9494: 
                   9495: 
                   9496: =item *
                   9497: 
                   9498: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9499: replaces a &store() version of data with a replacement set of data
                   9500: for a particular resource in a namespace passed in the $storehash hash 
                   9501: reference
                   9502: 
                   9503: =item *
                   9504: 
1.243     albertel 9505: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9506: works very similar to store/cstore, but all data is stored in a
                   9507: temporary location and can be reset using tmpreset, $storehash should
                   9508: be a hash reference, returns nothing on success
1.191     harris41 9509: 
                   9510: =item *
                   9511: 
1.243     albertel 9512: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9513: similar to restore, but all data is stored in a temporary location and
                   9514: can be reset using tmpreset. Returns a hash of values on success,
                   9515: error string otherwise.
1.191     harris41 9516: 
                   9517: =item *
                   9518: 
1.243     albertel 9519: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9520: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9521: 
                   9522: =item *
                   9523: 
1.243     albertel 9524: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9525: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9526: 
                   9527: =item *
                   9528: 
1.243     albertel 9529: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9530: namesp ($udom and $uname are optional)
1.191     harris41 9531: 
                   9532: =item *
                   9533: 
1.702     albertel 9534: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9535: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9536: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9537: 
1.702     albertel 9538: $range should be either an integer '100' (give me the first 100
                   9539:                                            matching records)
                   9540:               or be  two integers sperated by a - with no spaces
                   9541:                  '30-50' (give me the 30th through the 50th matching
                   9542:                           records)
1.449     matthew  9543: =item *
                   9544: 
                   9545: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9546: $store can be a scalar, an array reference, or if the amount to be 
                   9547: incremented is > 1, a hash reference.
                   9548: 
                   9549: ($udom and $uname are optional)
1.191     harris41 9550: 
                   9551: =item *
                   9552: 
1.243     albertel 9553: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9554: ($udom and $uname are optional)
1.191     harris41 9555: 
                   9556: =item *
                   9557: 
1.243     albertel 9558: cput($namespace,$storehash,$udom,$uname) : critical put
                   9559: ($udom and $uname are optional)
1.191     harris41 9560: 
                   9561: =item *
                   9562: 
1.748     albertel 9563: newput($namespace,$storehash,$udom,$uname) :
                   9564: 
                   9565: Attempts to store the items in the $storehash, but only if they don't
                   9566: currently exist, if this succeeds you can be certain that you have 
                   9567: successfully created a new key value pair in the $namespace db.
                   9568: 
                   9569: 
                   9570: Args:
                   9571:  $namespace: name of database to store values to
                   9572:  $storehash: hashref to store to the db
                   9573:  $udom: (optional) domain of user containing the db
                   9574:  $uname: (optional) name of user caontaining the db
                   9575: 
                   9576: Returns:
                   9577:  'ok' -> succeeded in storing all keys of $storehash
                   9578:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9579:                         least <key> already existed in the db (other
                   9580:                         requested keys may also already exist)
1.967     bisitz   9581:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9582:  'con_lost' -> unable to contact request server
                   9583:  'refused' -> action was not allowed by remote machine
                   9584: 
                   9585: 
                   9586: =item *
                   9587: 
1.243     albertel 9588: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9589: reference filled in from namesp (encrypts the return communication)
                   9590: ($udom and $uname are optional)
1.191     harris41 9591: 
                   9592: =item *
                   9593: 
1.243     albertel 9594: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9595: critical subroutine
                   9596: 
1.806     raeburn  9597: =item *
                   9598: 
1.860     raeburn  9599: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9600: array reference filled in from namespace found in domain level on either
                   9601: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9602: 
                   9603: =item *
                   9604: 
1.860     raeburn  9605: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9606: domain level either on specified domain server ($uhome) or primary domain 
                   9607: server ($udom and $uhome are optional)
1.806     raeburn  9608: 
1.943     raeburn  9609: =item * 
                   9610: 
                   9611: get_domain_defaults($target_domain) : returns hash with defaults for
                   9612: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9613: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9614: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9615: Values are retrieved from cache (if current), or from domain's configuration.db
                   9616: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9617: or lonTabs/domain.tab. 
                   9618: 
                   9619: %domdefaults = &get_auth_defaults($target_domain);
                   9620: 
1.243     albertel 9621: =back
                   9622: 
                   9623: =head2 Network Status Functions
                   9624: 
                   9625: =over 4
1.191     harris41 9626: 
                   9627: =item *
                   9628: 
                   9629: dirlist($uri) : return directory list based on URI
                   9630: 
                   9631: =item *
                   9632: 
1.243     albertel 9633: spareserver() : find server with least workload from spare.tab
                   9634: 
                   9635: =back
                   9636: 
                   9637: =head2 Apache Request
                   9638: 
                   9639: =over 4
1.191     harris41 9640: 
                   9641: =item *
                   9642: 
1.243     albertel 9643: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9644: localhost, posts hash
                   9645: 
                   9646: =back
                   9647: 
                   9648: =head2 Data to String to Data
                   9649: 
                   9650: =over 4
1.191     harris41 9651: 
                   9652: =item *
                   9653: 
1.243     albertel 9654: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9655: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9656: 
                   9657: =item *
                   9658: 
1.243     albertel 9659: hashref2str($hashref) : convert a hashref into a string complete with
                   9660: escaping and '=' and '&' separators, supports elements that are
                   9661: arrayrefs and hashrefs
1.191     harris41 9662: 
                   9663: =item *
                   9664: 
1.243     albertel 9665: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9666: with escaping and '&' separators, supports elements that are arrayrefs
                   9667: and hashrefs
1.191     harris41 9668: 
                   9669: =item *
                   9670: 
1.243     albertel 9671: str2hash($string) : convert string to hash using unescaping and
                   9672: splitting on '=' and '&', supports elements that are arrayrefs and
                   9673: hashrefs
1.191     harris41 9674: 
                   9675: =item *
                   9676: 
1.243     albertel 9677: str2array($string) : convert string to hash using unescaping and
                   9678: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9679: 
                   9680: =back
                   9681: 
                   9682: =head2 Logging Routines
                   9683: 
                   9684: =over 4
                   9685: 
                   9686: These routines allow one to make log messages in the lonnet.log and
                   9687: lonnet.perm logfiles.
1.191     harris41 9688: 
                   9689: =item *
                   9690: 
1.243     albertel 9691: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9692: 
                   9693: =item *
                   9694: 
1.243     albertel 9695: logthis() : append message to the normal lonnet.log file, it gets
                   9696: preiodically rolled over and deleted.
1.191     harris41 9697: 
                   9698: =item *
                   9699: 
1.243     albertel 9700: logperm() : append a permanent message to lonnet.perm.log, this log
                   9701: file never gets deleted by any automated portion of the system, only
                   9702: messages of critical importance should go in here.
                   9703: 
                   9704: =back
                   9705: 
                   9706: =head2 General File Helper Routines
                   9707: 
                   9708: =over 4
1.191     harris41 9709: 
                   9710: =item *
                   9711: 
1.481     raeburn  9712: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9713: (a) files in /uploaded
                   9714:   (i) If a local copy of the file exists - 
                   9715:       compares modification date of local copy with last-modified date for 
                   9716:       definitive version stored on home server for course. If local copy is 
                   9717:       stale, requests a new version from the home server and stores it. 
                   9718:       If the original has been removed from the home server, then local copy 
                   9719:       is unlinked.
                   9720:   (ii) If local copy does not exist -
                   9721:       requests the file from the home server and stores it. 
                   9722:   
                   9723:   If $caller is 'uploadrep':  
                   9724:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9725:     for request for files originally uploaded via DOCS. 
                   9726:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9727:   
                   9728:   Otherwise:
                   9729:      This indicates a call from the content generation phase of the request.
                   9730:      -  returns the entire contents of the file or -1.
                   9731:      
                   9732: (b) files in /res
                   9733:    - returns the entire contents of a file or -1; 
                   9734:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9735: 
1.712     albertel 9736: 
                   9737: =item *
                   9738: 
                   9739: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9740:                   reference
                   9741: 
                   9742: returns either a stat() list of data about the file or an empty list
                   9743: if the file doesn't exist or couldn't find out about it (connection
                   9744: problems or user unknown)
                   9745: 
1.191     harris41 9746: =item *
                   9747: 
1.243     albertel 9748: filelocation($dir,$file) : returns file system location of a file
                   9749: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9750: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9751: and a file of ../bob will become /a/bob)
1.191     harris41 9752: 
                   9753: =item *
                   9754: 
                   9755: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9756: filelocation except for hrefs
                   9757: 
                   9758: =item *
                   9759: 
                   9760: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9761: 
1.243     albertel 9762: =back
                   9763: 
1.608     albertel 9764: =head2 Usererfile file routines (/uploaded*)
                   9765: 
                   9766: =over 4
                   9767: 
                   9768: =item *
                   9769: 
                   9770: userfileupload(): main rotine for putting a file in a user or course's
                   9771:                   filespace, arguments are,
                   9772: 
1.620     albertel 9773:  formname - required - this is the name of the element in $env where the
1.608     albertel 9774:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9775:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9776:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9777:  coursedoc - if true, store the file in the course of the active role
                   9778:              of the current user
                   9779:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9780:          if undefined, it will be placed in "unknown"
                   9781: 
                   9782:  (This routine calls clean_filename() to remove any dangerous
                   9783:  characters from the filename, and then calls finuserfileupload() to
                   9784:  complete the transaction)
                   9785: 
                   9786:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9787:  and /adm/notfound.html if unsuccessful
                   9788: 
                   9789: =item *
                   9790: 
                   9791: clean_filename(): routine for cleaing a filename up for storage in
                   9792:                  userfile space, argument is:
                   9793: 
                   9794:  filename - proposed filename
                   9795: 
                   9796: returns: the new clean filename
                   9797: 
                   9798: =item *
                   9799: 
                   9800: finishuserfileupload(): routine that creaes and sends the file to
                   9801: userspace, probably shouldn't be called directly
                   9802: 
                   9803:   docuname: username or courseid of destination for the file
                   9804:   docudom: domain of user/course of destination for the file
                   9805:   formname: same as for userfileupload()
                   9806:   fname: filename (inculding subdirectories) for the file
                   9807: 
                   9808:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9809:  and /adm/notfound.html if unsuccessful
                   9810: 
                   9811: =item *
                   9812: 
                   9813: renameuserfile(): renames an existing userfile to a new name
                   9814: 
                   9815:   Args:
                   9816:    docuname: username or courseid of destination for the file
                   9817:    docudom: domain of user/course of destination for the file
                   9818:    old: current file name (including any subdirs under userfiles)
                   9819:    new: desired file name (including any subdirs under userfiles)
                   9820: 
                   9821: =item *
                   9822: 
                   9823: mkdiruserfile(): creates a directory is a userfiles dir
                   9824: 
                   9825:   Args:
                   9826:    docuname: username or courseid of destination for the file
                   9827:    docudom: domain of user/course of destination for the file
                   9828:    dir: dir to create (including any subdirs under userfiles)
                   9829: 
                   9830: =item *
                   9831: 
                   9832: removeuserfile(): removes a file that exists in userfiles
                   9833: 
                   9834:   Args:
                   9835:    docuname: username or courseid of destination for the file
                   9836:    docudom: domain of user/course of destination for the file
                   9837:    fname: filname to delete (including any subdirs under userfiles)
                   9838: 
                   9839: =item *
                   9840: 
                   9841: removeuploadedurl(): convience function for removeuserfile()
                   9842: 
                   9843:   Args:
                   9844:    url:  a full /uploaded/... url to delete
                   9845: 
1.747     albertel 9846: =item * 
                   9847: 
                   9848: get_portfile_permissions():
                   9849:   Args:
                   9850:     domain: domain of user or course contain the portfolio files
                   9851:     user: name of user or num of course contain the portfolio files
                   9852:   Returns:
                   9853:     hashref of a dump of the proper file_permissions.db
                   9854:    
                   9855: 
                   9856: =item * 
                   9857: 
                   9858: get_access_controls():
                   9859: 
                   9860: Args:
                   9861:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9862:   group: (optional) the group you want the files associated with
                   9863:   file: (optional) the file you want access info on
                   9864: 
                   9865: Returns:
1.749     raeburn  9866:     a hash (keys are file names) of hashes containing
                   9867:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9868:         values are XML containing access control settings (see below) 
1.747     albertel 9869: 
                   9870: Internal notes:
                   9871: 
1.749     raeburn  9872:  access controls are stored in file_permissions.db as key=value pairs.
                   9873:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9874:         where scope -> public,guest,course,group,domains or users.
                   9875:               end -> UNIX time for end of access (0 -> no end date)
                   9876:               start -> UNIX time for start of access
                   9877: 
                   9878:     value -> XML description of access control
                   9879:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9880:             <start></start>
                   9881:             <end></end>
                   9882: 
                   9883:             <password></password>  for scope type = guest
                   9884: 
                   9885:             <domain></domain>     for scope type = course or group
                   9886:             <number></number>
                   9887:             <roles id="">
                   9888:              <role></role>
                   9889:              <access></access>
                   9890:              <section></section>
                   9891:              <group></group>
                   9892:             </roles>
                   9893: 
                   9894:             <dom></dom>         for scope type = domains
                   9895: 
                   9896:             <users>             for scope type = users
                   9897:              <user>
                   9898:               <uname></uname>
                   9899:               <udom></udom>
                   9900:              </user>
                   9901:             </users>
                   9902:            </scope> 
                   9903:               
                   9904:  Access data is also aggregated for each file in an additional key=value pair:
                   9905:  key -> path to file/file_name\0accesscontrol 
                   9906:  value -> reference to hash
                   9907:           hash contains key = value pairs
                   9908:           where key = uniqueID:scope_end_start
                   9909:                 value = UNIX time record was last updated
                   9910: 
                   9911:           Used to improve speed of look-ups of access controls for each file.  
                   9912:  
                   9913:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9914: 
                   9915: modify_access_controls():
                   9916: 
                   9917: Modifies access controls for a portfolio file
                   9918: Args
                   9919: 1. file name
                   9920: 2. reference to hash of required changes,
                   9921: 3. domain
                   9922: 4. username
                   9923:   where domain,username are the domain of the portfolio owner 
                   9924:   (either a user or a course) 
                   9925: 
                   9926: Returns:
                   9927: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9928: 2. result of deletions ('ok' or 'error', with error message).
                   9929: 3. reference to hash of any new or updated access controls.
                   9930: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9931:    key = integer (inbound ID)
                   9932:    value = uniqueID  
1.747     albertel 9933: 
1.608     albertel 9934: =back
                   9935: 
1.243     albertel 9936: =head2 HTTP Helper Routines
                   9937: 
                   9938: =over 4
                   9939: 
1.191     harris41 9940: =item *
                   9941: 
                   9942: escape() : unpack non-word characters into CGI-compatible hex codes
                   9943: 
                   9944: =item *
                   9945: 
                   9946: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9947: 
1.243     albertel 9948: =back
                   9949: 
                   9950: =head1 PRIVATE SUBROUTINES
                   9951: 
                   9952: =head2 Underlying communication routines (Shouldn't call)
                   9953: 
                   9954: =over 4
                   9955: 
                   9956: =item *
                   9957: 
                   9958: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9959: 
                   9960: =item *
                   9961: 
                   9962: reply() : uses subreply to send a message to remote machine, logs all failures
                   9963: 
                   9964: =item *
                   9965: 
                   9966: critical() : passes a critical message to another server; if cannot
                   9967: get through then place message in connection buffer directory and
                   9968: returns con_delayed, if incapable of saving message, returns
                   9969: con_failed
                   9970: 
                   9971: =item *
                   9972: 
                   9973: reconlonc() : tries to reconnect lonc client processes.
                   9974: 
                   9975: =back
                   9976: 
                   9977: =head2 Resource Access Logging
                   9978: 
                   9979: =over 4
                   9980: 
                   9981: =item *
                   9982: 
                   9983: flushcourselogs() : flush (save) buffer logs and access logs
                   9984: 
                   9985: =item *
                   9986: 
                   9987: courselog($what) : save message for course in hash
                   9988: 
                   9989: =item *
                   9990: 
                   9991: courseacclog($what) : save message for course using &courselog().  Perform
                   9992: special processing for specific resource types (problems, exams, quizzes, etc).
                   9993: 
1.191     harris41 9994: =item *
                   9995: 
                   9996: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9997: as a PerlChildExitHandler
1.243     albertel 9998: 
                   9999: =back
                   10000: 
                   10001: =head2 Other
                   10002: 
                   10003: =over 4
                   10004: 
                   10005: =item *
                   10006: 
                   10007: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10008: 
                   10009: =back
                   10010: 
                   10011: =cut
1.877     foxr     10012: 

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