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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.980   ! raeburn     4: # $Id: lonnet.pm,v 1.979 2008/12/19 17:04:57 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.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.486     www        78: # use Date::Parse;
1.871     albertel   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    80:             $_64bit %env %protocol);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.977     amueller  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    153: 	print $fh "$local ($$): $message\n";
                    154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
                    184: 
1.1       albertel  185: # -------------------------------------------------- Non-critical communication
                    186: sub subreply {
                    187:     my ($cmd,$server)=@_;
1.838     albertel  188:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      189:     #
                    190:     #  With loncnew process trimming, there's a timing hole between lonc server
                    191:     #  process exit and the master server picking up the listen on the AF_UNIX
                    192:     #  socket.  In that time interval, a lock file will exist:
                    193: 
                    194:     my $lockfile=$peerfile.".lock";
                    195:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    196: 	sleep(1);
                    197:     }
                    198:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      199:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      200:     #
1.550     foxr      201:     #   We'll give the connection a few tries before abandoning it.  If
                    202:     #   connection is not possible, we'll con_lost back to the client.
                    203:     #   
                    204:     my $client;
                    205:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    206: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    207: 				      Type    => SOCK_STREAM,
                    208: 				      Timeout => 10);
1.869     albertel  209: 	if ($client) {
1.550     foxr      210: 	    last;		# Connected!
1.850     albertel  211: 	} else {
1.853     albertel  212: 	    &create_connection(&hostname($server),$server);
1.550     foxr      213: 	}
1.850     albertel  214:         sleep(1);		# Try again later if failed connection.
1.550     foxr      215:     }
                    216:     my $answer;
                    217:     if ($client) {
1.704     albertel  218: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      219: 	$answer=<$client>;
                    220: 	if (!$answer) { $answer="con_lost"; }
                    221: 	chomp($answer);
                    222:     } else {
                    223: 	$answer = 'con_lost';	# Failed connection.
                    224:     }
1.1       albertel  225:     return $answer;
                    226: }
                    227: 
                    228: sub reply {
                    229:     my ($cmd,$server)=@_;
1.838     albertel  230:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  231:     my $answer=subreply($cmd,$server);
1.65      www       232:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  233:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       234:                 " $cmd to $server returned $answer</font>");
                    235:     }
1.1       albertel  236:     return $answer;
                    237: }
                    238: 
                    239: # ----------------------------------------------------------- Send USR1 to lonc
                    240: 
                    241: sub reconlonc {
1.891     albertel  242:     my ($lonid) = @_;
                    243:     my $hostname = &hostname($lonid);
                    244:     if ($lonid) {
                    245: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    246: 	if ($hostname && -e $peerfile) {
                    247: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    248: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    249: 					     Type    => SOCK_STREAM,
                    250: 					     Timeout => 10);
                    251: 	    if ($client) {
                    252: 		print $client ("reset_retries\n");
                    253: 		my $answer=<$client>;
                    254: 		#reset just this one.
                    255: 	    }
                    256: 	}
                    257: 	return;
                    258:     }
                    259: 
1.836     www       260:     &logthis("Trying to reconnect lonc");
1.1       albertel  261:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  262:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  263: 	my $loncpid=<$fh>;
                    264:         chomp($loncpid);
                    265:         if (kill 0 => $loncpid) {
                    266: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    267:             kill USR1 => $loncpid;
                    268:             sleep 1;
1.836     www       269:          } else {
1.12      www       270: 	    &logthis(
1.672     albertel  271:                "<font color=\"blue\">WARNING:".
1.12      www       272:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  273:         }
                    274:     } else {
1.836     www       275: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  276:     }
                    277: }
                    278: 
                    279: # ------------------------------------------------------ Critical communication
1.12      www       280: 
1.1       albertel  281: sub critical {
                    282:     my ($cmd,$server)=@_;
1.838     albertel  283:     unless (&hostname($server)) {
1.672     albertel  284:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       285:                " Critical message to unknown server ($server)</font>");
                    286:         return 'no_such_host';
                    287:     }
1.1       albertel  288:     my $answer=reply($cmd,$server);
                    289:     if ($answer eq 'con_lost') {
                    290: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  291: 	my $answer=reply($cmd,$server);
1.1       albertel  292:         if ($answer eq 'con_lost') {
                    293:             my $now=time;
                    294:             my $middlename=$cmd;
1.5       www       295:             $middlename=substr($middlename,0,16);
1.1       albertel  296:             $middlename=~s/\W//g;
                    297:             my $dfilename=
1.305     www       298:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    299:             $dumpcount++;
1.1       albertel  300:             {
1.448     albertel  301: 		my $dfh;
                    302: 		if (open($dfh,">$dfilename")) {
                    303: 		    print $dfh "$cmd\n"; 
                    304: 		    close($dfh);
                    305: 		}
1.1       albertel  306:             }
                    307:             sleep 2;
                    308:             my $wcmd='';
                    309:             {
1.448     albertel  310: 		my $dfh;
                    311: 		if (open($dfh,"<$dfilename")) {
                    312: 		    $wcmd=<$dfh>; 
                    313: 		    close($dfh);
                    314: 		}
1.1       albertel  315:             }
                    316:             chomp($wcmd);
1.7       www       317:             if ($wcmd eq $cmd) {
1.672     albertel  318: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       319:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  320:                 &logperm("D:$server:$cmd");
                    321: 	        return 'con_delayed';
                    322:             } else {
1.672     albertel  323:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       324:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  325:                 &logperm("F:$server:$cmd");
                    326:                 return 'con_failed';
                    327:             }
                    328:         }
                    329:     }
                    330:     return $answer;
1.405     albertel  331: }
                    332: 
1.755     albertel  333: # ------------------------------------------- check if return value is an error
                    334: 
                    335: sub error {
                    336:     my ($result) = @_;
1.756     albertel  337:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  338: 	if ($2 == 2) { return undef; }
                    339: 	return $1;
                    340:     }
                    341:     return undef;
                    342: }
                    343: 
1.783     albertel  344: sub convert_and_load_session_env {
                    345:     my ($lonidsdir,$handle)=@_;
                    346:     my @profile;
                    347:     {
1.917     albertel  348: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    349: 	if (!$opened) {
1.915     albertel  350: 	    return 0;
                    351: 	}
1.783     albertel  352: 	flock($idf,LOCK_SH);
                    353: 	@profile=<$idf>;
                    354: 	close($idf);
                    355:     }
                    356:     my %temp_env;
                    357:     foreach my $line (@profile) {
1.786     albertel  358: 	if ($line !~ m/=/) {
                    359: 	    return 0;
                    360: 	}
1.783     albertel  361: 	chomp($line);
                    362: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    363: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    364:     }
                    365:     unlink("$lonidsdir/$handle.id");
                    366:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    367: 	    0640)) {
                    368: 	%disk_env = %temp_env;
                    369: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    370: 	untie(%disk_env);
                    371:     }
1.786     albertel  372:     return 1;
1.783     albertel  373: }
                    374: 
1.374     www       375: # ------------------------------------------- Transfer profile into environment
1.780     albertel  376: my $env_loaded;
                    377: sub transfer_profile_to_env {
1.788     albertel  378:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    379:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       380: 
1.720     albertel  381:     if (!defined($lonidsdir)) {
                    382: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    383:     }
                    384:     if (!defined($handle)) {
                    385:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    386:     }
                    387: 
1.786     albertel  388:     my $convert;
                    389:     {
1.917     albertel  390:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    391: 	if (!$opened) {
1.915     albertel  392: 	    return;
                    393: 	}
1.786     albertel  394: 	flock($idf,LOCK_SH);
                    395: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    396: 		&GDBM_READER(),0640)) {
                    397: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    398: 	    untie(%disk_env);
                    399: 	} else {
                    400: 	    $convert = 1;
                    401: 	}
                    402:     }
                    403:     if ($convert) {
                    404: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    405: 	    &logthis("Failed to load session, or convert session.");
                    406: 	}
1.374     www       407:     }
1.783     albertel  408: 
1.786     albertel  409:     my %remove;
1.783     albertel  410:     while ( my $envname = each(%env) ) {
1.433     matthew   411:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    412:             if ($time < time-300) {
1.783     albertel  413:                 $remove{$key}++;
1.433     matthew   414:             }
                    415:         }
                    416:     }
1.783     albertel  417: 
1.619     albertel  418:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  419:     $env_loaded=1;
1.783     albertel  420:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   421:         &delenv($expired_key);
1.374     www       422:     }
1.1       albertel  423: }
                    424: 
1.916     albertel  425: # ---------------------------------------------------- Check for valid session 
                    426: sub check_for_valid_session {
                    427:     my ($r) = @_;
                    428:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    429:     my $lonid=$cookies{'lonID'};
                    430:     return undef if (!$lonid);
                    431: 
                    432:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    433:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    434:     return undef if (!-e "$lonidsdir/$handle.id");
                    435: 
1.917     albertel  436:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    437:     return undef if (!$opened);
1.916     albertel  438: 
                    439:     flock($idf,LOCK_SH);
                    440:     my %disk_env;
                    441:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    442: 	    &GDBM_READER(),0640)) {
                    443: 	return undef;	
                    444:     }
                    445: 
                    446:     if (!defined($disk_env{'user.name'})
                    447: 	|| !defined($disk_env{'user.domain'})) {
                    448: 	return undef;
                    449:     }
                    450:     return $handle;
                    451: }
                    452: 
1.830     albertel  453: sub timed_flock {
                    454:     my ($file,$lock_type) = @_;
                    455:     my $failed=0;
                    456:     eval {
                    457: 	local $SIG{__DIE__}='DEFAULT';
                    458: 	local $SIG{ALRM}=sub {
                    459: 	    $failed=1;
                    460: 	    die("failed lock");
                    461: 	};
                    462: 	alarm(13);
                    463: 	flock($file,$lock_type);
                    464: 	alarm(0);
                    465:     };
                    466:     if ($failed) {
                    467: 	return undef;
                    468:     } else {
                    469: 	return 1;
                    470:     }
                    471: }
                    472: 
1.5       www       473: # ---------------------------------------------------------- Append Environment
                    474: 
                    475: sub appenv {
1.949     raeburn   476:     my ($newenv,$roles) = @_;
                    477:     if (ref($newenv) eq 'HASH') {
                    478:         foreach my $key (keys(%{$newenv})) {
                    479:             my $refused = 0;
                    480: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    481:                 $refused = 1;
                    482:                 if (ref($roles) eq 'ARRAY') {
                    483:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    484:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    485:                         $refused = 0;
                    486:                     }
                    487:                 }
                    488:             }
                    489:             if ($refused) {
                    490:                 &logthis("<font color=\"blue\">WARNING: ".
                    491:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    492:                          .'</font>');
                    493: 	        delete($newenv->{$key});
                    494:             } else {
                    495:                 $env{$key}=$newenv->{$key};
                    496:             }
                    497:         }
                    498:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    499:         if ($opened
                    500: 	    && &timed_flock($env_file,LOCK_EX)
                    501: 	    &&
                    502: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    503: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    504: 	    while (my ($key,$value) = each(%{$newenv})) {
                    505: 	        $disk_env{$key} = $value;
                    506: 	    }
                    507: 	    untie(%disk_env);
1.35      www       508:         }
1.191     harris41  509:     }
1.56      www       510:     return 'ok';
                    511: }
                    512: # ----------------------------------------------------- Delete from Environment
                    513: 
                    514: sub delenv {
                    515:     my $delthis=shift;
                    516:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  517:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       518:                 "Attempt to delete from environment ".$delthis);
                    519:         return 'error';
                    520:     }
1.917     albertel  521:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    522:     if ($opened
1.915     albertel  523: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  524: 	&&
                    525: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    526: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  527: 	foreach my $key (keys(%disk_env)) {
                    528: 	    if ($key=~/^$delthis/) { 
1.915     albertel  529: 		delete($env{$key});
                    530: 		delete($disk_env{$key});
                    531: 	    }
1.448     albertel  532: 	}
1.783     albertel  533: 	untie(%disk_env);
1.5       www       534:     }
                    535:     return 'ok';
1.369     albertel  536: }
                    537: 
1.790     albertel  538: sub get_env_multiple {
                    539:     my ($name) = @_;
                    540:     my @values;
                    541:     if (defined($env{$name})) {
                    542:         # exists is it an array
                    543:         if (ref($env{$name})) {
                    544:             @values=@{ $env{$name} };
                    545:         } else {
                    546:             $values[0]=$env{$name};
                    547:         }
                    548:     }
                    549:     return(@values);
                    550: }
                    551: 
1.958     www       552: # ------------------------------------------------------------------- Locking
                    553: 
                    554: sub set_lock {
                    555:     my ($text)=@_;
                    556:     $locknum++;
                    557:     my $id=$$.'-'.$locknum;
                    558:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    559:              'session.lock.'.$id => $text});
                    560:     return $id;
                    561: }
                    562: 
                    563: sub get_locks {
                    564:     my $num=0;
                    565:     my %texts=();
                    566:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    567:        if ($lock=~/\w/) {
                    568:           $num++;
                    569:           $texts{$lock}=$env{'session.lock.'.$lock};
                    570:        }
                    571:    }
                    572:    return ($num,%texts);
                    573: }
                    574: 
                    575: sub remove_lock {
                    576:     my ($id)=@_;
                    577:     my $newlocks='';
                    578:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    579:        if (($lock=~/\w/) && ($lock ne $id)) {
                    580:           $newlocks.=','.$lock;
                    581:        }
                    582:     }
                    583:     &appenv({'session.locks' => $newlocks});
                    584:     &delenv('session.lock.'.$id);
                    585: }
                    586: 
                    587: sub remove_all_locks {
                    588:     my $activelocks=$env{'session.locks'};
                    589:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    590:        if ($lock=~/\w/) {
                    591:           &remove_lock($lock);
                    592:        }
                    593:     }
                    594: }
                    595: 
                    596: 
1.369     albertel  597: # ------------------------------------------ Find out current server userload
                    598: sub userload {
                    599:     my $numusers=0;
                    600:     {
                    601: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    602: 	my $filename;
                    603: 	my $curtime=time;
                    604: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  605: 	    next if ($filename eq '.' || $filename eq '..');
                    606: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  607: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  608: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  609: 	}
                    610: 	closedir(LONIDS);
                    611:     }
                    612:     my $userloadpercent=0;
                    613:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    614:     if ($maxuserload) {
1.371     albertel  615: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  616:     }
1.372     albertel  617:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  618:     return $userloadpercent;
1.283     www       619: }
                    620: 
                    621: # ------------------------------------------ Fight off request when overloaded
                    622: 
                    623: sub overloaderror {
                    624:     my ($r,$checkserver)=@_;
                    625:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    626:     my $loadavg;
                    627:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  628:        open(my $loadfile,'/proc/loadavg');
1.283     www       629:        $loadavg=<$loadfile>;
                    630:        $loadavg =~ s/\s.*//g;
1.285     matthew   631:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  632:        close($loadfile);
1.283     www       633:     } else {
                    634:        $loadavg=&reply('load',$checkserver);
                    635:     }
1.285     matthew   636:     my $overload=$loadavg-100;
1.283     www       637:     if ($overload>0) {
1.285     matthew   638: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       639:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       640:         return 413;
1.283     www       641:     }    
                    642:     return '';
1.5       www       643: }
1.1       albertel  644: 
                    645: # ------------------------------ Find server with least workload from spare.tab
1.11      www       646: 
1.1       albertel  647: sub spareserver {
1.670     albertel  648:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  649:     my $spare_server;
1.370     albertel  650:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  651:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    652:                                                      :  $userloadpercent;
                    653:     
                    654:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    655: 	($spare_server, $lowest_load) =
                    656: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    657:     }
                    658: 
                    659:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    660: 
                    661:     if (!$found_server) {
                    662: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    663: 	    ($spare_server, $lowest_load) =
                    664: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    665: 	}
                    666:     }
                    667: 
                    668:     if (!$want_server_name) {
1.968     raeburn   669:         my $protocol = 'http';
                    670:         if ($protocol{$spare_server} eq 'https') {
                    671:             $protocol = $protocol{$spare_server};
                    672:         }
                    673: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  674:     }
                    675:     return $spare_server;
                    676: }
                    677: 
                    678: sub compare_server_load {
                    679:     my ($try_server, $spare_server, $lowest_load) = @_;
                    680: 
                    681:     my $loadans     = &reply('load',    $try_server);
                    682:     my $userloadans = &reply('userload',$try_server);
                    683: 
                    684:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    685: 	next; #didn't get a number from the server
                    686:     }
                    687: 
                    688:     my $load;
                    689:     if ($loadans =~ /\d/) {
                    690: 	if ($userloadans =~ /\d/) {
                    691: 	    #both are numbers, pick the bigger one
                    692: 	    $load = ($loadans > $userloadans) ? $loadans 
                    693: 		                              : $userloadans;
1.411     albertel  694: 	} else {
1.784     albertel  695: 	    $load = $loadans;
1.411     albertel  696: 	}
1.784     albertel  697:     } else {
                    698: 	$load = $userloadans;
                    699:     }
                    700: 
                    701:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    702: 	$spare_server = $try_server;
                    703: 	$lowest_load  = $load;
1.370     albertel  704:     }
1.784     albertel  705:     return ($spare_server,$lowest_load);
1.202     matthew   706: }
1.914     albertel  707: 
                    708: # --------------------------- ask offload servers if user already has a session
                    709: sub find_existing_session {
                    710:     my ($udom,$uname) = @_;
                    711:     foreach my $try_server (@{ $spareid{'primary'} },
                    712: 			    @{ $spareid{'default'} }) {
                    713: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    714:     }
                    715:     return;
                    716: }
                    717: 
                    718: # -------------------------------- ask if server already has a session for user
                    719: sub has_user_session {
                    720:     my ($lonid,$udom,$uname) = @_;
                    721:     my $result = &reply(join(':','userhassession',
                    722: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    723:     return 1 if ($result eq 'ok');
                    724: 
                    725:     return 0;
                    726: }
                    727: 
1.202     matthew   728: # --------------------------------------------- Try to change a user's password
                    729: 
                    730: sub changepass {
1.799     raeburn   731:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   732:     $currentpass = &escape($currentpass);
                    733:     $newpass     = &escape($newpass);
1.799     raeburn   734:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   735: 		       $server);
                    736:     if (! $answer) {
                    737: 	&logthis("No reply on password change request to $server ".
                    738: 		 "by $uname in domain $udom.");
                    739:     } elsif ($answer =~ "^ok") {
                    740:         &logthis("$uname in $udom successfully changed their password ".
                    741: 		 "on $server.");
                    742:     } elsif ($answer =~ "^pwchange_failure") {
                    743: 	&logthis("$uname in $udom was unable to change their password ".
                    744: 		 "on $server.  The action was blocked by either lcpasswd ".
                    745: 		 "or pwchange");
                    746:     } elsif ($answer =~ "^non_authorized") {
                    747:         &logthis("$uname in $udom did not get their password correct when ".
                    748: 		 "attempting to change it on $server.");
                    749:     } elsif ($answer =~ "^auth_mode_error") {
                    750:         &logthis("$uname in $udom attempted to change their password despite ".
                    751: 		 "not being locally or internally authenticated on $server.");
                    752:     } elsif ($answer =~ "^unknown_user") {
                    753:         &logthis("$uname in $udom attempted to change their password ".
                    754: 		 "on $server but were unable to because $server is not ".
                    755: 		 "their home server.");
                    756:     } elsif ($answer =~ "^refused") {
                    757: 	&logthis("$server refused to change $uname in $udom password because ".
                    758: 		 "it was sent an unencrypted request to change the password.");
                    759:     }
                    760:     return $answer;
1.1       albertel  761: }
                    762: 
1.169     harris41  763: # ----------------------- Try to determine user's current authentication scheme
                    764: 
                    765: sub queryauthenticate {
                    766:     my ($uname,$udom)=@_;
1.456     albertel  767:     my $uhome=&homeserver($uname,$udom);
                    768:     if (!$uhome) {
                    769: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    770: 	return 'no_host';
                    771:     }
                    772:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    773:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    774: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  775:     }
1.456     albertel  776:     return $answer;
1.169     harris41  777: }
                    778: 
1.1       albertel  779: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       780: 
1.1       albertel  781: sub authenticate {
1.952     raeburn   782:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  783:     $upass=&escape($upass);
                    784:     $uname= &LONCAPA::clean_username($uname);
1.836     www       785:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   786:     my $newhome;
1.836     www       787:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    788: # Maybe the machine was offline and only re-appeared again recently?
                    789:         &reconlonc();
                    790: # One more
1.952     raeburn   791: 	$uhome=&homeserver($uname,$udom,1);
                    792:         if (($uhome eq 'no_host') && $checkdefauth) {
                    793:             if (defined(&domain($udom,'primary'))) {
                    794:                 $newhome=&domain($udom,'primary');
                    795:             }
                    796:             if ($newhome ne '') {
                    797:                 $uhome = $newhome;
                    798:             }
                    799:         }
1.836     www       800: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    801: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   802: 	    return 'no_host';
                    803:         }
1.1       albertel  804:     }
1.952     raeburn   805:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  806:     if ($answer eq 'authorized') {
1.952     raeburn   807:         if ($newhome) {
                    808:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    809:             return 'no_account_on_host'; 
                    810:         } else {
                    811:             &logthis("User $uname at $udom authorized by $uhome");
                    812:             return $uhome;
                    813:         }
1.471     albertel  814:     }
                    815:     if ($answer eq 'non_authorized') {
                    816: 	&logthis("User $uname at $udom rejected by $uhome");
                    817: 	return 'no_host'; 
1.9       www       818:     }
1.471     albertel  819:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  820:     return 'no_host';
                    821: }
                    822: 
                    823: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       824: 
1.599     albertel  825: my %homecache;
1.1       albertel  826: sub homeserver {
1.230     stredwic  827:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  828:     my $index="$uname:$udom";
1.426     albertel  829: 
1.599     albertel  830:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  831: 
                    832:     my %servers = &get_servers($udom,'library');
                    833:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  834:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  835: 		 exists($badServerCache{$tryserver}));
1.841     albertel  836: 
                    837: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    838: 	if ($answer eq 'found') {
                    839: 	    delete($badServerCache{$tryserver}); 
                    840: 	    return $homecache{$index}=$tryserver;
                    841: 	} elsif ($answer eq 'no_host') {
                    842: 	    $badServerCache{$tryserver}=1;
                    843: 	}
1.1       albertel  844:     }    
                    845:     return 'no_host';
1.70      www       846: }
                    847: 
                    848: # ------------------------------------- Find the usernames behind a list of IDs
                    849: 
                    850: sub idget {
                    851:     my ($udom,@ids)=@_;
                    852:     my %returnhash=();
                    853:     
1.841     albertel  854:     my %servers = &get_servers($udom,'library');
                    855:     foreach my $tryserver (keys(%servers)) {
                    856: 	my $idlist=join('&',@ids);
                    857: 	$idlist=~tr/A-Z/a-z/; 
                    858: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    859: 	my @answer=();
                    860: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    861: 	    @answer=split(/\&/,$reply);
                    862: 	}                    ;
                    863: 	my $i;
                    864: 	for ($i=0;$i<=$#ids;$i++) {
                    865: 	    if ($answer[$i]) {
                    866: 		$returnhash{$ids[$i]}=$answer[$i];
                    867: 	    } 
                    868: 	}
                    869:     } 
1.70      www       870:     return %returnhash;
                    871: }
                    872: 
                    873: # ------------------------------------- Find the IDs behind a list of usernames
                    874: 
                    875: sub idrget {
                    876:     my ($udom,@unames)=@_;
                    877:     my %returnhash=();
1.800     albertel  878:     foreach my $uname (@unames) {
                    879:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  880:     }
1.70      www       881:     return %returnhash;
                    882: }
                    883: 
                    884: # ------------------------------- Store away a list of names and associated IDs
                    885: 
                    886: sub idput {
                    887:     my ($udom,%ids)=@_;
                    888:     my %servers=();
1.800     albertel  889:     foreach my $uname (keys(%ids)) {
                    890: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    891:         my $uhom=&homeserver($uname,$udom);
1.70      www       892:         if ($uhom ne 'no_host') {
1.800     albertel  893:             my $id=&escape($ids{$uname});
1.70      www       894:             $id=~tr/A-Z/a-z/;
1.800     albertel  895:             my $esc_unam=&escape($uname);
1.70      www       896: 	    if ($servers{$uhom}) {
1.800     albertel  897: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       898:             } else {
1.800     albertel  899:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       900:             }
                    901:         }
1.191     harris41  902:     }
1.800     albertel  903:     foreach my $server (keys(%servers)) {
                    904:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  905:     }
1.344     www       906: }
                    907: 
1.806     raeburn   908: # ------------------------------------------- get items from domain db files   
                    909: 
                    910: sub get_dom {
1.860     raeburn   911:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   912:     my $items='';
                    913:     foreach my $item (@$storearr) {
                    914:         $items.=&escape($item).'&';
                    915:     }
                    916:     $items=~s/\&$//;
1.860     raeburn   917:     if (!$udom) {
                    918:         $udom=$env{'user.domain'};
                    919:         if (defined(&domain($udom,'primary'))) {
                    920:             $uhome=&domain($udom,'primary');
                    921:         } else {
1.874     albertel  922:             undef($uhome);
1.860     raeburn   923:         }
                    924:     } else {
                    925:         if (!$uhome) {
                    926:             if (defined(&domain($udom,'primary'))) {
                    927:                 $uhome=&domain($udom,'primary');
                    928:             }
                    929:         }
                    930:     }
                    931:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   932:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   933:         my %returnhash;
1.875     albertel  934:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   935:             return %returnhash;
                    936:         }
1.806     raeburn   937:         my @pairs=split(/\&/,$rep);
                    938:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    939:             return @pairs;
                    940:         }
                    941:         my $i=0;
                    942:         foreach my $item (@$storearr) {
                    943:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    944:             $i++;
                    945:         }
                    946:         return %returnhash;
                    947:     } else {
1.880     banghart  948:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   949:     }
                    950: }
                    951: 
                    952: # -------------------------------------------- put items in domain db files 
                    953: 
                    954: sub put_dom {
1.860     raeburn   955:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    956:     if (!$udom) {
                    957:         $udom=$env{'user.domain'};
                    958:         if (defined(&domain($udom,'primary'))) {
                    959:             $uhome=&domain($udom,'primary');
                    960:         } else {
1.874     albertel  961:             undef($uhome);
1.860     raeburn   962:         }
                    963:     } else {
                    964:         if (!$uhome) {
                    965:             if (defined(&domain($udom,'primary'))) {
                    966:                 $uhome=&domain($udom,'primary');
                    967:             }
                    968:         }
                    969:     } 
                    970:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   971:         my $items='';
                    972:         foreach my $item (keys(%$storehash)) {
                    973:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    974:         }
                    975:         $items=~s/\&$//;
                    976:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    977:     } else {
1.860     raeburn   978:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   979:     }
                    980: }
                    981: 
1.837     raeburn   982: sub retrieve_inst_usertypes {
                    983:     my ($udom) = @_;
                    984:     my (%returnhash,@order);
1.846     albertel  985:     if (defined(&domain($udom,'primary'))) {
                    986:         my $uhome=&domain($udom,'primary');
1.837     raeburn   987:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn   988:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                    989:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                    990:             return (\%returnhash,\@order);
                    991:         }
1.837     raeburn   992:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    993:         my @pairs=split(/\&/,$hashitems);
                    994:         foreach my $item (@pairs) {
                    995:             my ($key,$value)=split(/=/,$item,2);
                    996:             $key = &unescape($key);
                    997:             next if ($key =~ /^error: 2 /);
                    998:             $returnhash{$key}=&thaw_unescape($value);
                    999:         }
                   1000:         my @esc_order = split(/\&/,$orderitems);
                   1001:         foreach my $item (@esc_order) {
                   1002:             push(@order,&unescape($item));
                   1003:         }
                   1004:     } else {
                   1005:         &logthis("get_dom failed - no primary domain server for $udom");
                   1006:     }
                   1007:     return (\%returnhash,\@order);
                   1008: }
                   1009: 
1.868     raeburn  1010: sub is_domainimage {
                   1011:     my ($url) = @_;
                   1012:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1013:         if (&domain($1) ne '') {
                   1014:             return '1';
                   1015:         }
                   1016:     }
                   1017:     return;
                   1018: }
                   1019: 
1.899     raeburn  1020: sub inst_directory_query {
                   1021:     my ($srch) = @_;
                   1022:     my $udom = $srch->{'srchdomain'};
                   1023:     my %results;
                   1024:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1025:     my $outcome;
1.899     raeburn  1026:     if ($homeserver ne '') {
1.904     albertel 1027: 	my $queryid=&reply("querysend:instdirsearch:".
                   1028: 			   &escape($srch->{'srchby'}).':'.
                   1029: 			   &escape($srch->{'srchterm'}).':'.
                   1030: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1031: 	my $host=&hostname($homeserver);
                   1032: 	if ($queryid !~/^\Q$host\E\_/) {
                   1033: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1034: 	    return;
                   1035: 	}
                   1036: 	my $response = &get_query_reply($queryid);
                   1037: 	my $maxtries = 5;
                   1038: 	my $tries = 1;
                   1039: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1040: 	    $response = &get_query_reply($queryid);
                   1041: 	    $tries ++;
                   1042: 	}
                   1043: 
                   1044:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1045:             if ($response eq 'unavailable') {
                   1046:                 $outcome = $response;
                   1047:             } else {
                   1048:                 $outcome = 'ok';
                   1049:                 my @matches = split(/\n/,$response);
                   1050:                 foreach my $match (@matches) {
                   1051:                     my ($key,$value) = split(/=/,$match);
                   1052:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1053:                 }
1.899     raeburn  1054:             }
                   1055:         }
                   1056:     }
1.909     raeburn  1057:     return ($outcome,%results);
1.899     raeburn  1058: }
                   1059: 
                   1060: sub usersearch {
                   1061:     my ($srch) = @_;
                   1062:     my $dom = $srch->{'srchdomain'};
                   1063:     my %results;
                   1064:     my %libserv = &all_library();
                   1065:     my $query = 'usersearch';
                   1066:     foreach my $tryserver (keys(%libserv)) {
                   1067:         if (&host_domain($tryserver) eq $dom) {
                   1068:             my $host=&hostname($tryserver);
                   1069:             my $queryid=
1.911     raeburn  1070:                 &reply("querysend:".&escape($query).':'.
                   1071:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1072:                        &escape($srch->{'srchtype'}).':'.
                   1073:                        &escape($srch->{'srchterm'}),$tryserver);
                   1074:             if ($queryid !~/^\Q$host\E\_/) {
                   1075:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1076:                 next;
1.899     raeburn  1077:             }
                   1078:             my $reply = &get_query_reply($queryid);
                   1079:             my $maxtries = 1;
                   1080:             my $tries = 1;
                   1081:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1082:                 $reply = &get_query_reply($queryid);
                   1083:                 $tries ++;
                   1084:             }
                   1085:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1086:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1087:             } else {
1.911     raeburn  1088:                 my @matches;
                   1089:                 if ($reply =~ /\n/) {
                   1090:                     @matches = split(/\n/,$reply);
                   1091:                 } else {
                   1092:                     @matches = split(/\&/,$reply);
                   1093:                 }
1.899     raeburn  1094:                 foreach my $match (@matches) {
                   1095:                     my ($uname,$udom,%userhash);
1.911     raeburn  1096:                     foreach my $entry (split(/:/,$match)) {
                   1097:                         my ($key,$value) =
                   1098:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1099:                         $userhash{$key} = $value;
                   1100:                         if ($key eq 'username') {
                   1101:                             $uname = $value;
                   1102:                         } elsif ($key eq 'domain') {
                   1103:                             $udom = $value;
1.911     raeburn  1104:                         }
1.899     raeburn  1105:                     }
                   1106:                     $results{$uname.':'.$udom} = \%userhash;
                   1107:                 }
                   1108:             }
                   1109:         }
                   1110:     }
                   1111:     return %results;
                   1112: }
                   1113: 
1.912     raeburn  1114: sub get_instuser {
                   1115:     my ($udom,$uname,$id) = @_;
                   1116:     my $homeserver = &domain($udom,'primary');
                   1117:     my ($outcome,%results);
                   1118:     if ($homeserver ne '') {
                   1119:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1120:                            &escape($id).':'.&escape($udom),$homeserver);
                   1121:         my $host=&hostname($homeserver);
                   1122:         if ($queryid !~/^\Q$host\E\_/) {
                   1123:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1124:             return;
                   1125:         }
                   1126:         my $response = &get_query_reply($queryid);
                   1127:         my $maxtries = 5;
                   1128:         my $tries = 1;
                   1129:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1130:             $response = &get_query_reply($queryid);
                   1131:             $tries ++;
                   1132:         }
                   1133:         if (!&error($response) && $response ne 'refused') {
                   1134:             if ($response eq 'unavailable') {
                   1135:                 $outcome = $response;
                   1136:             } else {
                   1137:                 $outcome = 'ok';
                   1138:                 my @matches = split(/\n/,$response);
                   1139:                 foreach my $match (@matches) {
                   1140:                     my ($key,$value) = split(/=/,$match);
                   1141:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1142:                 }
                   1143:             }
                   1144:         }
                   1145:     }
                   1146:     my %userinfo;
                   1147:     if (ref($results{$uname}) eq 'HASH') {
                   1148:         %userinfo = %{$results{$uname}};
                   1149:     } 
                   1150:     return ($outcome,%userinfo);
                   1151: }
                   1152: 
                   1153: sub inst_rulecheck {
1.923     raeburn  1154:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1155:     my %returnhash;
                   1156:     if ($udom ne '') {
                   1157:         if (ref($rules) eq 'ARRAY') {
                   1158:             @{$rules} = map {&escape($_);} (@{$rules});
                   1159:             my $rulestr = join(':',@{$rules});
                   1160:             my $homeserver=&domain($udom,'primary');
                   1161:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1162:                 my $response;
                   1163:                 if ($item eq 'username') {                
                   1164:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1165:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1166:                                               $homeserver));
1.923     raeburn  1167:                 } elsif ($item eq 'id') {
                   1168:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1169:                                               ':'.&escape($id).':'.$rulestr,
                   1170:                                               $homeserver));
1.945     raeburn  1171:                 } elsif ($item eq 'selfcreate') {
                   1172:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1173:                                                &escape($udom).':'.&escape($uname).
                   1174:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1175:                 }
1.912     raeburn  1176:                 if ($response ne 'refused') {
                   1177:                     my @pairs=split(/\&/,$response);
                   1178:                     foreach my $item (@pairs) {
                   1179:                         my ($key,$value)=split(/=/,$item,2);
                   1180:                         $key = &unescape($key);
                   1181:                         next if ($key =~ /^error: 2 /);
                   1182:                         $returnhash{$key}=&thaw_unescape($value);
                   1183:                     }
                   1184:                 }
                   1185:             }
                   1186:         }
                   1187:     }
                   1188:     return %returnhash;
                   1189: }
                   1190: 
                   1191: sub inst_userrules {
1.923     raeburn  1192:     my ($udom,$check) = @_;
1.912     raeburn  1193:     my (%ruleshash,@ruleorder);
                   1194:     if ($udom ne '') {
                   1195:         my $homeserver=&domain($udom,'primary');
                   1196:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1197:             my $response;
                   1198:             if ($check eq 'id') {
                   1199:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1200:                                  $homeserver);
1.943     raeburn  1201:             } elsif ($check eq 'email') {
                   1202:                 $response=&reply('instemailrules:'.&escape($udom),
                   1203:                                  $homeserver);
1.923     raeburn  1204:             } else {
                   1205:                 $response=&reply('instuserrules:'.&escape($udom),
                   1206:                                  $homeserver);
                   1207:             }
1.912     raeburn  1208:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1209:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1210:                 ($response ne 'no_such_host')) {
                   1211:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1212:                 my @pairs=split(/\&/,$hashitems);
                   1213:                 foreach my $item (@pairs) {
                   1214:                     my ($key,$value)=split(/=/,$item,2);
                   1215:                     $key = &unescape($key);
                   1216:                     next if ($key =~ /^error: 2 /);
                   1217:                     $ruleshash{$key}=&thaw_unescape($value);
                   1218:                 }
                   1219:                 my @esc_order = split(/\&/,$orderitems);
                   1220:                 foreach my $item (@esc_order) {
                   1221:                     push(@ruleorder,&unescape($item));
                   1222:                 }
                   1223:             }
                   1224:         }
                   1225:     }
                   1226:     return (\%ruleshash,\@ruleorder);
                   1227: }
                   1228: 
1.976     raeburn  1229: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1230: 
                   1231: sub get_domain_defaults {
                   1232:     my ($domain) = @_;
                   1233:     my $cachetime = 60*60*24;
1.976     raeburn  1234:     my ($defauthtype,$defautharg,$deflang,%deftools);
1.943     raeburn  1235:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1236:     if (defined($cached)) {
                   1237:         if (ref($result) eq 'HASH') {
                   1238:             return %{$result};
                   1239:         }
                   1240:     }
                   1241:     my %domdefaults;
                   1242:     my %domconfig =
1.976     raeburn  1243:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1244:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1245:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1246:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1247:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1248:     } else {
                   1249:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1250:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1251:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1252:     }
1.976     raeburn  1253:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1254:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1255:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1256:         } else {
                   1257:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1258:         } 
                   1259:         my @usertools = ('aboutme','blog','portfolio');
                   1260:         foreach my $item (@usertools) {
                   1261:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1262:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1263:             }
                   1264:         }
                   1265:     }
1.943     raeburn  1266:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1267:                                   $cachetime);
                   1268:     return %domdefaults;
                   1269: }
                   1270: 
1.344     www      1271: # --------------------------------------------------- Assign a key to a student
                   1272: 
                   1273: sub assign_access_key {
1.364     www      1274: #
                   1275: # a valid key looks like uname:udom#comments
                   1276: # comments are being appended
                   1277: #
1.498     www      1278:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1279:     $kdom=
1.620     albertel 1280:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1281:     $knum=
1.620     albertel 1282:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1283:     $cdom=
1.620     albertel 1284:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1285:     $cnum=
1.620     albertel 1286:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1287:     $udom=$env{'user.name'} unless (defined($udom));
                   1288:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1289:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1290:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1291:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1292:                                                   # assigned to this person
                   1293:                                                   # - this should not happen,
1.345     www      1294:                                                   # unless something went wrong
                   1295:                                                   # the first time around
                   1296: # ready to assign
1.364     www      1297:         $logentry=$1.'; '.$logentry;
1.496     www      1298:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1299:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1300: # key now belongs to user
1.346     www      1301: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1302:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1303:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1304:                 return 'ok';
                   1305:             } else {
                   1306:                 return 
                   1307:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1308: 	    }
                   1309:         } else {
                   1310:             return 'error: Could not assign key, try again later.';
                   1311:         }
1.364     www      1312:     } elsif (!$existing{$ckey}) {
1.345     www      1313: # the key does not exist
                   1314: 	return 'error: The key does not exist';
                   1315:     } else {
                   1316: # the key is somebody else's
                   1317: 	return 'error: The key is already in use';
                   1318:     }
1.344     www      1319: }
                   1320: 
1.364     www      1321: # ------------------------------------------ put an additional comment on a key
                   1322: 
                   1323: sub comment_access_key {
                   1324: #
                   1325: # a valid key looks like uname:udom#comments
                   1326: # comments are being appended
                   1327: #
                   1328:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1329:     $cdom=
1.620     albertel 1330:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1331:     $cnum=
1.620     albertel 1332:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1333:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1334:     if ($existing{$ckey}) {
                   1335:         $existing{$ckey}.='; '.$logentry;
                   1336: # ready to assign
1.367     www      1337:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1338:                                                  $cdom,$cnum) eq 'ok') {
                   1339: 	    return 'ok';
                   1340:         } else {
                   1341: 	    return 'error: Count not store comment.';
                   1342:         }
                   1343:     } else {
                   1344: # the key does not exist
                   1345: 	return 'error: The key does not exist';
                   1346:     }
                   1347: }
                   1348: 
1.344     www      1349: # ------------------------------------------------------ Generate a set of keys
                   1350: 
                   1351: sub generate_access_keys {
1.364     www      1352:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1353:     $cdom=
1.620     albertel 1354:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1355:     $cnum=
1.620     albertel 1356:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1357:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1358:     unless (($cdom) && ($cnum)) { return 0; }
                   1359:     if ($number>10000) { return 0; }
                   1360:     sleep(2); # make sure don't get same seed twice
                   1361:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1362:     my $total=0;
                   1363:     for (my $i=1;$i<=$number;$i++) {
                   1364:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1365:                   sprintf("%lx",int(100000*rand)).'-'.
                   1366:                   sprintf("%lx",int(100000*rand));
                   1367:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1368:        $newkey=~s/0/h/g; # and also 0 and O
                   1369:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1370:        if ($existing{$newkey}) {
                   1371:            $i--;
                   1372:        } else {
1.364     www      1373: 	  if (&put('accesskeys',
                   1374:               { $newkey => '# generated '.localtime().
1.620     albertel 1375:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1376:                            '; '.$logentry },
                   1377: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1378:               $total++;
                   1379: 	  }
                   1380:        }
                   1381:     }
1.620     albertel 1382:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1383:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1384:     return $total;
                   1385: }
                   1386: 
                   1387: # ------------------------------------------------------- Validate an accesskey
                   1388: 
                   1389: sub validate_access_key {
                   1390:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1391:     $cdom=
1.620     albertel 1392:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1393:     $cnum=
1.620     albertel 1394:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1395:     $udom=$env{'user.domain'} unless (defined($udom));
                   1396:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1397:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1398:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1399: }
                   1400: 
                   1401: # ------------------------------------- Find the section of student in a course
1.652     albertel 1402: sub devalidate_getsection_cache {
                   1403:     my ($udom,$unam,$courseid)=@_;
                   1404:     my $hashid="$udom:$unam:$courseid";
                   1405:     &devalidate_cache_new('getsection',$hashid);
                   1406: }
1.298     matthew  1407: 
1.815     albertel 1408: sub courseid_to_courseurl {
                   1409:     my ($courseid) = @_;
                   1410:     #already url style courseid
                   1411:     return $courseid if ($courseid =~ m{^/});
                   1412: 
                   1413:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1414: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1415: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1416: 	return "/$cdom/$cnum";
                   1417:     }
                   1418: 
                   1419:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1420:     if (exists($courseinfo{'num'})) {
                   1421: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1422:     }
                   1423: 
                   1424:     return undef;
                   1425: }
                   1426: 
1.298     matthew  1427: sub getsection {
                   1428:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1429:     my $cachetime=1800;
1.551     albertel 1430: 
                   1431:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1432:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1433:     if (defined($cached)) { return $result; }
                   1434: 
1.298     matthew  1435:     my %Pending; 
                   1436:     my %Expired;
                   1437:     #
                   1438:     # Each role can either have not started yet (pending), be active, 
                   1439:     #    or have expired.
                   1440:     #
                   1441:     # If there is an active role, we are done.
                   1442:     #
                   1443:     # If there is more than one role which has not started yet, 
                   1444:     #     choose the one which will start sooner
                   1445:     # If there is one role which has not started yet, return it.
                   1446:     #
                   1447:     # If there is more than one expired role, choose the one which ended last.
                   1448:     # If there is a role which has expired, return it.
                   1449:     #
1.815     albertel 1450:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1451:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1452:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1453:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1454:         my $section=$1;
                   1455:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1456:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1457:         my $now=time;
1.548     albertel 1458:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1459:             $Expired{$end}=$section;
                   1460:             next;
                   1461:         }
1.548     albertel 1462:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1463:             $Pending{$start}=$section;
                   1464:             next;
                   1465:         }
1.599     albertel 1466:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1467:     }
                   1468:     #
                   1469:     # Presumedly there will be few matching roles from the above
                   1470:     # loop and the sorting time will be negligible.
                   1471:     if (scalar(keys(%Pending))) {
                   1472:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1473:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1474:     } 
                   1475:     if (scalar(keys(%Expired))) {
                   1476:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1477:         my $time = pop(@sorted);
1.599     albertel 1478:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1479:     }
1.599     albertel 1480:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1481: }
1.70      www      1482: 
1.599     albertel 1483: sub save_cache {
                   1484:     &purge_remembered();
1.722     albertel 1485:     #&Apache::loncommon::validate_page();
1.620     albertel 1486:     undef(%env);
1.780     albertel 1487:     undef($env_loaded);
1.599     albertel 1488: }
1.452     albertel 1489: 
1.599     albertel 1490: my $to_remember=-1;
                   1491: my %remembered;
                   1492: my %accessed;
                   1493: my $kicks=0;
                   1494: my $hits=0;
1.849     albertel 1495: sub make_key {
                   1496:     my ($name,$id) = @_;
1.872     albertel 1497:     if (length($id) > 65 
                   1498: 	&& length(&escape($id)) > 200) {
                   1499: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1500:     }
1.849     albertel 1501:     return &escape($name.':'.$id);
                   1502: }
                   1503: 
1.599     albertel 1504: sub devalidate_cache_new {
                   1505:     my ($name,$id,$debug) = @_;
                   1506:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1507:     $id=&make_key($name,$id);
1.599     albertel 1508:     $memcache->delete($id);
                   1509:     delete($remembered{$id});
                   1510:     delete($accessed{$id});
                   1511: }
                   1512: 
                   1513: sub is_cached_new {
                   1514:     my ($name,$id,$debug) = @_;
1.849     albertel 1515:     $id=&make_key($name,$id);
1.599     albertel 1516:     if (exists($remembered{$id})) {
                   1517: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1518: 	$accessed{$id}=[&gettimeofday()];
                   1519: 	$hits++;
                   1520: 	return ($remembered{$id},1);
                   1521:     }
                   1522:     my $value = $memcache->get($id);
                   1523:     if (!(defined($value))) {
                   1524: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1525: 	return (undef,undef);
1.416     albertel 1526:     }
1.599     albertel 1527:     if ($value eq '__undef__') {
                   1528: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1529: 	$value=undef;
                   1530:     }
                   1531:     &make_room($id,$value,$debug);
                   1532:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1533:     return ($value,1);
                   1534: }
                   1535: 
                   1536: sub do_cache_new {
                   1537:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1538:     $id=&make_key($name,$id);
1.599     albertel 1539:     my $setvalue=$value;
                   1540:     if (!defined($setvalue)) {
                   1541: 	$setvalue='__undef__';
                   1542:     }
1.623     albertel 1543:     if (!defined($time) ) {
                   1544: 	$time=600;
                   1545:     }
1.599     albertel 1546:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1547:     my $result = $memcache->set($id,$setvalue,$time);
                   1548:     if (! $result) {
1.872     albertel 1549: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1550: 	$memcache->disconnect_all();
1.872     albertel 1551:     }
1.600     albertel 1552:     # need to make a copy of $value
1.919     albertel 1553:     &make_room($id,$value,$debug);
1.599     albertel 1554:     return $value;
                   1555: }
                   1556: 
                   1557: sub make_room {
                   1558:     my ($id,$value,$debug)=@_;
1.919     albertel 1559: 
                   1560:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1561:                                     : $value;
1.599     albertel 1562:     if ($to_remember<0) { return; }
                   1563:     $accessed{$id}=[&gettimeofday()];
                   1564:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1565:     my $to_kick;
                   1566:     my $max_time=0;
                   1567:     foreach my $other (keys(%accessed)) {
                   1568: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1569: 	    $to_kick=$other;
                   1570: 	    $max_time=&tv_interval($accessed{$other});
                   1571: 	}
                   1572:     }
                   1573:     delete($remembered{$to_kick});
                   1574:     delete($accessed{$to_kick});
                   1575:     $kicks++;
                   1576:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1577:     return;
                   1578: }
                   1579: 
1.599     albertel 1580: sub purge_remembered {
1.604     albertel 1581:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1582:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1583:     undef(%remembered);
                   1584:     undef(%accessed);
1.428     albertel 1585: }
1.70      www      1586: # ------------------------------------- Read an entry from a user's environment
                   1587: 
                   1588: sub userenvironment {
                   1589:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1590:     my $items;
                   1591:     foreach my $item (@what) {
                   1592:         $items.=&escape($item).'&';
                   1593:     }
                   1594:     $items=~s/\&$//;
1.70      www      1595:     my %returnhash=();
                   1596:     my @answer=split(/\&/,
1.976     raeburn  1597:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1598:                       &homeserver($unam,$udom)));
                   1599:     my $i;
                   1600:     for ($i=0;$i<=$#what;$i++) {
                   1601: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1602:     }
                   1603:     return %returnhash;
1.1       albertel 1604: }
                   1605: 
1.617     albertel 1606: # ---------------------------------------------------------- Get a studentphoto
                   1607: sub studentphoto {
                   1608:     my ($udom,$unam,$ext) = @_;
                   1609:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1610:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1611:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1612:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1613:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1614:             } else {
                   1615:                 my ($result,$perm_reqd)=
1.707     albertel 1616: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1617:                 if ($result eq 'ok') {
                   1618:                     if (!($perm_reqd eq 'yes')) {
                   1619:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1620:                     }
                   1621:                 }
                   1622:             }
                   1623:         }
                   1624:     } else {
                   1625:         my ($result,$perm_reqd) = 
1.707     albertel 1626: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1627:         if ($result eq 'ok') {
                   1628:             if (!($perm_reqd eq 'yes')) {
                   1629:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1630:             }
                   1631:         }
                   1632:     }
                   1633:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1634: }
                   1635: 
                   1636: sub retrievestudentphoto {
                   1637:     my ($udom,$unam,$ext,$type) = @_;
                   1638:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1639:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1640:     if ($ret eq 'ok') {
                   1641:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1642:         if ($type eq 'thumbnail') {
                   1643:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1644:         }
                   1645:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1646:         return $tokenurl;
                   1647:     } else {
                   1648:         if ($type eq 'thumbnail') {
                   1649:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1650:         } else { 
                   1651:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1652:         }
1.617     albertel 1653:     }
                   1654: }
                   1655: 
1.263     www      1656: # -------------------------------------------------------------------- New chat
                   1657: 
                   1658: sub chatsend {
1.724     raeburn  1659:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1660:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1661:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1662:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1663:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1664: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1665: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1666: }
                   1667: 
                   1668: # ------------------------------------------ Find current version of a resource
                   1669: 
                   1670: sub getversion {
                   1671:     my $fname=&clutter(shift);
                   1672:     unless ($fname=~/^\/res\//) { return -1; }
                   1673:     return &currentversion(&filelocation('',$fname));
                   1674: }
                   1675: 
                   1676: sub currentversion {
                   1677:     my $fname=shift;
1.599     albertel 1678:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1679:     if (defined($cached)) { return $result; }
1.292     www      1680:     my $author=$fname;
                   1681:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1682:     my ($udom,$uname)=split(/\//,$author);
                   1683:     my $home=homeserver($uname,$udom);
                   1684:     if ($home eq 'no_host') { 
                   1685:         return -1; 
                   1686:     }
                   1687:     my $answer=reply("currentversion:$fname",$home);
                   1688:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1689: 	return -1;
                   1690:     }
1.599     albertel 1691:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1692: }
                   1693: 
1.1       albertel 1694: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1695: 
1.1       albertel 1696: sub subscribe {
                   1697:     my $fname=shift;
1.761     raeburn  1698:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1699:     $fname=~s/[\n\r]//g;
1.1       albertel 1700:     my $author=$fname;
                   1701:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1702:     my ($udom,$uname)=split(/\//,$author);
                   1703:     my $home=homeserver($uname,$udom);
1.335     albertel 1704:     if ($home eq 'no_host') {
                   1705:         return 'not_found';
1.1       albertel 1706:     }
                   1707:     my $answer=reply("sub:$fname",$home);
1.64      www      1708:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1709: 	$answer.=' by '.$home;
                   1710:     }
1.1       albertel 1711:     return $answer;
                   1712: }
                   1713:     
1.8       www      1714: # -------------------------------------------------------------- Replicate file
                   1715: 
                   1716: sub repcopy {
                   1717:     my $filename=shift;
1.23      www      1718:     $filename=~s/\/+/\//g;
1.607     raeburn  1719:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1720:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1721:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1722: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1723: 	return &repcopy_userfile($filename);
                   1724:     }
1.532     albertel 1725:     $filename=~s/[\n\r]//g;
1.8       www      1726:     my $transname="$filename.in.transfer";
1.828     www      1727: # FIXME: this should flock
1.607     raeburn  1728:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1729:     my $remoteurl=subscribe($filename);
1.64      www      1730:     if ($remoteurl =~ /^con_lost by/) {
                   1731: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1732:            return 'unavailable';
1.8       www      1733:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1734: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1735: 	   return 'not_found';
1.64      www      1736:     } elsif ($remoteurl =~ /^rejected by/) {
                   1737: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1738:            return 'forbidden';
1.20      www      1739:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1740:            return 'ok';
1.8       www      1741:     } else {
1.290     www      1742:         my $author=$filename;
                   1743:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1744:         my ($udom,$uname)=split(/\//,$author);
                   1745:         my $home=homeserver($uname,$udom);
                   1746:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1747:            my @parts=split(/\//,$filename);
                   1748:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1749:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1750:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1751: 	       return 'bad_request';
1.8       www      1752:            }
                   1753:            my $count;
                   1754:            for ($count=5;$count<$#parts;$count++) {
                   1755:                $path.="/$parts[$count]";
                   1756:                if ((-e $path)!=1) {
                   1757: 		   mkdir($path,0777);
                   1758:                }
                   1759:            }
                   1760:            my $ua=new LWP::UserAgent;
                   1761:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1762:            my $response=$ua->request($request,$transname);
                   1763:            if ($response->is_error()) {
                   1764: 	       unlink($transname);
                   1765:                my $message=$response->status_line;
1.672     albertel 1766:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1767:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1768:                return 'unavailable';
1.8       www      1769:            } else {
1.16      www      1770: 	       if ($remoteurl!~/\.meta$/) {
                   1771:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1772:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1773:                   if ($mresponse->is_error()) {
                   1774: 		      unlink($filename.'.meta');
                   1775:                       &logthis(
1.672     albertel 1776:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1777:                   }
                   1778: 	       }
1.8       www      1779:                rename($transname,$filename);
1.607     raeburn  1780:                return 'ok';
1.8       www      1781:            }
1.290     www      1782:        }
1.8       www      1783:     }
1.330     www      1784: }
                   1785: 
                   1786: # ------------------------------------------------ Get server side include body
                   1787: sub ssi_body {
1.381     albertel 1788:     my ($filelink,%form)=@_;
1.606     matthew  1789:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1790:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1791:     }
1.953     www      1792:     my $output='';
                   1793:     my $response;
1.980   ! raeburn  1794:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1795:        ($output,$response)=&externalssi($filelink);
1.953     www      1796:     } else {
                   1797:        ($output,$response)=&ssi($filelink,%form);
                   1798:     }
1.778     albertel 1799:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1800:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1801:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1802:     if (wantarray) {
                   1803:         return ($output, $response);
                   1804:     } else {
                   1805:         return $output;
                   1806:     }
1.8       www      1807: }
                   1808: 
1.15      www      1809: # --------------------------------------------------------- Server Side Include
                   1810: 
1.782     albertel 1811: sub absolute_url {
                   1812:     my ($host_name) = @_;
                   1813:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1814:     if ($host_name eq '') {
                   1815: 	$host_name = $ENV{'SERVER_NAME'};
                   1816:     }
                   1817:     return $protocol.$host_name;
                   1818: }
                   1819: 
1.942     foxr     1820: #
                   1821: #   Server side include.
                   1822: # Parameters:
                   1823: #  fn     Possibly encrypted resource name/id.
                   1824: #  form   Hash that describes how the rendering should be done
                   1825: #         and other things.
1.944     foxr     1826: # Returns:
1.950     raeburn  1827: #   Scalar context: The content of the response.
                   1828: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1829: #     
1.15      www      1830: sub ssi {
                   1831: 
1.944     foxr     1832:     my ($fn,%form)=@_;
1.15      www      1833:     my $ua=new LWP::UserAgent;
1.23      www      1834:     my $request;
1.711     albertel 1835: 
                   1836:     $form{'no_update_last_known'}=1;
1.895     albertel 1837:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1838:     if (%form) {
1.782     albertel 1839:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1840:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1841:     } else {
1.782     albertel 1842:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1843:     }
                   1844: 
1.15      www      1845:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1846:     my $response=$ua->request($request);
                   1847: 
1.944     foxr     1848:     if (wantarray) {
                   1849: 	return ($response->content, $response);
                   1850:     } else {
                   1851: 	return $response->content;
1.942     foxr     1852:     }
1.324     www      1853: }
                   1854: 
                   1855: sub externalssi {
                   1856:     my ($url)=@_;
                   1857:     my $ua=new LWP::UserAgent;
                   1858:     my $request=new HTTP::Request('GET',$url);
                   1859:     my $response=$ua->request($request);
1.954     raeburn  1860:     if (wantarray) {
                   1861:         return ($response->content, $response);
                   1862:     } else {
                   1863:         return $response->content;
                   1864:     }
1.15      www      1865: }
1.254     www      1866: 
1.492     albertel 1867: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1868: 
                   1869: sub allowuploaded {
                   1870:     my ($srcurl,$url)=@_;
                   1871:     $url=&clutter(&declutter($url));
                   1872:     my $dir=$url;
                   1873:     $dir=~s/\/[^\/]+$//;
                   1874:     my %httpref=();
                   1875:     my $httpurl=&hreflocation('',$url);
                   1876:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1877:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1878: }
1.477     raeburn  1879: 
1.478     albertel 1880: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1881: # input: action, courseID, current domain, intended
1.637     raeburn  1882: #        path to file, source of file, instruction to parse file for objects,
                   1883: #        ref to hash for embedded objects,
                   1884: #        ref to hash for codebase of java objects.
                   1885: #
1.485     raeburn  1886: # output: url to file (if action was uploaddoc), 
                   1887: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1888: #
1.478     albertel 1889: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1890: # course.
1.477     raeburn  1891: #
1.478     albertel 1892: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1893: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1894: #          course's home server.
1.477     raeburn  1895: #
1.478     albertel 1896: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1897: #          be copied from $source (current location) to 
                   1898: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1899: #         and will then be copied to
                   1900: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1901: #         course's home server.
1.485     raeburn  1902: #
1.481     raeburn  1903: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1904: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1905: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1906: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1907: #         in course's home server.
1.637     raeburn  1908: #
1.477     raeburn  1909: 
                   1910: sub process_coursefile {
1.638     albertel 1911:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1912:     my $fetchresult;
1.638     albertel 1913:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1914:     if ($action eq 'propagate') {
1.638     albertel 1915:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1916: 			     $home);
1.481     raeburn  1917:     } else {
1.477     raeburn  1918:         my $fpath = '';
                   1919:         my $fname = $file;
1.478     albertel 1920:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1921:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1922:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1923:         if ($action eq 'copy') {
                   1924:             if ($source eq '') {
                   1925:                 $fetchresult = 'no source file';
                   1926:                 return $fetchresult;
                   1927:             } else {
                   1928:                 my $destination = $filepath.'/'.$fname;
                   1929:                 rename($source,$destination);
                   1930:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1931:                                  $home);
1.481     raeburn  1932:             }
                   1933:         } elsif ($action eq 'uploaddoc') {
                   1934:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1935:             print $fh $env{'form.'.$source};
1.481     raeburn  1936:             close($fh);
1.637     raeburn  1937:             if ($parser eq 'parse') {
1.961     raeburn  1938:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1939:                 unless ($parse_result eq 'ok') {
                   1940:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1941:                 }
                   1942:             }
1.477     raeburn  1943:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1944:                                  $home);
1.481     raeburn  1945:             if ($fetchresult eq 'ok') {
                   1946:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1947:             } else {
                   1948:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1949:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1950:                 return '/adm/notfound.html';
                   1951:             }
1.477     raeburn  1952:         }
                   1953:     }
1.485     raeburn  1954:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1955:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1956:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1957:     }
                   1958:     return $fetchresult;
                   1959: }
                   1960: 
1.637     raeburn  1961: sub build_filepath {
                   1962:     my ($fpath) = @_;
                   1963:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1964:     unless ($fpath eq '') {
                   1965:         my @parts=split('/',$fpath);
                   1966:         foreach my $part (@parts) {
                   1967:             $filepath.= '/'.$part;
                   1968:             if ((-e $filepath)!=1) {
                   1969:                 mkdir($filepath,0777);
                   1970:             }
                   1971:         }
                   1972:     }
                   1973:     return $filepath;
                   1974: }
                   1975: 
                   1976: sub store_edited_file {
1.638     albertel 1977:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1978:     my $file = $primary_url;
                   1979:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1980:     my $fpath = '';
                   1981:     my $fname = $file;
                   1982:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1983:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1984:     my $filepath = &build_filepath($fpath);
                   1985:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1986:     print $fh $content;
                   1987:     close($fh);
1.638     albertel 1988:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1989:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1990: 			  $home);
1.637     raeburn  1991:     if ($$fetchresult eq 'ok') {
                   1992:         return '/uploaded/'.$fpath.'/'.$fname;
                   1993:     } else {
1.638     albertel 1994:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1995: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1996:         return '/adm/notfound.html';
                   1997:     }
                   1998: }
                   1999: 
1.531     albertel 2000: sub clean_filename {
1.831     albertel 2001:     my ($fname,$args)=@_;
1.315     www      2002: # Replace Windows backslashes by forward slashes
1.257     www      2003:     $fname=~s/\\/\//g;
1.831     albertel 2004:     if (!$args->{'keep_path'}) {
                   2005:         # Get rid of everything but the actual filename
                   2006: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2007:     }
1.315     www      2008: # Replace spaces by underscores
                   2009:     $fname=~s/\s+/\_/g;
                   2010: # Replace all other weird characters by nothing
1.831     albertel 2011:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2012: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2013: # numbers
                   2014:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2015:     return $fname;
                   2016: }
                   2017: 
1.977     amueller 2018: #Wrapper function for userphotoupload
                   2019: sub userphotoupload
                   2020: {
                   2021: 	my($formname,$subdir) = @_;
                   2022: 	$upload_photo_form = 1;
                   2023: 	return &userfileupload($formname,undef,$subdir);
                   2024: }
                   2025: 
1.608     albertel 2026: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2027: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2028: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2029: #        $coursedoc - if true up to the current course
                   2030: #                     if false
                   2031: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2032: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2033: #        $allfiles - reference to hash for embedded objects
                   2034: #        $codebase - reference to hash for codebase of java objects
                   2035: #        $desuname - username for permanent storage of uploaded file
                   2036: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2037: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2038: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2039: # 
1.686     albertel 2040: # output: url of file in userspace, or error: <message> 
                   2041: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2042: 
                   2043: 
1.531     albertel 2044: sub userfileupload {
1.860     raeburn  2045:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2046:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2047:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2048:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2049:     $fname=&clean_filename($fname);
1.315     www      2050: # See if there is anything left
1.257     www      2051:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2052:     chop($env{'form.'.$formname});
1.523     raeburn  2053:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2054:         my $now = time;
                   2055:         my $filepath = 'tmp/helprequests/'.$now;
                   2056:         my @parts=split(/\//,$filepath);
                   2057:         my $fullpath = $perlvar{'lonDaemons'};
                   2058:         for (my $i=0;$i<@parts;$i++) {
                   2059:             $fullpath .= '/'.$parts[$i];
                   2060:             if ((-e $fullpath)!=1) {
                   2061:                 mkdir($fullpath,0777);
                   2062:             }
                   2063:         }
                   2064:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2065:         print $fh $env{'form.'.$formname};
1.523     raeburn  2066:         close($fh);
1.741     raeburn  2067:         return $fullpath.'/'.$fname;
                   2068:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2069:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2070:                        '_'.$env{'user.domain'}.'/pending';
                   2071:         my @parts=split(/\//,$filepath);
                   2072:         my $fullpath = $perlvar{'lonDaemons'};
                   2073:         for (my $i=0;$i<@parts;$i++) {
                   2074:             $fullpath .= '/'.$parts[$i];
                   2075:             if ((-e $fullpath)!=1) {
                   2076:                 mkdir($fullpath,0777);
                   2077:             }
                   2078:         }
                   2079:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2080:         print $fh $env{'form.'.$formname};
                   2081:         close($fh);
                   2082:         return $fullpath.'/'.$fname;
1.523     raeburn  2083:     }
1.719     banghart 2084:     
1.258     www      2085: # Create the directory if not present
1.493     albertel 2086:     $fname="$subdir/$fname";
1.259     www      2087:     if ($coursedoc) {
1.638     albertel 2088: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2089: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2090:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2091:             return &finishuserfileupload($docuname,$docudom,
                   2092: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2093: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2094:         } else {
1.620     albertel 2095:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2096:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2097: 				       $fname,$formname,$parser,
                   2098: 				       $allfiles,$codebase);
1.481     raeburn  2099:         }
1.719     banghart 2100:     } elsif (defined($destuname)) {
                   2101:         my $docuname=$destuname;
                   2102:         my $docudom=$destudom;
1.860     raeburn  2103: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2104: 				     $parser,$allfiles,$codebase,
                   2105:                                      $thumbwidth,$thumbheight);
1.719     banghart 2106:         
1.259     www      2107:     } else {
1.638     albertel 2108:         my $docuname=$env{'user.name'};
                   2109:         my $docudom=$env{'user.domain'};
1.714     raeburn  2110:         if (exists($env{'form.group'})) {
                   2111:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2112:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2113:         }
1.860     raeburn  2114: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2115: 				     $parser,$allfiles,$codebase,
                   2116:                                      $thumbwidth,$thumbheight);
1.259     www      2117:     }
1.271     www      2118: }
                   2119: 
                   2120: sub finishuserfileupload {
1.860     raeburn  2121:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2122:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2123:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2124:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2125:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2126:     $file=$fname;
                   2127:     if ($fname=~m|/|) {
                   2128:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2129: 	$path.=$fnamepath.'/';
                   2130:     }
1.259     www      2131:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2132:     my $count;
                   2133:     for ($count=4;$count<=$#parts;$count++) {
                   2134:         $filepath.="/$parts[$count]";
                   2135:         if ((-e $filepath)!=1) {
                   2136: 	    mkdir($filepath,0777);
                   2137:         }
                   2138:     }
                   2139: # Save the file
                   2140:     {
1.701     albertel 2141: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2142: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2143: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2144: 	    return '/adm/notfound.html';
                   2145: 	}
                   2146: 	if (!print FH ($env{'form.'.$formname})) {
                   2147: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2148: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2149: 	    return '/adm/notfound.html';
                   2150: 	}
1.570     albertel 2151: 	close(FH);
1.977     amueller 2152: 	if($upload_photo_form==1)
                   2153: 	{
                   2154: 		my $ima = Image::Magick->new;                       
                   2155:             	$ima->Read($filepath.'/'.$file);
                   2156: 		if($ima->Get('width') > 300)
                   2157: 		{
                   2158: 			my $factor = $ima->Get('width')/300;
                   2159:              		$ima->Scale( width=>300, height=>$ima->Get('height')/$factor );
                   2160: 		}
                   2161: 		if($ima->Get('height') > 400)
                   2162:                 {
                   2163:                         my $factor = $ima->Get('height')/400;
                   2164:                         $ima->Scale( width=>$ima->Get('width')/$factor, height=>400);
                   2165:                 }
                   2166:  
                   2167: 		
                   2168: 		$ima->Write($filepath.'/'.$file);
                   2169: 		$upload_photo_form = 0;
                   2170: 	}
1.258     www      2171:     }
1.637     raeburn  2172:     if ($parser eq 'parse') {
1.961     raeburn  2173:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2174: 						   $codebase);
1.637     raeburn  2175:         unless ($parse_result eq 'ok') {
1.638     albertel 2176:             &logthis('Failed to parse '.$filepath.$file.
                   2177: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2178:         }
                   2179:     }
1.860     raeburn  2180:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2181:         my $input = $filepath.'/'.$file;
                   2182:         my $output = $filepath.'/'.'tn-'.$file;
                   2183:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2184:         system("convert -sample $thumbsize $input $output");
                   2185:         if (-e $filepath.'/'.'tn-'.$file) {
                   2186:             $fetchthumb  = 1; 
                   2187:         }
                   2188:     }
1.858     raeburn  2189:  
1.259     www      2190: # Notify homeserver to grep it
                   2191: #
1.638     albertel 2192:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2193:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2194:     if ($fetchresult eq 'ok') {
1.860     raeburn  2195:         if ($fetchthumb) {
                   2196:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2197:             if ($thumbresult ne 'ok') {
                   2198:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2199:                          $docuhome.': '.$thumbresult);
                   2200:             }
                   2201:         }
1.259     www      2202: #
1.258     www      2203: # Return the URL to it
1.494     albertel 2204:         return '/uploaded/'.$path.$file;
1.263     www      2205:     } else {
1.494     albertel 2206:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2207: 		 ': '.$fetchresult);
1.263     www      2208:         return '/adm/notfound.html';
1.858     raeburn  2209:     }
1.493     albertel 2210: }
                   2211: 
1.637     raeburn  2212: sub extract_embedded_items {
1.961     raeburn  2213:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2214:     my @state = ();
                   2215:     my %javafiles = (
                   2216:                       codebase => '',
                   2217:                       code => '',
                   2218:                       archive => ''
                   2219:                     );
                   2220:     my %mediafiles = (
                   2221:                       src => '',
                   2222:                       movie => '',
                   2223:                      );
1.648     raeburn  2224:     my $p;
                   2225:     if ($content) {
                   2226:         $p = HTML::LCParser->new($content);
                   2227:     } else {
1.961     raeburn  2228:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2229:     }
1.641     albertel 2230:     while (my $t=$p->get_token()) {
1.640     albertel 2231: 	if ($t->[0] eq 'S') {
                   2232: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2233: 	    push(@state, $tagname);
1.648     raeburn  2234:             if (lc($tagname) eq 'allow') {
                   2235:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2236:             }
1.640     albertel 2237: 	    if (lc($tagname) eq 'img') {
                   2238: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2239: 	    }
1.886     albertel 2240: 	    if (lc($tagname) eq 'a') {
                   2241: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2242: 	    }
1.645     raeburn  2243:             if (lc($tagname) eq 'script') {
                   2244:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2245:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2246:                 } else {
                   2247:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2248:                 }
                   2249:             }
                   2250:             if (lc($tagname) eq 'link') {
                   2251:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2252:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2253:                 }
                   2254:             }
1.640     albertel 2255: 	    if (lc($tagname) eq 'object' ||
                   2256: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2257: 		foreach my $item (keys(%javafiles)) {
                   2258: 		    $javafiles{$item} = '';
                   2259: 		}
                   2260: 	    }
                   2261: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2262: 		my $name = lc($attr->{'name'});
                   2263: 		foreach my $item (keys(%javafiles)) {
                   2264: 		    if ($name eq $item) {
                   2265: 			$javafiles{$item} = $attr->{'value'};
                   2266: 			last;
                   2267: 		    }
                   2268: 		}
                   2269: 		foreach my $item (keys(%mediafiles)) {
                   2270: 		    if ($name eq $item) {
                   2271: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2272: 			last;
                   2273: 		    }
                   2274: 		}
                   2275: 	    }
                   2276: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2277: 		foreach my $item (keys(%javafiles)) {
                   2278: 		    if ($attr->{$item}) {
                   2279: 			$javafiles{$item} = $attr->{$item};
                   2280: 			last;
                   2281: 		    }
                   2282: 		}
                   2283: 		foreach my $item (keys(%mediafiles)) {
                   2284: 		    if ($attr->{$item}) {
                   2285: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2286: 			last;
                   2287: 		    }
                   2288: 		}
                   2289: 	    }
                   2290: 	} elsif ($t->[0] eq 'E') {
                   2291: 	    my ($tagname) = ($t->[1]);
                   2292: 	    if ($javafiles{'codebase'} ne '') {
                   2293: 		$javafiles{'codebase'} .= '/';
                   2294: 	    }  
                   2295: 	    if (lc($tagname) eq 'applet' ||
                   2296: 		lc($tagname) eq 'object' ||
                   2297: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2298: 		) {
                   2299: 		foreach my $item (keys(%javafiles)) {
                   2300: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2301: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2302: 			&add_filetype($allfiles,$file,$item);
                   2303: 		    }
                   2304: 		}
                   2305: 	    } 
                   2306: 	    pop @state;
                   2307: 	}
                   2308:     }
1.637     raeburn  2309:     return 'ok';
                   2310: }
                   2311: 
1.639     albertel 2312: sub add_filetype {
                   2313:     my ($allfiles,$file,$type)=@_;
                   2314:     if (exists($allfiles->{$file})) {
                   2315: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2316: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2317: 	}
                   2318:     } else {
                   2319: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2320:     }
                   2321: }
                   2322: 
1.493     albertel 2323: sub removeuploadedurl {
                   2324:     my ($url)=@_;
                   2325:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2326:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2327: }
                   2328: 
                   2329: sub removeuserfile {
                   2330:     my ($docuname,$docudom,$fname)=@_;
                   2331:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2332:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2333:     if ($result eq 'ok') {
                   2334:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2335:             my $metafile = $fname.'.meta';
                   2336:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2337: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2338:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2339:             my $sqlresult = 
1.823     albertel 2340:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2341:                                         'portfolio_metadata',$group,
                   2342:                                         'delete');
1.798     raeburn  2343:         }
                   2344:     }
                   2345:     return $result;
1.257     www      2346: }
1.15      www      2347: 
1.530     albertel 2348: sub mkdiruserfile {
                   2349:     my ($docuname,$docudom,$dir)=@_;
                   2350:     my $home=&homeserver($docuname,$docudom);
                   2351:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2352: }
                   2353: 
1.531     albertel 2354: sub renameuserfile {
                   2355:     my ($docuname,$docudom,$old,$new)=@_;
                   2356:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2357:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2358:                         &escape("$old").':'.&escape("$new"),$home);
                   2359:     if ($result eq 'ok') {
                   2360:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2361:             my $oldmeta = $old.'.meta';
                   2362:             my $newmeta = $new.'.meta';
                   2363:             my $metaresult = 
                   2364:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2365: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2366:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2367:             my $sqlresult = 
1.823     albertel 2368:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2369:                                         'portfolio_metadata',$group,
                   2370:                                         'delete');
1.798     raeburn  2371:         }
                   2372:     }
                   2373:     return $result;
1.531     albertel 2374: }
                   2375: 
1.14      www      2376: # ------------------------------------------------------------------------- Log
                   2377: 
                   2378: sub log {
                   2379:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2380:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2381: }
                   2382: 
                   2383: # ------------------------------------------------------------------ Course Log
1.352     www      2384: #
                   2385: # This routine flushes several buffers of non-mission-critical nature
                   2386: #
1.157     www      2387: 
                   2388: sub flushcourselogs {
1.352     www      2389:     &logthis('Flushing log buffers');
                   2390: #
                   2391: # course logs
                   2392: # This is a log of all transactions in a course, which can be used
                   2393: # for data mining purposes
                   2394: #
                   2395: # It also collects the courseid database, which lists last transaction
                   2396: # times and course titles for all courseids
                   2397: #
                   2398:     my %courseidbuffer=();
1.921     raeburn  2399:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2400:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2401: 		          &escape($courselogs{$crsid}),
                   2402: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2403: 	    delete $courselogs{$crsid};
                   2404:         } else {
                   2405:             &logthis('Failed to flush log buffer for '.$crsid);
                   2406:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2407:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2408:                         " exceeded maximum size, deleting.</font>");
                   2409:                delete $courselogs{$crsid};
                   2410:             }
1.352     www      2411:         }
1.920     raeburn  2412:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2413:             'description' => $coursedescrbuf{$crsid},
                   2414:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2415:             'type'        => $coursetypebuf{$crsid},
                   2416:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2417:         };
1.191     harris41 2418:     }
1.352     www      2419: #
                   2420: # Write course id database (reverse lookup) to homeserver of courses 
                   2421: # Is used in pickcourse
                   2422: #
1.840     albertel 2423:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2424:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2425:                                     $courseidbuffer{$crs_home},
                   2426:                                     $crs_home,'timeonly');
1.352     www      2427:     }
                   2428: #
                   2429: # File accesses
                   2430: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2431: #
1.449     matthew  2432:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2433:         if ($entry =~ /___count$/) {
                   2434:             my ($dom,$name);
1.807     albertel 2435:             ($dom,$name,undef)=
1.811     albertel 2436: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2437:             if (! defined($dom) || $dom eq '' || 
                   2438:                 ! defined($name) || $name eq '') {
1.620     albertel 2439:                 my $cid = $env{'request.course.id'};
                   2440:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2441:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2442:             }
1.450     matthew  2443:             my $value = $accesshash{$entry};
                   2444:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2445:             my %temphash=($url => $value);
1.449     matthew  2446:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2447:             if ($result eq 'ok') {
                   2448:                 delete $accesshash{$entry};
                   2449:             } elsif ($result eq 'unknown_cmd') {
                   2450:                 # Target server has old code running on it.
1.450     matthew  2451:                 my %temphash=($entry => $value);
1.449     matthew  2452:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2453:                     delete $accesshash{$entry};
                   2454:                 }
                   2455:             }
                   2456:         } else {
1.811     albertel 2457:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2458:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2459:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2460:                 delete $accesshash{$entry};
                   2461:             }
1.185     www      2462:         }
1.191     harris41 2463:     }
1.352     www      2464: #
                   2465: # Roles
                   2466: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2467: #
1.800     albertel 2468:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2469:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2470: 	    split(/\:/,$entry);
                   2471:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2472:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2473:                 $rudom,$runame) eq 'ok') {
                   2474: 	    delete $userrolehash{$entry};
                   2475:         }
                   2476:     }
1.662     raeburn  2477: #
                   2478: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2479: #
                   2480:     my %domrolebuffer = ();
                   2481:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2482:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2483:         if ($domrolebuffer{$rudom}) {
                   2484:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2485:                       '='.&escape($domainrolehash{$entry});
                   2486:         } else {
                   2487:             $domrolebuffer{$rudom}.=&escape($entry).
                   2488:                       '='.&escape($domainrolehash{$entry});
                   2489:         }
                   2490:         delete $domainrolehash{$entry};
                   2491:     }
                   2492:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2493: 	my %servers = &get_servers($dom,'library');
                   2494: 	foreach my $tryserver (keys(%servers)) {
                   2495: 	    unless (&reply('domroleput:'.$dom.':'.
                   2496: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2497: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2498: 	    }
1.662     raeburn  2499:         }
                   2500:     }
1.186     www      2501:     $dumpcount++;
1.157     www      2502: }
                   2503: 
                   2504: sub courselog {
                   2505:     my $what=shift;
1.158     www      2506:     $what=time.':'.$what;
1.620     albertel 2507:     unless ($env{'request.course.id'}) { return ''; }
                   2508:     $coursedombuf{$env{'request.course.id'}}=
                   2509:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2510:     $coursenumbuf{$env{'request.course.id'}}=
                   2511:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2512:     $coursehombuf{$env{'request.course.id'}}=
                   2513:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2514:     $coursedescrbuf{$env{'request.course.id'}}=
                   2515:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2516:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2517:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2518:     $courseownerbuf{$env{'request.course.id'}}=
                   2519:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2520:     $coursetypebuf{$env{'request.course.id'}}=
                   2521:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2522:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2523: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2524:     } else {
1.620     albertel 2525: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2526:     }
1.620     albertel 2527:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2528: 	&flushcourselogs();
                   2529:     }
1.158     www      2530: }
                   2531: 
                   2532: sub courseacclog {
                   2533:     my $fnsymb=shift;
1.620     albertel 2534:     unless ($env{'request.course.id'}) { return ''; }
                   2535:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2536:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2537:         $what.=':POST';
1.583     matthew  2538:         # FIXME: Probably ought to escape things....
1.800     albertel 2539: 	foreach my $key (keys(%env)) {
                   2540:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2541:                 my $formitem = $1;
                   2542:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2543:                     $what.=':'.$formitem.'='.$env{$key};
                   2544:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2545:                     $what.=':'.$formitem.'='.$env{$key};
                   2546:                 }
1.158     www      2547:             }
1.191     harris41 2548:         }
1.583     matthew  2549:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2550:         # FIXME: We should not be depending on a form parameter that someone
                   2551:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2552:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2553:             $what.= ':POST';
                   2554:             # FIXME: Probably ought to escape things....
                   2555:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2556:                                  'crsdiscuss') {
1.620     albertel 2557:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2558:             }
                   2559:         }
1.158     www      2560:     }
                   2561:     &courselog($what);
1.149     www      2562: }
                   2563: 
1.185     www      2564: sub countacc {
                   2565:     my $url=&declutter(shift);
1.458     matthew  2566:     return if (! defined($url) || $url eq '');
1.620     albertel 2567:     unless ($env{'request.course.id'}) { return ''; }
                   2568:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2569:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2570:     $accesshash{$key}++;
1.185     www      2571: }
1.349     www      2572: 
1.361     www      2573: sub linklog {
                   2574:     my ($from,$to)=@_;
                   2575:     $from=&declutter($from);
                   2576:     $to=&declutter($to);
                   2577:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2578:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2579: }
                   2580:   
1.349     www      2581: sub userrolelog {
                   2582:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2583:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2584:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2585:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2586:         ($trole=~/^ta/)) {
1.350     www      2587:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2588:        $userrolehash
                   2589:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2590:                     =$tend.':'.$tstart;
1.662     raeburn  2591:     }
1.898     albertel 2592:     if (($env{'request.role'} =~ /dc\./) &&
                   2593: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2594: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2595: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2596:        $userrolehash
                   2597:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2598:                     =$tend.':'.$tstart;
                   2599:     }
1.662     raeburn  2600:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2601:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2602:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2603:         ($trole=~/^sc/)) {
                   2604:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2605:        $domainrolehash
                   2606:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2607:                     = $tend.':'.$tstart;
                   2608:     }
1.351     www      2609: }
                   2610: 
1.957     raeburn  2611: sub courserolelog {
                   2612:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2613:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2614:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2615:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2616:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2617:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2618:             my $cdom = $1;
                   2619:             my $cnum = $2;
                   2620:             my $sec = $3;
                   2621:             my $namespace = 'rolelog';
                   2622:             my %storehash = (
                   2623:                                role    => $trole,
                   2624:                                start   => $tstart,
                   2625:                                end     => $tend,
                   2626:                                selfenroll => $selfenroll,
                   2627:                                context    => $context,
                   2628:                             );
                   2629:             if ($trole eq 'gr') {
                   2630:                 $namespace = 'groupslog';
                   2631:                 $storehash{'group'} = $sec;
                   2632:             } else {
                   2633:                 $storehash{'section'} = $sec;
                   2634:             }
                   2635:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2636:         }
                   2637:     }
                   2638:     return;
                   2639: }
                   2640: 
1.351     www      2641: sub get_course_adv_roles {
1.948     raeburn  2642:     my ($cid,$codes) = @_;
1.620     albertel 2643:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2644:     my %coursehash=&coursedescription($cid);
1.470     www      2645:     my %nothide=();
1.800     albertel 2646:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2647:         if ($user !~ /:/) {
                   2648: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2649:         } else {
                   2650:             $nothide{$user}=1;
                   2651:         }
1.470     www      2652:     }
1.351     www      2653:     my %returnhash=();
                   2654:     my %dumphash=
                   2655:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2656:     my $now=time;
1.800     albertel 2657:     foreach my $entry (keys %dumphash) {
                   2658: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2659:         if (($tstart) && ($tstart<0)) { next; }
                   2660:         if (($tend) && ($tend<$now)) { next; }
                   2661:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2662:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2663: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2664: 	if ((&privileged($username,$domain)) && 
                   2665: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2666: 	if ($role eq 'cr') { next; }
1.948     raeburn  2667:         if ($codes) {
                   2668:             if ($section) { $role .= ':'.$section; }
                   2669:             if ($returnhash{$role}) {
                   2670:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2671:             } else {
                   2672:                 $returnhash{$role}=$username.':'.$domain;
                   2673:             }
1.351     www      2674:         } else {
1.948     raeburn  2675:             my $key=&plaintext($role);
1.973     bisitz   2676:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2677:             if ($returnhash{$key}) {
                   2678: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2679:             } else {
                   2680:                 $returnhash{$key}=$username.':'.$domain;
                   2681:             }
1.351     www      2682:         }
1.948     raeburn  2683:     }
1.400     www      2684:     return %returnhash;
                   2685: }
                   2686: 
                   2687: sub get_my_roles {
1.937     raeburn  2688:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2689:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2690:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2691:     my (%dumphash,%nothide);
1.858     raeburn  2692:     if ($context eq 'userroles') { 
                   2693:         %dumphash = &dump('roles',$udom,$uname);
                   2694:     } else {
                   2695:         %dumphash=
1.400     www      2696:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2697:         if ($hidepriv) {
                   2698:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2699:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2700:                 if ($user !~ /:/) {
                   2701:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2702:                 } else {
                   2703:                     $nothide{$user} = 1;
                   2704:                 }
                   2705:             }
                   2706:         }
1.858     raeburn  2707:     }
1.400     www      2708:     my %returnhash=();
                   2709:     my $now=time;
1.800     albertel 2710:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2711:         my ($role,$tend,$tstart);
                   2712:         if ($context eq 'userroles') {
                   2713: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2714:         } else {
                   2715:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2716:         }
1.400     www      2717:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2718:         my $status = 'active';
1.939     raeburn  2719:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2720:             $status = 'previous';
                   2721:         } 
                   2722:         if (($tstart) && ($now<$tstart)) {
                   2723:             $status = 'future';
                   2724:         }
                   2725:         if (ref($types) eq 'ARRAY') {
                   2726:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2727:                 next;
                   2728:             } 
                   2729:         } else {
                   2730:             if ($status ne 'active') {
                   2731:                 next;
                   2732:             }
                   2733:         }
1.867     raeburn  2734:         my ($rolecode,$username,$domain,$section,$area);
                   2735:         if ($context eq 'userroles') {
                   2736:             ($area,$rolecode) = split(/_/,$entry);
                   2737:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2738:         } else {
                   2739:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2740:         }
1.832     raeburn  2741:         if (ref($roledoms) eq 'ARRAY') {
                   2742:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2743:                 next;
                   2744:             }
                   2745:         }
                   2746:         if (ref($roles) eq 'ARRAY') {
                   2747:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2748:                 if ($role =~ /^cr\//) {
                   2749:                     if (!grep(/^cr$/,@{$roles})) {
                   2750:                         next;
                   2751:                     }
                   2752:                 } else {
                   2753:                     next;
                   2754:                 }
1.832     raeburn  2755:             }
1.867     raeburn  2756:         }
1.937     raeburn  2757:         if ($hidepriv) {
                   2758:             if ((&privileged($username,$domain)) &&
                   2759:                 (!$nothide{$username.':'.$domain})) { 
                   2760:                 next;
                   2761:             }
                   2762:         }
1.933     raeburn  2763:         if ($withsec) {
                   2764:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2765:                 $tstart.':'.$tend;
                   2766:         } else {
                   2767:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2768:         }
1.832     raeburn  2769:     }
1.373     www      2770:     return %returnhash;
1.399     www      2771: }
                   2772: 
                   2773: # ----------------------------------------------------- Frontpage Announcements
                   2774: #
                   2775: #
                   2776: 
                   2777: sub postannounce {
                   2778:     my ($server,$text)=@_;
1.844     albertel 2779:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2780:     unless ($text=~/\w/) { $text=''; }
                   2781:     return &reply('setannounce:'.&escape($text),$server);
                   2782: }
                   2783: 
                   2784: sub getannounce {
1.448     albertel 2785: 
                   2786:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2787: 	my $announcement='';
1.800     albertel 2788: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2789: 	close($fh);
1.399     www      2790: 	if ($announcement=~/\w/) { 
                   2791: 	    return 
                   2792:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2793:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2794: 	} else {
                   2795: 	    return '';
                   2796: 	}
                   2797:     } else {
                   2798: 	return '';
                   2799:     }
1.351     www      2800: }
1.353     www      2801: 
                   2802: # ---------------------------------------------------------- Course ID routines
                   2803: # Deal with domain's nohist_courseid.db files
                   2804: #
                   2805: 
                   2806: sub courseidput {
1.921     raeburn  2807:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2808:     my $outcome;
                   2809:     if ($caller eq 'timeonly') {
                   2810:         my $cids = '';
                   2811:         foreach my $item (keys(%$storehash)) {
                   2812:             $cids.=&escape($item).'&';
                   2813:         }
                   2814:         $cids=~s/\&$//;
                   2815:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2816:                           $coursehome);       
                   2817:     } else {
                   2818:         my $items = '';
                   2819:         foreach my $item (keys(%$storehash)) {
                   2820:             $items.= &escape($item).'='.
                   2821:                      &freeze_escape($$storehash{$item}).'&';
                   2822:         }
                   2823:         $items=~s/\&$//;
                   2824:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2825:                           $coursehome);
1.918     raeburn  2826:     }
                   2827:     if ($outcome eq 'unknown_cmd') {
                   2828:         my $what;
                   2829:         foreach my $cid (keys(%$storehash)) {
                   2830:             $what .= &escape($cid).'=';
1.921     raeburn  2831:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2832:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2833:             }
                   2834:             $what =~ s/\:$/&/;
                   2835:         }
                   2836:         $what =~ s/\&$//;  
                   2837:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2838:     } else {
                   2839:         return $outcome;
                   2840:     }
1.353     www      2841: }
                   2842: 
                   2843: sub courseiddump {
1.921     raeburn  2844:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2845:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2846:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2847:     my $as_hash = 1;
                   2848:     my %returnhash;
                   2849:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2850:     my %libserv = &all_library();
                   2851:     foreach my $tryserver (keys(%libserv)) {
                   2852:         if ( (  $hostidflag == 1 
                   2853: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2854: 	     || (!defined($hostidflag)) ) {
                   2855: 
1.918     raeburn  2856: 	    if (($domfilter eq '') ||
                   2857: 		(&host_domain($tryserver) eq $domfilter)) {
                   2858:                 my $rep = 
                   2859:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2860:                          $sincefilter.':'.&escape($descfilter).':'.
                   2861:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2862:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2863:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2864:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2865:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2866:                 my @pairs=split(/\&/,$rep);
                   2867:                 foreach my $item (@pairs) {
                   2868:                     my ($key,$value)=split(/\=/,$item,2);
                   2869:                     $key = &unescape($key);
                   2870:                     next if ($key =~ /^error: 2 /);
                   2871:                     my $result = &thaw_unescape($value);
                   2872:                     if (ref($result) eq 'HASH') {
                   2873:                         $returnhash{$key}=$result;
                   2874:                     } else {
1.921     raeburn  2875:                         my @responses = split(/:/,$value);
                   2876:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2877:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2878:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2879:                         }
                   2880:                     } 
1.353     www      2881:                 }
                   2882:             }
                   2883:         }
                   2884:     }
                   2885:     return %returnhash;
                   2886: }
                   2887: 
1.658     raeburn  2888: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2889: 
                   2890: sub dcmailput {
1.685     raeburn  2891:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2892:     my $status = &Apache::lonnet::critical(
1.740     www      2893:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2894:        &escape($message),$server);
1.662     raeburn  2895:     return $status;
                   2896: }
                   2897: 
1.658     raeburn  2898: sub dcmaildump {
                   2899:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2900:     my %returnhash=();
1.846     albertel 2901: 
                   2902:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2903:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2904:                                                          &escape($enddate).':';
                   2905: 	my @esc_senders=map { &escape($_)} @$senders;
                   2906: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2907: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2908:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2909:             if (($key) && ($value)) {
                   2910:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2911:             }
                   2912:         }
                   2913:     }
                   2914:     return %returnhash;
                   2915: }
1.662     raeburn  2916: # ---------------------------------------------------------- Domain roles
                   2917: 
                   2918: sub get_domain_roles {
                   2919:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2920:     if (undef($startdate) || $startdate eq '') {
                   2921:         $startdate = '.';
                   2922:     }
                   2923:     if (undef($enddate) || $enddate eq '') {
                   2924:         $enddate = '.';
                   2925:     }
1.922     raeburn  2926:     my $rolelist;
                   2927:     if (ref($roles) eq 'ARRAY') {
                   2928:         $rolelist = join(':',@{$roles});
                   2929:     }
1.662     raeburn  2930:     my %personnel = ();
1.841     albertel 2931: 
                   2932:     my %servers = &get_servers($dom,'library');
                   2933:     foreach my $tryserver (keys(%servers)) {
                   2934: 	%{$personnel{$tryserver}}=();
                   2935: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2936: 					    &escape($startdate).':'.
                   2937: 					    &escape($enddate).':'.
                   2938: 					    &escape($rolelist), $tryserver))) {
                   2939: 	    my ($key,$value) = split(/\=/,$line,2);
                   2940: 	    if (($key) && ($value)) {
                   2941: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2942: 	    }
                   2943: 	}
1.662     raeburn  2944:     }
                   2945:     return %personnel;
                   2946: }
1.658     raeburn  2947: 
1.149     www      2948: # ----------------------------------------------------------- Check out an item
                   2949: 
1.504     albertel 2950: sub get_first_access {
                   2951:     my ($type,$argsymb)=@_;
1.790     albertel 2952:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2953:     if ($argsymb) { $symb=$argsymb; }
                   2954:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2955:     if ($type eq 'course') {
                   2956: 	$res='course';
                   2957:     } elsif ($type eq 'map') {
1.588     albertel 2958: 	$res=&symbread($map);
                   2959:     } else {
                   2960: 	$res=$symb;
                   2961:     }
                   2962:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2963:     return $times{"$courseid\0$res"};
1.504     albertel 2964: }
                   2965: 
                   2966: sub set_first_access {
                   2967:     my ($type)=@_;
1.790     albertel 2968:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2969:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2970:     if ($type eq 'course') {
                   2971: 	$res='course';
                   2972:     } elsif ($type eq 'map') {
1.588     albertel 2973: 	$res=&symbread($map);
                   2974:     } else {
                   2975: 	$res=$symb;
                   2976:     }
                   2977:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2978:     if (!$firstaccess) {
1.588     albertel 2979: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2980:     }
                   2981:     return 'already_set';
1.504     albertel 2982: }
                   2983: 
1.149     www      2984: sub checkout {
                   2985:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2986:     my $now=time;
                   2987:     my $lonhost=$perlvar{'lonHostID'};
                   2988:     my $infostr=&escape(
1.234     www      2989:                  'CHECKOUTTOKEN&'.
1.149     www      2990:                  $tuname.'&'.
                   2991:                  $tudom.'&'.
                   2992:                  $tcrsid.'&'.
                   2993:                  $symb.'&'.
                   2994: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2995:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2996:     if ($token=~/^error\:/) { 
1.672     albertel 2997:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2998:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2999:                  "</font>");
                   3000:         return ''; 
                   3001:     }
                   3002: 
1.149     www      3003:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3004:     $token=~tr/a-z/A-Z/;
                   3005: 
1.153     www      3006:     my %infohash=('resource.0.outtoken' => $token,
                   3007:                   'resource.0.checkouttime' => $now,
                   3008:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3009: 
                   3010:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3011:        return '';
1.151     www      3012:     } else {
1.672     albertel 3013:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3014:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3015:                  "</font>");
1.149     www      3016:     }    
                   3017: 
                   3018:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3019:                          &escape('Checkout '.$infostr.' - '.
                   3020:                                                  $token)) ne 'ok') {
                   3021: 	return '';
1.151     www      3022:     } else {
1.672     albertel 3023:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3024:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3025:                  "</font>");
1.149     www      3026:     }
1.151     www      3027:     return $token;
1.149     www      3028: }
                   3029: 
                   3030: # ------------------------------------------------------------ Check in an item
                   3031: 
                   3032: sub checkin {
                   3033:     my $token=shift;
1.150     www      3034:     my $now=time;
                   3035:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3036:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3037:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3038:     $dtoken=~s/\W/\_/g;
1.234     www      3039:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3040:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3041: 
1.154     www      3042:     unless (($tuname) && ($tudom)) {
                   3043:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3044:         return '';
                   3045:     }
                   3046:     
                   3047:     unless (&allowed('mgr',$tcrsid)) {
                   3048:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3049:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3050:         return '';
                   3051:     }
                   3052: 
1.153     www      3053:     my %infohash=('resource.0.intoken' => $token,
                   3054:                   'resource.0.checkintime' => $now,
                   3055:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3056: 
                   3057:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3058:        return '';
                   3059:     }    
                   3060: 
                   3061:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3062:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3063: 	return '';
                   3064:     }
                   3065: 
                   3066:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3067: }
                   3068: 
                   3069: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3070: 
                   3071: sub expirespread {
                   3072:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3073:     my $cid=$env{'request.course.id'}; 
1.110     www      3074:     if ($cid) {
                   3075:        my $now=time;
                   3076:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3077:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3078:                             $env{'course.'.$cid.'.num'}.
1.110     www      3079: 	        	    ':nohist_expirationdates:'.
                   3080:                             &escape($key).'='.$now,
1.620     albertel 3081:                             $env{'course.'.$cid.'.home'})
1.110     www      3082:     }
                   3083:     return 'ok';
1.14      www      3084: }
                   3085: 
1.109     www      3086: # ----------------------------------------------------- Devalidate Spreadsheets
                   3087: 
                   3088: sub devalidate {
1.325     www      3089:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3090:     my $cid=$env{'request.course.id'}; 
1.109     www      3091:     if ($cid) {
1.391     matthew  3092:         # delete the stored spreadsheets for
                   3093:         # - the student level sheet of this user in course's homespace
                   3094:         # - the assessment level sheet for this resource 
                   3095:         #   for this user in user's homespace
1.553     albertel 3096: 	# - current conditional state info
1.325     www      3097: 	my $key=$uname.':'.$udom.':';
1.109     www      3098:         my $status=
1.299     matthew  3099: 	    &del('nohist_calculatedsheets',
1.391     matthew  3100: 		 [$key.'studentcalc:'],
1.620     albertel 3101: 		 $env{'course.'.$cid.'.domain'},
                   3102: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3103: 		.' '.
                   3104: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3105: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3106:         unless ($status eq 'ok ok') {
                   3107:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3108:                     $uname.' at '.$udom.' for '.
1.109     www      3109: 		    $symb.': '.$status);
1.133     albertel 3110:         }
1.553     albertel 3111: 	&delenv('user.state.'.$cid);
1.109     www      3112:     }
                   3113: }
                   3114: 
1.265     albertel 3115: sub get_scalar {
                   3116:     my ($string,$end) = @_;
                   3117:     my $value;
                   3118:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3119: 	$value = $1;
                   3120:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3121: 	$value = $1;
                   3122:     }
                   3123:     return &unescape($value);
                   3124: }
                   3125: 
                   3126: sub array2str {
                   3127:   my (@array) = @_;
                   3128:   my $result=&arrayref2str(\@array);
                   3129:   $result=~s/^__ARRAY_REF__//;
                   3130:   $result=~s/__END_ARRAY_REF__$//;
                   3131:   return $result;
                   3132: }
                   3133: 
1.204     albertel 3134: sub arrayref2str {
                   3135:   my ($arrayref) = @_;
1.265     albertel 3136:   my $result='__ARRAY_REF__';
1.204     albertel 3137:   foreach my $elem (@$arrayref) {
1.265     albertel 3138:     if(ref($elem) eq 'ARRAY') {
                   3139:       $result.=&arrayref2str($elem).'&';
                   3140:     } elsif(ref($elem) eq 'HASH') {
                   3141:       $result.=&hashref2str($elem).'&';
                   3142:     } elsif(ref($elem)) {
                   3143:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3144:     } else {
                   3145:       $result.=&escape($elem).'&';
                   3146:     }
                   3147:   }
                   3148:   $result=~s/\&$//;
1.265     albertel 3149:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3150:   return $result;
                   3151: }
                   3152: 
1.168     albertel 3153: sub hash2str {
1.204     albertel 3154:   my (%hash) = @_;
                   3155:   my $result=&hashref2str(\%hash);
1.265     albertel 3156:   $result=~s/^__HASH_REF__//;
                   3157:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3158:   return $result;
                   3159: }
                   3160: 
                   3161: sub hashref2str {
                   3162:   my ($hashref)=@_;
1.265     albertel 3163:   my $result='__HASH_REF__';
1.800     albertel 3164:   foreach my $key (sort(keys(%$hashref))) {
                   3165:     if (ref($key) eq 'ARRAY') {
                   3166:       $result.=&arrayref2str($key).'=';
                   3167:     } elsif (ref($key) eq 'HASH') {
                   3168:       $result.=&hashref2str($key).'=';
                   3169:     } elsif (ref($key)) {
1.265     albertel 3170:       $result.='=';
1.800     albertel 3171:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3172:     } else {
1.800     albertel 3173: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3174:     }
                   3175: 
1.800     albertel 3176:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3177:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3178:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3179:       $result.=&hashref2str($hashref->{$key}).'&';
                   3180:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3181:        $result.='&';
1.800     albertel 3182:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3183:     } else {
1.800     albertel 3184:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3185:     }
                   3186:   }
1.168     albertel 3187:   $result=~s/\&$//;
1.265     albertel 3188:   $result .= '__END_HASH_REF__';
1.168     albertel 3189:   return $result;
                   3190: }
                   3191: 
                   3192: sub str2hash {
1.265     albertel 3193:     my ($string)=@_;
                   3194:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3195:     return %$hash;
                   3196: }
                   3197: 
                   3198: sub str2hashref {
1.168     albertel 3199:   my ($string) = @_;
1.265     albertel 3200: 
                   3201:   my %hash;
                   3202: 
                   3203:   if($string !~ /^__HASH_REF__/) {
                   3204:       if (! ($string eq '' || !defined($string))) {
                   3205: 	  $hash{'error'}='Not hash reference';
                   3206:       }
                   3207:       return (\%hash, $string);
                   3208:   }
                   3209: 
                   3210:   $string =~ s/^__HASH_REF__//;
                   3211: 
                   3212:   while($string !~ /^__END_HASH_REF__/) {
                   3213:       #key
                   3214:       my $key='';
                   3215:       if($string =~ /^__HASH_REF__/) {
                   3216:           ($key, $string)=&str2hashref($string);
                   3217:           if(defined($key->{'error'})) {
                   3218:               $hash{'error'}='Bad data';
                   3219:               return (\%hash, $string);
                   3220:           }
                   3221:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3222:           ($key, $string)=&str2arrayref($string);
                   3223:           if($key->[0] eq 'Array reference error') {
                   3224:               $hash{'error'}='Bad data';
                   3225:               return (\%hash, $string);
                   3226:           }
                   3227:       } else {
                   3228:           $string =~ s/^(.*?)=//;
1.267     albertel 3229: 	  $key=&unescape($1);
1.265     albertel 3230:       }
                   3231:       $string =~ s/^=//;
                   3232: 
                   3233:       #value
                   3234:       my $value='';
                   3235:       if($string =~ /^__HASH_REF__/) {
                   3236:           ($value, $string)=&str2hashref($string);
                   3237:           if(defined($value->{'error'})) {
                   3238:               $hash{'error'}='Bad data';
                   3239:               return (\%hash, $string);
                   3240:           }
                   3241:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3242:           ($value, $string)=&str2arrayref($string);
                   3243:           if($value->[0] eq 'Array reference error') {
                   3244:               $hash{'error'}='Bad data';
                   3245:               return (\%hash, $string);
                   3246:           }
                   3247:       } else {
                   3248: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3249:       }
                   3250:       $string =~ s/^&//;
                   3251: 
                   3252:       $hash{$key}=$value;
1.204     albertel 3253:   }
1.265     albertel 3254: 
                   3255:   $string =~ s/^__END_HASH_REF__//;
                   3256: 
                   3257:   return (\%hash, $string);
1.204     albertel 3258: }
                   3259: 
                   3260: sub str2array {
1.265     albertel 3261:     my ($string)=@_;
                   3262:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3263:     return @$array;
                   3264: }
                   3265: 
                   3266: sub str2arrayref {
1.204     albertel 3267:   my ($string) = @_;
1.265     albertel 3268:   my @array;
                   3269: 
                   3270:   if($string !~ /^__ARRAY_REF__/) {
                   3271:       if (! ($string eq '' || !defined($string))) {
                   3272: 	  $array[0]='Array reference error';
                   3273:       }
                   3274:       return (\@array, $string);
                   3275:   }
                   3276: 
                   3277:   $string =~ s/^__ARRAY_REF__//;
                   3278: 
                   3279:   while($string !~ /^__END_ARRAY_REF__/) {
                   3280:       my $value='';
                   3281:       if($string =~ /^__HASH_REF__/) {
                   3282:           ($value, $string)=&str2hashref($string);
                   3283:           if(defined($value->{'error'})) {
                   3284:               $array[0] ='Array reference error';
                   3285:               return (\@array, $string);
                   3286:           }
                   3287:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3288:           ($value, $string)=&str2arrayref($string);
                   3289:           if($value->[0] eq 'Array reference error') {
                   3290:               $array[0] ='Array reference error';
                   3291:               return (\@array, $string);
                   3292:           }
                   3293:       } else {
                   3294: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3295:       }
                   3296:       $string =~ s/^&//;
                   3297: 
                   3298:       push(@array, $value);
1.191     harris41 3299:   }
1.265     albertel 3300: 
                   3301:   $string =~ s/^__END_ARRAY_REF__//;
                   3302: 
                   3303:   return (\@array, $string);
1.168     albertel 3304: }
                   3305: 
1.167     albertel 3306: # -------------------------------------------------------------------Temp Store
                   3307: 
1.168     albertel 3308: sub tmpreset {
                   3309:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3310:   if (!$symb) {
                   3311:     $symb=&symbread();
1.620     albertel 3312:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3313:   }
                   3314:   $symb=escape($symb);
                   3315: 
1.620     albertel 3316:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3317:   $namespace=~s/\//\_/g;
                   3318:   $namespace=~s/\W//g;
                   3319: 
1.620     albertel 3320:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3321:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3322:   if ($domain eq 'public' && $stuname eq 'public') {
                   3323:       $stuname=$ENV{'REMOTE_ADDR'};
                   3324:   }
1.168     albertel 3325:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3326:   my %hash;
                   3327:   if (tie(%hash,'GDBM_File',
                   3328: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3329: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3330:     foreach my $key (keys %hash) {
1.180     albertel 3331:       if ($key=~ /:$symb/) {
1.168     albertel 3332: 	delete($hash{$key});
                   3333:       }
                   3334:     }
                   3335:   }
                   3336: }
                   3337: 
1.167     albertel 3338: sub tmpstore {
1.168     albertel 3339:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3340: 
                   3341:   if (!$symb) {
                   3342:     $symb=&symbread();
1.620     albertel 3343:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3344:   }
                   3345:   $symb=escape($symb);
                   3346: 
                   3347:   if (!$namespace) {
                   3348:     # I don't think we would ever want to store this for a course.
                   3349:     # it seems this will only be used if we don't have a course.
1.620     albertel 3350:     #$namespace=$env{'request.course.id'};
1.168     albertel 3351:     #if (!$namespace) {
1.620     albertel 3352:       $namespace=$env{'request.state'};
1.168     albertel 3353:     #}
                   3354:   }
                   3355:   $namespace=~s/\//\_/g;
                   3356:   $namespace=~s/\W//g;
1.620     albertel 3357:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3358:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3359:   if ($domain eq 'public' && $stuname eq 'public') {
                   3360:       $stuname=$ENV{'REMOTE_ADDR'};
                   3361:   }
1.168     albertel 3362:   my $now=time;
                   3363:   my %hash;
                   3364:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3365:   if (tie(%hash,'GDBM_File',
                   3366: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3367: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3368:     $hash{"version:$symb"}++;
                   3369:     my $version=$hash{"version:$symb"};
                   3370:     my $allkeys=''; 
                   3371:     foreach my $key (keys(%$storehash)) {
                   3372:       $allkeys.=$key.':';
1.591     albertel 3373:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3374:     }
                   3375:     $hash{"$version:$symb:timestamp"}=$now;
                   3376:     $allkeys.='timestamp';
                   3377:     $hash{"$version:keys:$symb"}=$allkeys;
                   3378:     if (untie(%hash)) {
                   3379:       return 'ok';
                   3380:     } else {
                   3381:       return "error:$!";
                   3382:     }
                   3383:   } else {
                   3384:     return "error:$!";
                   3385:   }
                   3386: }
1.167     albertel 3387: 
1.168     albertel 3388: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3389: 
1.168     albertel 3390: sub tmprestore {
                   3391:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3392: 
1.168     albertel 3393:   if (!$symb) {
                   3394:     $symb=&symbread();
1.620     albertel 3395:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3396:   }
                   3397:   $symb=escape($symb);
                   3398: 
1.620     albertel 3399:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3400: 
1.620     albertel 3401:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3402:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3403:   if ($domain eq 'public' && $stuname eq 'public') {
                   3404:       $stuname=$ENV{'REMOTE_ADDR'};
                   3405:   }
1.168     albertel 3406:   my %returnhash;
                   3407:   $namespace=~s/\//\_/g;
                   3408:   $namespace=~s/\W//g;
                   3409:   my %hash;
                   3410:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3411:   if (tie(%hash,'GDBM_File',
                   3412: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3413: 	  &GDBM_READER(),0640)) {
1.168     albertel 3414:     my $version=$hash{"version:$symb"};
                   3415:     $returnhash{'version'}=$version;
                   3416:     my $scope;
                   3417:     for ($scope=1;$scope<=$version;$scope++) {
                   3418:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3419:       my @keys=split(/:/,$vkeys);
                   3420:       my $key;
                   3421:       $returnhash{"$scope:keys"}=$vkeys;
                   3422:       foreach $key (@keys) {
1.591     albertel 3423: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3424: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3425:       }
                   3426:     }
1.168     albertel 3427:     if (!(untie(%hash))) {
                   3428:       return "error:$!";
                   3429:     }
                   3430:   } else {
                   3431:     return "error:$!";
                   3432:   }
                   3433:   return %returnhash;
1.167     albertel 3434: }
                   3435: 
1.9       www      3436: # ----------------------------------------------------------------------- Store
                   3437: 
                   3438: sub store {
1.124     www      3439:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3440:     my $home='';
                   3441: 
1.168     albertel 3442:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3443: 
1.213     www      3444:     $symb=&symbclean($symb);
1.122     albertel 3445:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3446: 
1.620     albertel 3447:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3448:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3449: 
                   3450:     &devalidate($symb,$stuname,$domain);
1.109     www      3451: 
                   3452:     $symb=escape($symb);
1.187     www      3453:     if (!$namespace) { 
1.620     albertel 3454:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3455:           return ''; 
                   3456:        } 
                   3457:     }
1.620     albertel 3458:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3459: 
                   3460:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3461:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3462: 
1.12      www      3463:     my $namevalue='';
1.800     albertel 3464:     foreach my $key (keys(%$storehash)) {
                   3465:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3466:     }
1.12      www      3467:     $namevalue=~s/\&$//;
1.187     www      3468:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3469:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3470: }
                   3471: 
1.47      www      3472: # -------------------------------------------------------------- Critical Store
                   3473: 
                   3474: sub cstore {
1.124     www      3475:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3476:     my $home='';
                   3477: 
1.168     albertel 3478:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3479: 
1.213     www      3480:     $symb=&symbclean($symb);
1.122     albertel 3481:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3482: 
1.620     albertel 3483:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3484:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3485: 
                   3486:     &devalidate($symb,$stuname,$domain);
1.109     www      3487: 
                   3488:     $symb=escape($symb);
1.187     www      3489:     if (!$namespace) { 
1.620     albertel 3490:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3491:           return ''; 
                   3492:        } 
                   3493:     }
1.620     albertel 3494:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3495: 
                   3496:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3497:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3498: 
1.47      www      3499:     my $namevalue='';
1.800     albertel 3500:     foreach my $key (keys(%$storehash)) {
                   3501:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3502:     }
1.47      www      3503:     $namevalue=~s/\&$//;
1.187     www      3504:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3505:     return critical
                   3506:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3507: }
                   3508: 
1.9       www      3509: # --------------------------------------------------------------------- Restore
                   3510: 
                   3511: sub restore {
1.124     www      3512:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3513:     my $home='';
                   3514: 
1.168     albertel 3515:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3516: 
1.122     albertel 3517:     if (!$symb) {
                   3518:       unless ($symb=escape(&symbread())) { return ''; }
                   3519:     } else {
1.213     www      3520:       $symb=&escape(&symbclean($symb));
1.122     albertel 3521:     }
1.188     www      3522:     if (!$namespace) { 
1.620     albertel 3523:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3524:           return ''; 
                   3525:        } 
                   3526:     }
1.620     albertel 3527:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3528:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3529:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3530:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3531: 
1.12      www      3532:     my %returnhash=();
1.800     albertel 3533:     foreach my $line (split(/\&/,$answer)) {
                   3534: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3535:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3536:     }
1.75      www      3537:     my $version;
                   3538:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3539:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3540:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3541:        }
1.75      www      3542:     }
1.13      www      3543:     return %returnhash;
1.34      www      3544: }
                   3545: 
                   3546: # ---------------------------------------------------------- Course Description
                   3547: 
                   3548: sub coursedescription {
1.731     albertel 3549:     my ($courseid,$args)=@_;
1.34      www      3550:     $courseid=~s/^\///;
1.49      www      3551:     $courseid=~s/\_/\//g;
1.34      www      3552:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3553:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3554:     my $normalid=$cdomain.'_'.$cnum;
                   3555:     # need to always cache even if we get errors otherwise we keep 
                   3556:     # trying and trying and trying to get the course description.
                   3557:     my %envhash=();
                   3558:     my %returnhash=();
1.731     albertel 3559:     
                   3560:     my $expiretime=600;
                   3561:     if ($env{'request.course.id'} eq $normalid) {
                   3562: 	$expiretime=120;
                   3563:     }
                   3564: 
                   3565:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3566:     if (!$args->{'freshen_cache'}
                   3567: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3568: 	foreach my $key (keys(%env)) {
                   3569: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3570: 	    my ($setting) = $1;
                   3571: 	    $returnhash{$setting} = $env{$key};
                   3572: 	}
                   3573: 	return %returnhash;
                   3574:     }
                   3575: 
                   3576:     # get the data agin
                   3577:     if (!$args->{'one_time'}) {
                   3578: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3579:     }
1.811     albertel 3580: 
1.34      www      3581:     if ($chome ne 'no_host') {
1.302     albertel 3582:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3583:        if (!exists($returnhash{'con_lost'})) {
                   3584:            $returnhash{'home'}= $chome;
                   3585: 	   $returnhash{'domain'} = $cdomain;
                   3586: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3587:            if (!defined($returnhash{'type'})) {
                   3588:                $returnhash{'type'} = 'Course';
                   3589:            }
1.130     albertel 3590:            while (my ($name,$value) = each %returnhash) {
1.53      www      3591:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3592:            }
1.270     www      3593:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3594:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3595: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3596:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3597:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3598:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3599:        }
                   3600:     }
1.731     albertel 3601:     if (!$args->{'one_time'}) {
1.949     raeburn  3602: 	&appenv(\%envhash);
1.731     albertel 3603:     }
1.302     albertel 3604:     return %returnhash;
1.461     www      3605: }
                   3606: 
                   3607: # -------------------------------------------------See if a user is privileged
                   3608: 
                   3609: sub privileged {
                   3610:     my ($username,$domain)=@_;
                   3611:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3612: 			&homeserver($username,$domain));
                   3613:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3614:     my $now=time;
                   3615:     if ($rolesdump ne '') {
1.800     albertel 3616:         foreach my $entry (split(/&/,$rolesdump)) {
                   3617: 	    if ($entry!~/^rolesdef_/) {
                   3618: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3619: 		$area=~s/\_\w\w$//;
                   3620: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3621: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3622: 		    my $active=1;
                   3623: 		    if ($tend) {
                   3624: 			if ($tend<$now) { $active=0; }
                   3625: 		    }
                   3626: 		    if ($tstart) {
                   3627: 			if ($tstart>$now) { $active=0; }
                   3628: 		    }
                   3629: 		    if ($active) { return 1; }
                   3630: 		}
                   3631: 	    }
                   3632: 	}
                   3633:     }
                   3634:     return 0;
1.9       www      3635: }
1.1       albertel 3636: 
1.103     harris41 3637: # -------------------------------------------------------- Get user privileges
1.11      www      3638: 
                   3639: sub rolesinit {
                   3640:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3641:     my %userroles;
1.11      www      3642:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3643:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3644:     my %allroles=();
1.678     raeburn  3645:     my %allgroups=();   
1.11      www      3646:     my $now=time;
1.966     raeburn  3647:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3648:     my $group_privs;
1.11      www      3649: 
                   3650:     if ($rolesdump ne '') {
1.800     albertel 3651:         foreach my $entry (split(/&/,$rolesdump)) {
                   3652: 	  if ($entry!~/^rolesdef_/) {
                   3653:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3654: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3655:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3656: 	    if ($role=~/^cr/) { 
1.807     albertel 3657: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3658: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3659: 		    ($tend,$tstart)=split('_',$trest);
                   3660: 		} else {
                   3661: 		    $trole=$role;
                   3662: 		}
1.678     raeburn  3663:             } elsif ($role =~ m|^gr/|) {
                   3664:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3665:                 ($trole,$group_privs) = split(/\//,$trole);
                   3666:                 $group_privs = &unescape($group_privs);
1.587     albertel 3667: 	    } else {
                   3668: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3669: 	    }
1.743     albertel 3670: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3671: 					 $username);
                   3672: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3673:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3674:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3675:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3676: 		my $spec=$trole.'.'.$area;
                   3677: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3678: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3679:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3680:                 } elsif ($trole eq 'gr') {
                   3681:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3682: 		} else {
1.567     raeburn  3683:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3684: 		}
1.12      www      3685:             }
1.662     raeburn  3686:           }
1.191     harris41 3687:         }
1.743     albertel 3688:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3689:         $userroles{'user.adv'}    = $adv;
                   3690: 	$userroles{'user.author'} = $author;
1.620     albertel 3691:         $env{'user.adv'}=$adv;
1.11      www      3692:     }
1.743     albertel 3693:     return \%userroles;  
1.11      www      3694: }
                   3695: 
1.567     raeburn  3696: sub set_arearole {
                   3697:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3698: # log the associated role with the area
                   3699:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3700:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3701: }
                   3702: 
                   3703: sub custom_roleprivs {
                   3704:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3705:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3706:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3707:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3708:         my ($rdummy,$roledef)=
                   3709:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3710:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3711:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3712:             if (defined($syspriv)) {
                   3713:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3714:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3715:             }
                   3716:             if ($tdomain ne '') {
                   3717:                 if (defined($dompriv)) {
                   3718:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3719:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3720:                 }
                   3721:                 if (($trest ne '') && (defined($coursepriv))) {
                   3722:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3723:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3724:                 }
                   3725:             }
                   3726:         }
                   3727:     }
                   3728: }
                   3729: 
1.678     raeburn  3730: sub group_roleprivs {
                   3731:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3732:     my $access = 1;
                   3733:     my $now = time;
                   3734:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3735:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3736:     if ($access) {
1.811     albertel 3737:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3738:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3739:     }
                   3740: }
1.567     raeburn  3741: 
                   3742: sub standard_roleprivs {
                   3743:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3744:     if (defined($pr{$trole.':s'})) {
                   3745:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3746:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3747:     }
                   3748:     if ($tdomain ne '') {
                   3749:         if (defined($pr{$trole.':d'})) {
                   3750:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3751:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3752:         }
                   3753:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3754:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3755:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3756:         }
                   3757:     }
                   3758: }
                   3759: 
                   3760: sub set_userprivs {
1.678     raeburn  3761:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3762:     my $author=0;
                   3763:     my $adv=0;
1.678     raeburn  3764:     my %grouproles = ();
                   3765:     if (keys(%{$allgroups}) > 0) {
                   3766:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3767:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3768:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3769:                 $trole = $1;
                   3770:                 $area = $2;
1.681     raeburn  3771:                 $sec = $3;
                   3772:                 $extendedarea = $area.$sec;
                   3773:                 if (exists($$allgroups{$area})) {
                   3774:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3775:                         my $spec = $trole.'.'.$extendedarea;
                   3776:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3777:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3778:                     }
                   3779:                 }
                   3780:             }
                   3781:         }
                   3782:     }
1.800     albertel 3783:     foreach my $group (keys(%grouproles)) {
                   3784:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3785:     }
1.800     albertel 3786:     foreach my $role (keys(%{$allroles})) {
                   3787:         my %thesepriv;
1.941     raeburn  3788:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3789:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3790:             if ($item ne '') {
                   3791:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3792:                 if ($restrictions eq '') {
                   3793:                     $thesepriv{$privilege}='F';
                   3794:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3795:                     $thesepriv{$privilege}.=$restrictions;
                   3796:                 }
                   3797:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3798:             }
                   3799:         }
                   3800:         my $thesestr='';
1.800     albertel 3801:         foreach my $priv (keys(%thesepriv)) {
                   3802: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3803: 	}
                   3804:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3805:     }
                   3806:     return ($author,$adv);
                   3807: }
                   3808: 
1.12      www      3809: # --------------------------------------------------------------- get interface
                   3810: 
                   3811: sub get {
1.131     albertel 3812:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3813:    my $items='';
1.800     albertel 3814:    foreach my $item (@$storearr) {
                   3815:        $items.=&escape($item).'&';
1.191     harris41 3816:    }
1.12      www      3817:    $items=~s/\&$//;
1.620     albertel 3818:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3819:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3820:    my $uhome=&homeserver($uname,$udomain);
                   3821: 
1.133     albertel 3822:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3823:    my @pairs=split(/\&/,$rep);
1.273     albertel 3824:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3825:      return @pairs;
                   3826:    }
1.15      www      3827:    my %returnhash=();
1.42      www      3828:    my $i=0;
1.800     albertel 3829:    foreach my $item (@$storearr) {
                   3830:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3831:       $i++;
1.191     harris41 3832:    }
1.15      www      3833:    return %returnhash;
1.27      www      3834: }
                   3835: 
                   3836: # --------------------------------------------------------------- del interface
                   3837: 
                   3838: sub del {
1.133     albertel 3839:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3840:    my $items='';
1.800     albertel 3841:    foreach my $item (@$storearr) {
                   3842:        $items.=&escape($item).'&';
1.191     harris41 3843:    }
1.27      www      3844:    $items=~s/\&$//;
1.620     albertel 3845:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3846:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3847:    my $uhome=&homeserver($uname,$udomain);
                   3848: 
                   3849:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3850: }
                   3851: 
                   3852: # -------------------------------------------------------------- dump interface
                   3853: 
                   3854: sub dump {
1.755     albertel 3855:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3856:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3857:     if (!$uname) { $uname=$env{'user.name'}; }
                   3858:     my $uhome=&homeserver($uname,$udomain);
                   3859:     if ($regexp) {
                   3860: 	$regexp=&escape($regexp);
                   3861:     } else {
                   3862: 	$regexp='.';
                   3863:     }
                   3864:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3865:     my @pairs=split(/\&/,$rep);
                   3866:     my %returnhash=();
                   3867:     foreach my $item (@pairs) {
                   3868: 	my ($key,$value)=split(/=/,$item,2);
                   3869: 	$key = &unescape($key);
                   3870: 	next if ($key =~ /^error: 2 /);
                   3871: 	$returnhash{$key}=&thaw_unescape($value);
                   3872:     }
                   3873:     return %returnhash;
1.407     www      3874: }
                   3875: 
1.717     albertel 3876: # --------------------------------------------------------- dumpstore interface
                   3877: 
                   3878: sub dumpstore {
                   3879:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3880:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3881:    if (!$uname) { $uname=$env{'user.name'}; }
                   3882:    my $uhome=&homeserver($uname,$udomain);
                   3883:    if ($regexp) {
                   3884:        $regexp=&escape($regexp);
                   3885:    } else {
                   3886:        $regexp='.';
                   3887:    }
                   3888:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3889:    my @pairs=split(/\&/,$rep);
                   3890:    my %returnhash=();
                   3891:    foreach my $item (@pairs) {
                   3892:        my ($key,$value)=split(/=/,$item,2);
                   3893:        next if ($key =~ /^error: 2 /);
                   3894:        $returnhash{$key}=&thaw_unescape($value);
                   3895:    }
                   3896:    return %returnhash;
1.717     albertel 3897: }
                   3898: 
1.407     www      3899: # -------------------------------------------------------------- keys interface
                   3900: 
                   3901: sub getkeys {
                   3902:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3903:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3904:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3905:    my $uhome=&homeserver($uname,$udomain);
                   3906:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3907:    my @keyarray=();
1.800     albertel 3908:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3909:       next if ($key =~ /^error: 2 /);
1.800     albertel 3910:       push(@keyarray,&unescape($key));
1.407     www      3911:    }
                   3912:    return @keyarray;
1.318     matthew  3913: }
                   3914: 
1.319     matthew  3915: # --------------------------------------------------------------- currentdump
                   3916: sub currentdump {
1.328     matthew  3917:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3918:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3919:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3920:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3921:    my $uhome = &homeserver($sname,$sdom);
                   3922:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3923:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3924:    #
1.318     matthew  3925:    my %returnhash=();
1.319     matthew  3926:    #
                   3927:    if ($rep eq "unknown_cmd") { 
                   3928:        # an old lond will not know currentdump
                   3929:        # Do a dump and make it look like a currentdump
1.822     albertel 3930:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3931:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3932:        my %hash = @tmp;
                   3933:        @tmp=();
1.424     matthew  3934:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3935:    } else {
                   3936:        my @pairs=split(/\&/,$rep);
1.800     albertel 3937:        foreach my $pair (@pairs) {
                   3938:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3939:            my ($symb,$param) = split(/:/,$key);
                   3940:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3941:                                                         &thaw_unescape($value);
1.319     matthew  3942:        }
1.191     harris41 3943:    }
1.12      www      3944:    return %returnhash;
1.424     matthew  3945: }
                   3946: 
                   3947: sub convert_dump_to_currentdump{
                   3948:     my %hash = %{shift()};
                   3949:     my %returnhash;
                   3950:     # Code ripped from lond, essentially.  The only difference
                   3951:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3952:     # we might run in to problems with parameter names =~ /^v\./
                   3953:     while (my ($key,$value) = each(%hash)) {
                   3954:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3955: 	$symb  = &unescape($symb);
                   3956: 	$param = &unescape($param);
1.424     matthew  3957:         next if ($v eq 'version' || $symb eq 'keys');
                   3958:         next if (exists($returnhash{$symb}) &&
                   3959:                  exists($returnhash{$symb}->{$param}) &&
                   3960:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3961:         $returnhash{$symb}->{$param}=$value;
                   3962:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3963:     }
                   3964:     #
                   3965:     # Remove all of the keys in the hashes which keep track of
                   3966:     # the version of the parameter.
                   3967:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3968:         # use a foreach because we are going to delete from the hash.
                   3969:         foreach my $key (keys(%$param_hash)) {
                   3970:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3971:         }
                   3972:     }
                   3973:     return \%returnhash;
1.12      www      3974: }
                   3975: 
1.627     albertel 3976: # ------------------------------------------------------ critical inc interface
                   3977: 
                   3978: sub cinc {
                   3979:     return &inc(@_,'critical');
                   3980: }
                   3981: 
1.449     matthew  3982: # --------------------------------------------------------------- inc interface
                   3983: 
                   3984: sub inc {
1.627     albertel 3985:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3986:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3987:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3988:     my $uhome=&homeserver($uname,$udomain);
                   3989:     my $items='';
                   3990:     if (! ref($store)) {
                   3991:         # got a single value, so use that instead
                   3992:         $items = &escape($store).'=&';
                   3993:     } elsif (ref($store) eq 'SCALAR') {
                   3994:         $items = &escape($$store).'=&';        
                   3995:     } elsif (ref($store) eq 'ARRAY') {
                   3996:         $items = join('=&',map {&escape($_);} @{$store});
                   3997:     } elsif (ref($store) eq 'HASH') {
                   3998:         while (my($key,$value) = each(%{$store})) {
                   3999:             $items.= &escape($key).'='.&escape($value).'&';
                   4000:         }
                   4001:     }
                   4002:     $items=~s/\&$//;
1.627     albertel 4003:     if ($critical) {
                   4004: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4005:     } else {
                   4006: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4007:     }
1.449     matthew  4008: }
                   4009: 
1.12      www      4010: # --------------------------------------------------------------- put interface
                   4011: 
                   4012: sub put {
1.134     albertel 4013:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4014:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4015:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4016:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4017:    my $items='';
1.800     albertel 4018:    foreach my $item (keys(%$storehash)) {
                   4019:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4020:    }
1.12      www      4021:    $items=~s/\&$//;
1.134     albertel 4022:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4023: }
                   4024: 
1.631     albertel 4025: # ------------------------------------------------------------ newput interface
                   4026: 
                   4027: sub newput {
                   4028:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4029:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4030:    if (!$uname) { $uname=$env{'user.name'}; }
                   4031:    my $uhome=&homeserver($uname,$udomain);
                   4032:    my $items='';
                   4033:    foreach my $key (keys(%$storehash)) {
                   4034:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4035:    }
                   4036:    $items=~s/\&$//;
                   4037:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4038: }
                   4039: 
                   4040: # ---------------------------------------------------------  putstore interface
                   4041: 
1.524     raeburn  4042: sub putstore {
1.715     albertel 4043:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4044:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4045:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4046:    my $uhome=&homeserver($uname,$udomain);
                   4047:    my $items='';
1.715     albertel 4048:    foreach my $key (keys(%$storehash)) {
                   4049:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4050:    }
1.715     albertel 4051:    $items=~s/\&$//;
1.716     albertel 4052:    my $esc_symb=&escape($symb);
                   4053:    my $esc_v=&escape($version);
1.715     albertel 4054:    my $reply =
1.716     albertel 4055:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4056: 	      $uhome);
                   4057:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4058:        # gfall back to way things use to be done
1.715     albertel 4059:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4060: 			    $uname);
1.524     raeburn  4061:    }
1.715     albertel 4062:    return $reply;
                   4063: }
                   4064: 
                   4065: sub old_putstore {
1.716     albertel 4066:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4067:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4068:     if (!$uname) { $uname=$env{'user.name'}; }
                   4069:     my $uhome=&homeserver($uname,$udomain);
                   4070:     my %newstorehash;
1.800     albertel 4071:     foreach my $item (keys(%$storehash)) {
                   4072: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4073: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4074:     }
                   4075:     my $items='';
                   4076:     my %allitems = ();
1.800     albertel 4077:     foreach my $item (keys(%newstorehash)) {
                   4078: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4079: 	    my $key = $1.':keys:'.$2;
                   4080: 	    $allitems{$key} .= $3.':';
                   4081: 	}
1.800     albertel 4082: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4083:     }
1.800     albertel 4084:     foreach my $item (keys(%allitems)) {
                   4085: 	$allitems{$item} =~ s/\:$//;
                   4086: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4087:     }
                   4088:     $items=~s/\&$//;
                   4089:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4090: }
                   4091: 
1.47      www      4092: # ------------------------------------------------------ critical put interface
                   4093: 
                   4094: sub cput {
1.134     albertel 4095:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4097:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4098:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4099:    my $items='';
1.800     albertel 4100:    foreach my $item (keys(%$storehash)) {
                   4101:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4102:    }
1.47      www      4103:    $items=~s/\&$//;
1.134     albertel 4104:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4105: }
                   4106: 
                   4107: # -------------------------------------------------------------- eget interface
                   4108: 
                   4109: sub eget {
1.133     albertel 4110:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4111:    my $items='';
1.800     albertel 4112:    foreach my $item (@$storearr) {
                   4113:        $items.=&escape($item).'&';
1.191     harris41 4114:    }
1.12      www      4115:    $items=~s/\&$//;
1.620     albertel 4116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4117:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4118:    my $uhome=&homeserver($uname,$udomain);
                   4119:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4120:    my @pairs=split(/\&/,$rep);
                   4121:    my %returnhash=();
1.42      www      4122:    my $i=0;
1.800     albertel 4123:    foreach my $item (@$storearr) {
                   4124:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4125:       $i++;
1.191     harris41 4126:    }
1.12      www      4127:    return %returnhash;
                   4128: }
                   4129: 
1.667     albertel 4130: # ------------------------------------------------------------ tmpput interface
                   4131: sub tmpput {
1.802     raeburn  4132:     my ($storehash,$server,$context)=@_;
1.667     albertel 4133:     my $items='';
1.800     albertel 4134:     foreach my $item (keys(%$storehash)) {
                   4135: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4136:     }
                   4137:     $items=~s/\&$//;
1.802     raeburn  4138:     if (defined($context)) {
                   4139:         $items .= ':'.&escape($context);
                   4140:     }
1.667     albertel 4141:     return &reply("tmpput:$items",$server);
                   4142: }
                   4143: 
                   4144: # ------------------------------------------------------------ tmpget interface
                   4145: sub tmpget {
1.688     albertel 4146:     my ($token,$server)=@_;
                   4147:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4148:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4149:     my %returnhash;
                   4150:     foreach my $item (split(/\&/,$rep)) {
                   4151: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4152:         next if ($key =~ /^error: 2 /);
1.667     albertel 4153: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4154:     }
                   4155:     return %returnhash;
                   4156: }
                   4157: 
1.688     albertel 4158: # ------------------------------------------------------------ tmpget interface
                   4159: sub tmpdel {
                   4160:     my ($token,$server)=@_;
                   4161:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4162:     return &reply("tmpdel:$token",$server);
                   4163: }
                   4164: 
1.765     albertel 4165: # -------------------------------------------------- portfolio access checking
                   4166: 
                   4167: sub portfolio_access {
1.766     albertel 4168:     my ($requrl) = @_;
1.765     albertel 4169:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4170:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4171:     if ($result) {
                   4172:         my %setters;
                   4173:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4174:             my ($startblock,$endblock) =
                   4175:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4176:             if ($startblock && $endblock) {
                   4177:                 return 'B';
                   4178:             }
                   4179:         } else {
                   4180:             my ($startblock,$endblock) =
                   4181:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4182:             if ($startblock && $endblock) {
                   4183:                 return 'B';
                   4184:             }
                   4185:         }
                   4186:     }
1.765     albertel 4187:     if ($result eq 'ok') {
1.766     albertel 4188:        return 'F';
1.765     albertel 4189:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4190:        return 'A';
1.765     albertel 4191:     }
1.766     albertel 4192:     return '';
1.765     albertel 4193: }
                   4194: 
                   4195: sub get_portfolio_access {
1.767     albertel 4196:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4197: 
                   4198:     if (!ref($access_hash)) {
                   4199: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4200: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4201: 						   $file_name);
                   4202: 	$access_hash = $access_controls{$file_name};
                   4203:     }
                   4204: 
1.765     albertel 4205:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4206:     my $now = time;
                   4207:     if (ref($access_hash) eq 'HASH') {
                   4208:         foreach my $key (keys(%{$access_hash})) {
                   4209:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4210:             if ($start > $now) {
                   4211:                 next;
                   4212:             }
                   4213:             if ($end && $end<$now) {
                   4214:                 next;
                   4215:             }
                   4216:             if ($scope eq 'public') {
                   4217:                 $public = $key;
                   4218:                 last;
                   4219:             } elsif ($scope eq 'guest') {
                   4220:                 $guest = $key;
                   4221:             } elsif ($scope eq 'domains') {
                   4222:                 push(@domains,$key);
                   4223:             } elsif ($scope eq 'users') {
                   4224:                 push(@users,$key);
                   4225:             } elsif ($scope eq 'course') {
                   4226:                 push(@courses,$key);
                   4227:             } elsif ($scope eq 'group') {
                   4228:                 push(@groups,$key);
                   4229:             }
                   4230:         }
                   4231:         if ($public) {
                   4232:             return 'ok';
                   4233:         }
                   4234:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4235:             if ($guest) {
                   4236:                 return $guest;
                   4237:             }
                   4238:         } else {
                   4239:             if (@domains > 0) {
                   4240:                 foreach my $domkey (@domains) {
                   4241:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4242:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4243:                             return 'ok';
                   4244:                         }
                   4245:                     }
                   4246:                 }
                   4247:             }
                   4248:             if (@users > 0) {
                   4249:                 foreach my $userkey (@users) {
1.865     raeburn  4250:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4251:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4252:                             if (ref($item) eq 'HASH') {
                   4253:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4254:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4255:                                     return 'ok';
                   4256:                                 }
                   4257:                             }
                   4258:                         }
                   4259:                     } 
1.765     albertel 4260:                 }
                   4261:             }
                   4262:             my %roleshash;
                   4263:             my @courses_and_groups = @courses;
                   4264:             push(@courses_and_groups,@groups); 
                   4265:             if (@courses_and_groups > 0) {
                   4266:                 my (%allgroups,%allroles); 
                   4267:                 my ($start,$end,$role,$sec,$group);
                   4268:                 foreach my $envkey (%env) {
1.811     albertel 4269:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4270:                         my $cid = $2.'_'.$3; 
                   4271:                         if ($1 eq 'gr') {
                   4272:                             $group = $4;
                   4273:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4274:                         } else {
                   4275:                             if ($4 eq '') {
                   4276:                                 $sec = 'none';
                   4277:                             } else {
                   4278:                                 $sec = $4;
                   4279:                             }
                   4280:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4281:                         }
1.811     albertel 4282:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4283:                         my $cid = $2.'_'.$3;
                   4284:                         if ($4 eq '') {
                   4285:                             $sec = 'none';
                   4286:                         } else {
                   4287:                             $sec = $4;
                   4288:                         }
                   4289:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4290:                     }
                   4291:                 }
                   4292:                 if (keys(%allroles) == 0) {
                   4293:                     return;
                   4294:                 }
                   4295:                 foreach my $key (@courses_and_groups) {
                   4296:                     my %content = %{$$access_hash{$key}};
                   4297:                     my $cnum = $content{'number'};
                   4298:                     my $cdom = $content{'domain'};
                   4299:                     my $cid = $cdom.'_'.$cnum;
                   4300:                     if (!exists($allroles{$cid})) {
                   4301:                         next;
                   4302:                     }    
                   4303:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4304:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4305:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4306:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4307:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4308:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4309:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4310:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4311:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4312:                                         if (grep/^all$/,@sections) {
                   4313:                                             return 'ok';
                   4314:                                         } else {
                   4315:                                             if (grep/^$sec$/,@sections) {
                   4316:                                                 return 'ok';
                   4317:                                             }
                   4318:                                         }
                   4319:                                     }
                   4320:                                 }
                   4321:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4322:                                     if (grep/^none$/,@groups) {
                   4323:                                         return 'ok';
                   4324:                                     }
                   4325:                                 } else {
                   4326:                                     if (grep/^all$/,@groups) {
                   4327:                                         return 'ok';
                   4328:                                     } 
                   4329:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4330:                                         if (grep/^$group$/,@groups) {
                   4331:                                             return 'ok';
                   4332:                                         }
                   4333:                                     }
                   4334:                                 } 
                   4335:                             }
                   4336:                         }
                   4337:                     }
                   4338:                 }
                   4339:             }
                   4340:             if ($guest) {
                   4341:                 return $guest;
                   4342:             }
                   4343:         }
                   4344:     }
                   4345:     return;
                   4346: }
                   4347: 
                   4348: sub course_group_datechecker {
                   4349:     my ($dates,$now,$status) = @_;
                   4350:     my ($start,$end) = split(/\./,$dates);
                   4351:     if (!$start && !$end) {
                   4352:         return 'ok';
                   4353:     }
                   4354:     if (grep/^active$/,@{$status}) {
                   4355:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4356:             return 'ok';
                   4357:         }
                   4358:     }
                   4359:     if (grep/^previous$/,@{$status}) {
                   4360:         if ($end > $now ) {
                   4361:             return 'ok';
                   4362:         }
                   4363:     }
                   4364:     if (grep/^future$/,@{$status}) {
                   4365:         if ($start > $now) {
                   4366:             return 'ok';
                   4367:         }
                   4368:     }
                   4369:     return; 
                   4370: }
                   4371: 
                   4372: sub parse_portfolio_url {
                   4373:     my ($url) = @_;
                   4374: 
                   4375:     my ($type,$udom,$unum,$group,$file_name);
                   4376:     
1.823     albertel 4377:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4378: 	$type = 1;
                   4379:         $udom = $1;
                   4380:         $unum = $2;
                   4381:         $file_name = $3;
1.823     albertel 4382:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4383: 	$type = 2;
                   4384:         $udom = $1;
                   4385:         $unum = $2;
                   4386:         $group = $3;
                   4387:         $file_name = $3.'/'.$4;
                   4388:     }
                   4389:     if (wantarray) {
                   4390: 	return ($type,$udom,$unum,$file_name,$group);
                   4391:     }
                   4392:     return $type;
                   4393: }
                   4394: 
                   4395: sub is_portfolio_url {
                   4396:     my ($url) = @_;
                   4397:     return scalar(&parse_portfolio_url($url));
                   4398: }
                   4399: 
1.798     raeburn  4400: sub is_portfolio_file {
                   4401:     my ($file) = @_;
1.820     raeburn  4402:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4403:         return 1;
                   4404:     }
                   4405:     return;
                   4406: }
                   4407: 
1.976     raeburn  4408: sub usertools_access {
1.978     raeburn  4409:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4410:     my $access;
                   4411:     my %tools = (
                   4412:                   aboutme   => 1,
                   4413:                   blog      => 1,
                   4414:                   portfolio => 1,
                   4415:                 );
                   4416:     return if (!defined($tools{$tool}));
                   4417: 
                   4418:     if ((!defined($udom)) || (!defined($uname))) {
                   4419:         $udom = $env{'user.domain'};
                   4420:         $uname = $env{'user.name'};
                   4421:     }
                   4422: 
1.978     raeburn  4423:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4424:         if ($action ne 'reload') {
                   4425:             return $env{'environment.availabletools.'.$tool};
                   4426:         } 
1.976     raeburn  4427:     }
                   4428: 
                   4429:     my ($toolstatus,$inststatus);
                   4430: 
                   4431:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4432:         $toolstatus = $env{'environment.tools.'.$tool};
                   4433:         $inststatus = $env{'environment.inststatus'};
                   4434:     } else {
                   4435:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4436:         $toolstatus = $userenv{'tools.'.$tool};
                   4437:         $inststatus = $userenv{'inststatus'};
                   4438:     }
                   4439: 
                   4440:     if ($toolstatus ne '') {
                   4441:         if ($toolstatus) {
                   4442:             $access = 1;
                   4443:         } else {
                   4444:             $access = 0;
                   4445:         }
                   4446:         return $access;
                   4447:     }
                   4448: 
                   4449:     my $is_adv = &is_advanced_user($udom,$uname);
                   4450:     my %domdef = &get_domain_defaults($udom);
                   4451:     if (ref($domdef{$tool}) eq 'HASH') {
                   4452:         if ($is_adv) {
                   4453:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4454:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4455:                     $access = 1;
                   4456:                 } else {
                   4457:                     $access = 0;
                   4458:                 }
                   4459:                 return $access;
                   4460:             }
                   4461:         }
                   4462:         if ($inststatus ne '') {
                   4463:             my ($hasaccess,$hasnoaccess);
                   4464:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4465:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4466:                     if ($domdef{$tool}{$affiliation}) {
                   4467:                         $hasaccess = 1;
                   4468:                     } else {
                   4469:                         $hasnoaccess = 1;
                   4470:                     }
                   4471:                 }
                   4472:             }
                   4473:             if ($hasaccess || $hasnoaccess) {
                   4474:                 if ($hasaccess) {
                   4475:                     $access = 1;
                   4476:                 } elsif ($hasnoaccess) {
                   4477:                     $access = 0; 
                   4478:                 }
                   4479:                 return $access;
                   4480:             }
                   4481:         } else {
                   4482:             if ($domdef{$tool}{'default'} ne '') {
                   4483:                 if ($domdef{$tool}{'default'}) {
                   4484:                     $access = 1;
                   4485:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4486:                     $access = 0;
                   4487:                 }
                   4488:                 return $access;
                   4489:             }
                   4490:         }
                   4491:     } else {
                   4492:         $access = 1;
                   4493:         return $access;
                   4494:     }
                   4495: }
                   4496: 
                   4497: sub is_advanced_user {
                   4498:     my ($udom,$uname) = @_;
                   4499:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4500:     my %allroles;
                   4501:     my $is_adv;
                   4502:     foreach my $role (keys(%roleshash)) {
                   4503:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4504:         my $area = '/'.$tdomain.'/'.$trest;
                   4505:         if ($sec ne '') {
                   4506:             $area .= '/'.$sec;
                   4507:         }
                   4508:         if (($area ne '') && ($trole ne '')) {
                   4509:             my $spec=$trole.'.'.$area;
                   4510:             if ($trole =~ /^cr\//) {
                   4511:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4512:             } elsif ($trole ne 'gr') {
                   4513:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4514:             }
                   4515:         }
                   4516:     }
                   4517:     foreach my $role (keys(%allroles)) {
                   4518:         last if ($is_adv);
                   4519:         foreach my $item (split(/:/,$allroles{$role})) {
                   4520:             if ($item ne '') {
                   4521:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4522:                 if ($privilege eq 'adv') {
                   4523:                     $is_adv = 1;
                   4524:                     last;
                   4525:                 }
                   4526:             }
                   4527:         }
                   4528:     }
                   4529:     return $is_adv;
                   4530: }
1.798     raeburn  4531: 
1.341     www      4532: # ---------------------------------------------- Custom access rule evaluation
                   4533: 
                   4534: sub customaccess {
                   4535:     my ($priv,$uri)=@_;
1.807     albertel 4536:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4537:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4538:     $udom = &LONCAPA::clean_domain($udom);
                   4539:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4540:     my $access=0;
1.800     albertel 4541:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4542: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4543: 	if ($type eq 'user') {
                   4544: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4545: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4546: 		if ($tdom) {
                   4547: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4548: 		}
1.896     albertel 4549: 		if ($tuname) {
                   4550: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4551: 		}
                   4552: 		$access=($effect eq 'allow');
                   4553: 		last;
                   4554: 	    }
                   4555: 	} else {
                   4556: 	    if ($role) {
                   4557: 		if ($role ne $urole) { next; }
                   4558: 	    }
                   4559: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4560: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4561: 		if ($tdom) {
                   4562: 		    if ($tdom ne $udom) { next; }
                   4563: 		}
                   4564: 		if ($tcrs) {
                   4565: 		    if ($tcrs ne $ucrs) { next; }
                   4566: 		}
                   4567: 		if ($tsec) {
                   4568: 		    if ($tsec ne $usec) { next; }
                   4569: 		}
                   4570: 		$access=($effect eq 'allow');
                   4571: 		last;
                   4572: 	    }
                   4573: 	    if ($realm eq '' && $role eq '') {
                   4574: 		$access=($effect eq 'allow');
                   4575: 	    }
1.402     bowersj2 4576: 	}
1.341     www      4577:     }
                   4578:     return $access;
                   4579: }
                   4580: 
1.103     harris41 4581: # ------------------------------------------------- Check for a user privilege
1.12      www      4582: 
                   4583: sub allowed {
1.810     raeburn  4584:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4585:     my $ver_orguri=$uri;
1.439     www      4586:     $uri=&deversion($uri);
1.152     www      4587:     my $orguri=$uri;
1.52      www      4588:     $uri=&declutter($uri);
1.809     raeburn  4589: 
1.810     raeburn  4590:     if ($priv eq 'evb') {
                   4591: # Evade communication block restrictions for specified role in a course
                   4592:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4593:             return $1;
                   4594:         } else {
                   4595:             return;
                   4596:         }
                   4597:     }
                   4598: 
1.620     albertel 4599:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4600: # Free bre access to adm and meta resources
1.775     albertel 4601:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4602: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4603: 	&& ($priv eq 'bre')) {
1.14      www      4604: 	return 'F';
1.159     www      4605:     }
                   4606: 
1.545     banghart 4607: # Free bre access to user's own portfolio contents
1.714     raeburn  4608:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4609:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4610: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4611:         my %setters;
                   4612:         my ($startblock,$endblock) = 
                   4613:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4614:         if ($startblock && $endblock) {
                   4615:             return 'B';
                   4616:         } else {
                   4617:             return 'F';
                   4618:         }
1.545     banghart 4619:     }
                   4620: 
1.762     raeburn  4621: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4622:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4623:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4624:         if (exists($env{'request.course.id'})) {
                   4625:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4626:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4627:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4628:                 my $courseprivid=$env{'request.course.id'};
                   4629:                 $courseprivid=~s/\_/\//;
                   4630:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4631:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4632:                     return $1; 
1.762     raeburn  4633:                 } else {
                   4634:                     if ($env{'request.course.sec'}) {
                   4635:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4636:                     }
                   4637:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4638:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4639:                         return $2;
                   4640:                     }
1.714     raeburn  4641:                 }
                   4642:             }
                   4643:         }
                   4644:     }
                   4645: 
1.159     www      4646: # Free bre to public access
                   4647: 
                   4648:     if ($priv eq 'bre') {
1.238     www      4649:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4650: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4651:            return 'F'; 
                   4652:         }
1.238     www      4653:         if ($copyright eq 'priv') {
                   4654:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4655: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4656: 		return '';
                   4657:             }
                   4658:         }
                   4659:         if ($copyright eq 'domain') {
                   4660:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4661: 	    unless (($env{'user.domain'} eq $1) ||
                   4662:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4663: 		return '';
                   4664:             }
1.262     matthew  4665:         }
1.620     albertel 4666:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4667:             # Library role, so allow browsing of resources in this domain.
                   4668:             return 'F';
1.238     www      4669:         }
1.341     www      4670:         if ($copyright eq 'custom') {
                   4671: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4672:         }
1.14      www      4673:     }
1.264     matthew  4674:     # Domain coordinator is trying to create a course
1.620     albertel 4675:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4676:         # uri is the requested domain in this case.
                   4677:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4678:         # a role of dc for the domain in question.
1.620     albertel 4679:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4680:     }
1.29      www      4681: 
1.52      www      4682:     my $thisallowed='';
                   4683:     my $statecond=0;
                   4684:     my $courseprivid='';
                   4685: 
                   4686: # Course
                   4687: 
1.620     albertel 4688:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4689:        $thisallowed.=$1;
                   4690:     }
1.29      www      4691: 
1.52      www      4692: # Domain
                   4693: 
1.620     albertel 4694:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4695:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4696:        $thisallowed.=$1;
                   4697:     }
1.52      www      4698: 
                   4699: # Course: uri itself is a course
1.66      www      4700:     my $courseuri=$uri;
                   4701:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4702:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4703: 
1.620     albertel 4704:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4705:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4706:        $thisallowed.=$1;
                   4707:     }
1.29      www      4708: 
1.665     albertel 4709: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4710: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4711:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4712: 	$thisallowed='';
1.671     raeburn  4713:         my ($match)=&is_on_map($uri);
                   4714:         if ($match) {
                   4715:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4716:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4717:                 $thisallowed.=$1;
                   4718:             }
                   4719:         } else {
1.705     albertel 4720:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4721:             if ($refuri) {
                   4722:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4723:                     $thisallowed='F';
1.671     raeburn  4724:                 } else {
                   4725:                     $refuri=&declutter($refuri);
                   4726:                     my ($match) = &is_on_map($refuri);
                   4727:                     if ($match) {
                   4728:                         $thisallowed='F';
                   4729:                     }
1.669     raeburn  4730:                 }
1.671     raeburn  4731:             }
                   4732:         }
1.314     www      4733:     }
1.492     albertel 4734: 
1.766     albertel 4735:     if ($priv eq 'bre'
                   4736: 	&& $thisallowed ne 'F' 
                   4737: 	&& $thisallowed ne '2'
                   4738: 	&& &is_portfolio_url($uri)) {
                   4739: 	$thisallowed = &portfolio_access($uri);
                   4740:     }
                   4741:     
1.52      www      4742: # Full access at system, domain or course-wide level? Exit.
1.29      www      4743:     if ($thisallowed=~/F/) {
                   4744: 	return 'F';
                   4745:     }
                   4746: 
1.52      www      4747: # If this is generating or modifying users, exit with special codes
1.29      www      4748: 
1.643     www      4749:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4750: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4751: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4752: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4753: 	    unless ($auname) { return $thisallowed; }
                   4754: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4755: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4756: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4757: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4758: 	}
1.52      www      4759: 	return $thisallowed;
                   4760:     }
                   4761: #
1.103     harris41 4762: # Gathered so far: system, domain and course wide privileges
1.52      www      4763: #
                   4764: # Course: See if uri or referer is an individual resource that is part of 
                   4765: # the course
                   4766: 
1.620     albertel 4767:     if ($env{'request.course.id'}) {
1.232     www      4768: 
1.620     albertel 4769:        $courseprivid=$env{'request.course.id'};
                   4770:        if ($env{'request.course.sec'}) {
                   4771:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4772:        }
                   4773:        $courseprivid=~s/\_/\//;
                   4774:        my $checkreferer=1;
1.232     www      4775:        my ($match,$cond)=&is_on_map($uri);
                   4776:        if ($match) {
                   4777:            $statecond=$cond;
1.620     albertel 4778:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4779:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4780:                $thisallowed.=$1;
                   4781:                $checkreferer=0;
                   4782:            }
1.29      www      4783:        }
1.83      www      4784:        
1.148     www      4785:        if ($checkreferer) {
1.620     albertel 4786: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4787:             unless ($refuri) {
1.800     albertel 4788:                 foreach my $key (keys(%env)) {
                   4789: 		    if ($key=~/^httpref\..*\*/) {
                   4790: 			my $pattern=$key;
1.156     www      4791:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4792:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4793:                         $pattern=~s/\//\\\//g;
1.152     www      4794:                         if ($orguri=~/$pattern/) {
1.800     albertel 4795: 			    $refuri=$env{$key};
1.148     www      4796:                         }
                   4797:                     }
1.191     harris41 4798:                 }
1.148     www      4799:             }
1.232     www      4800: 
1.148     www      4801:          if ($refuri) { 
1.152     www      4802: 	  $refuri=&declutter($refuri);
1.232     www      4803:           my ($match,$cond)=&is_on_map($refuri);
                   4804:             if ($match) {
                   4805:               my $refstatecond=$cond;
1.620     albertel 4806:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4807:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4808:                   $thisallowed.=$1;
1.53      www      4809:                   $uri=$refuri;
                   4810:                   $statecond=$refstatecond;
1.52      www      4811:               }
                   4812:           }
1.148     www      4813:         }
1.29      www      4814:        }
1.52      www      4815:    }
1.29      www      4816: 
1.52      www      4817: #
1.103     harris41 4818: # Gathered now: all privileges that could apply, and condition number
1.52      www      4819: # 
                   4820: #
                   4821: # Full or no access?
                   4822: #
1.29      www      4823: 
1.52      www      4824:     if ($thisallowed=~/F/) {
                   4825: 	return 'F';
                   4826:     }
1.29      www      4827: 
1.52      www      4828:     unless ($thisallowed) {
                   4829:         return '';
                   4830:     }
1.29      www      4831: 
1.52      www      4832: # Restrictions exist, deal with them
                   4833: #
                   4834: #   C:according to course preferences
                   4835: #   R:according to resource settings
                   4836: #   L:unless locked
                   4837: #   X:according to user session state
                   4838: #
                   4839: 
                   4840: # Possibly locked functionality, check all courses
1.54      www      4841: # Locks might take effect only after 10 minutes cache expiration for other
                   4842: # courses, and 2 minutes for current course
1.52      www      4843: 
                   4844:     my $envkey;
                   4845:     if ($thisallowed=~/L/) {
1.620     albertel 4846:         foreach $envkey (keys %env) {
1.54      www      4847:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4848:                my $courseid=$2;
                   4849:                my $roleid=$1.'.'.$2;
1.92      www      4850:                $courseid=~s/^\///;
1.54      www      4851:                my $expiretime=600;
1.620     albertel 4852:                if ($env{'request.role'} eq $roleid) {
1.54      www      4853: 		  $expiretime=120;
                   4854:                }
                   4855: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4856:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4857:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4858: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4859:                }
1.620     albertel 4860:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4861:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4862: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4863:                        &log($env{'user.domain'},$env{'user.name'},
                   4864:                             $env{'user.home'},
1.57      www      4865:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4866:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4867:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4868: 		       return '';
                   4869:                    }
                   4870:                }
1.620     albertel 4871:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4872:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4873: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4874:                        &log($env{'user.domain'},$env{'user.name'},
                   4875:                             $env{'user.home'},
1.57      www      4876:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4877:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4878:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4879: 		       return '';
                   4880:                    }
                   4881:                }
                   4882: 	   }
1.29      www      4883:        }
1.52      www      4884:     }
                   4885:    
                   4886: #
                   4887: # Rest of the restrictions depend on selected course
                   4888: #
                   4889: 
1.620     albertel 4890:     unless ($env{'request.course.id'}) {
1.766     albertel 4891: 	if ($thisallowed eq 'A') {
                   4892: 	    return 'A';
1.814     raeburn  4893:         } elsif ($thisallowed eq 'B') {
                   4894:             return 'B';
1.766     albertel 4895: 	} else {
                   4896: 	    return '1';
                   4897: 	}
1.52      www      4898:     }
1.29      www      4899: 
1.52      www      4900: #
                   4901: # Now user is definitely in a course
                   4902: #
1.53      www      4903: 
                   4904: 
                   4905: # Course preferences
                   4906: 
                   4907:    if ($thisallowed=~/C/) {
1.620     albertel 4908:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4909:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4910:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4911: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4912: 	   if ($priv ne 'pch') { 
                   4913: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4914: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4915: 			$env{'request.course.id'});
                   4916: 	   }
1.237     www      4917:            return '';
                   4918:        }
                   4919: 
1.620     albertel 4920:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4921: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4922: 	   if ($priv ne 'pch') { 
                   4923: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4924: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4925: 			$env{'request.course.id'});
                   4926: 	   }
1.54      www      4927:            return '';
                   4928:        }
1.53      www      4929:    }
                   4930: 
                   4931: # Resource preferences
                   4932: 
                   4933:    if ($thisallowed=~/R/) {
1.620     albertel 4934:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4935:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4936: 	   if ($priv ne 'pch') { 
                   4937: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4938: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4939: 	   }
                   4940: 	   return '';
1.54      www      4941:        }
1.53      www      4942:    }
1.30      www      4943: 
1.246     www      4944: # Restricted by state or randomout?
1.30      www      4945: 
1.52      www      4946:    if ($thisallowed=~/X/) {
1.620     albertel 4947:       if ($env{'acc.randomout'}) {
1.579     albertel 4948: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4949:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4950:             return ''; 
                   4951:          }
1.247     www      4952:       }
                   4953:       if (&condval($statecond)) {
1.52      www      4954: 	 return '2';
                   4955:       } else {
                   4956:          return '';
                   4957:       }
                   4958:    }
1.30      www      4959: 
1.766     albertel 4960:     if ($thisallowed eq 'A') {
                   4961: 	return 'A';
1.814     raeburn  4962:     } elsif ($thisallowed eq 'B') {
                   4963:         return 'B';
1.766     albertel 4964:     }
1.52      www      4965:    return 'F';
1.232     www      4966: }
                   4967: 
1.710     albertel 4968: sub split_uri_for_cond {
                   4969:     my $uri=&deversion(&declutter(shift));
                   4970:     my @uriparts=split(/\//,$uri);
                   4971:     my $filename=pop(@uriparts);
                   4972:     my $pathname=join('/',@uriparts);
                   4973:     return ($pathname,$filename);
                   4974: }
1.232     www      4975: # --------------------------------------------------- Is a resource on the map?
                   4976: 
                   4977: sub is_on_map {
1.710     albertel 4978:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4979:     #Trying to find the conditional for the file
1.620     albertel 4980:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4981: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4982:     if ($match) {
1.289     bowersj2 4983: 	return (1,$1);
                   4984:     } else {
1.434     www      4985: 	return (0,0);
1.289     bowersj2 4986:     }
1.12      www      4987: }
                   4988: 
1.427     www      4989: # --------------------------------------------------------- Get symb from alias
                   4990: 
                   4991: sub get_symb_from_alias {
                   4992:     my $symb=shift;
                   4993:     my ($map,$resid,$url)=&decode_symb($symb);
                   4994: # Already is a symb
                   4995:     if ($url) { return $symb; }
                   4996: # Must be an alias
                   4997:     my $aliassymb='';
                   4998:     my %bighash;
1.620     albertel 4999:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5000:                             &GDBM_READER(),0640)) {
                   5001:         my $rid=$bighash{'mapalias_'.$symb};
                   5002: 	if ($rid) {
                   5003: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5004: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5005: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5006: 	}
                   5007:         untie %bighash;
                   5008:     }
                   5009:     return $aliassymb;
                   5010: }
                   5011: 
1.12      www      5012: # ----------------------------------------------------------------- Define Role
                   5013: 
                   5014: sub definerole {
                   5015:   if (allowed('mcr','/')) {
                   5016:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5017:     foreach my $role (split(':',$sysrole)) {
                   5018: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5019:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5020:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5021: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5022:                return "refused:s:$crole&$cqual"; 
                   5023:             }
                   5024:         }
1.191     harris41 5025:     }
1.800     albertel 5026:     foreach my $role (split(':',$domrole)) {
                   5027: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5028:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5029:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5030: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5031:                return "refused:d:$crole&$cqual"; 
                   5032:             }
                   5033:         }
1.191     harris41 5034:     }
1.800     albertel 5035:     foreach my $role (split(':',$courole)) {
                   5036: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5037:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5038:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5039: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5040:                return "refused:c:$crole&$cqual"; 
                   5041:             }
                   5042:         }
1.191     harris41 5043:     }
1.620     albertel 5044:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5045:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5046: 	        "rolesdef_$rolename=".
                   5047:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5048:     return reply($command,$env{'user.home'});
1.12      www      5049:   } else {
                   5050:     return 'refused';
                   5051:   }
1.105     harris41 5052: }
                   5053: 
                   5054: # ---------------- Make a metadata query against the network of library servers
                   5055: 
                   5056: sub metadata_query {
1.244     matthew  5057:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5058:     my %rhash;
1.845     albertel 5059:     my %libserv = &all_library();
1.244     matthew  5060:     my @server_list = (defined($server_array) ? @$server_array
                   5061:                                               : keys(%libserv) );
                   5062:     for my $server (@server_list) {
1.118     harris41 5063: 	unless ($custom or $customshow) {
                   5064: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5065: 	    $rhash{$server}=$reply;
                   5066: 	}
                   5067: 	else {
                   5068: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5069: 			     &escape($custom).':'.&escape($customshow),
                   5070: 			     $server);
                   5071: 	    $rhash{$server}=$reply;
                   5072: 	}
1.112     harris41 5073:     }
1.118     harris41 5074:     return \%rhash;
1.240     www      5075: }
                   5076: 
                   5077: # ----------------------------------------- Send log queries and wait for reply
                   5078: 
                   5079: sub log_query {
                   5080:     my ($uname,$udom,$query,%filters)=@_;
                   5081:     my $uhome=&homeserver($uname,$udom);
                   5082:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5083:     my $uhost=&hostname($uhome);
1.800     albertel 5084:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5085:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5086:                        $uhome);
1.479     albertel 5087:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5088:     return get_query_reply($queryid);
                   5089: }
                   5090: 
1.818     raeburn  5091: # -------------------------- Update MySQL table for portfolio file
                   5092: 
                   5093: sub update_portfolio_table {
1.821     raeburn  5094:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5095:     if ($group ne '') {
                   5096:         $file_name =~s /^\Q$group\E//;
                   5097:     }
1.818     raeburn  5098:     my $homeserver = &homeserver($uname,$udom);
                   5099:     my $queryid=
1.821     raeburn  5100:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5101:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5102:     my $reply = &get_query_reply($queryid);
                   5103:     return $reply;
                   5104: }
                   5105: 
1.899     raeburn  5106: # -------------------------- Update MySQL allusers table
                   5107: 
                   5108: sub update_allusers_table {
                   5109:     my ($uname,$udom,$names) = @_;
                   5110:     my $homeserver = &homeserver($uname,$udom);
                   5111:     my $queryid=
                   5112:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5113:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5114:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5115:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5116:                'generation='.&escape($names->{'generation'}).'%%'.
                   5117:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5118:                'id='.&escape($names->{'id'}),$homeserver);
                   5119:     my $reply = &get_query_reply($queryid);
                   5120:     return $reply;
                   5121: }
                   5122: 
1.508     raeburn  5123: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5124: 
                   5125: sub fetch_enrollment_query {
1.511     raeburn  5126:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5127:     my $homeserver;
1.547     raeburn  5128:     my $maxtries = 1;
1.508     raeburn  5129:     if ($context eq 'automated') {
                   5130:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5131:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5132:     } else {
                   5133:         $homeserver = &homeserver($cnum,$dom);
                   5134:     }
1.838     albertel 5135:     my $host=&hostname($homeserver);
1.506     raeburn  5136:     my $cmd = '';
1.800     albertel 5137:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5138:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5139:     }
                   5140:     $cmd =~ s/%%$//;
                   5141:     $cmd = &escape($cmd);
                   5142:     my $query = 'fetchenrollment';
1.620     albertel 5143:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5144:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5145:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5146:         return 'error: '.$queryid;
                   5147:     }
1.506     raeburn  5148:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5149:     my $tries = 1;
                   5150:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5151:         $reply = &get_query_reply($queryid);
                   5152:         $tries ++;
                   5153:     }
1.526     raeburn  5154:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5155:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5156:     } else {
1.901     albertel 5157:         my @responses = split(/:/,$reply);
1.515     raeburn  5158:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5159:             foreach my $line (@responses) {
                   5160:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5161:                 $$replyref{$key} = $value;
                   5162:             }
                   5163:         } else {
1.506     raeburn  5164:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5165:             foreach my $line (@responses) {
                   5166:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5167:                 $$replyref{$key} = $value;
                   5168:                 if ($value > 0) {
1.800     albertel 5169:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5170:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5171:                         my $destname = $pathname.'/'.$filename;
                   5172:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5173:                         if ($xml_classlist =~ /^error/) {
                   5174:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5175:                         } else {
1.506     raeburn  5176:                             if ( open(FILE,">$destname") ) {
                   5177:                                 print FILE &unescape($xml_classlist);
                   5178:                                 close(FILE);
1.526     raeburn  5179:                             } else {
                   5180:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5181:                             }
                   5182:                         }
                   5183:                     }
                   5184:                 }
                   5185:             }
                   5186:         }
                   5187:         return 'ok';
                   5188:     }
                   5189:     return 'error';
                   5190: }
                   5191: 
1.242     www      5192: sub get_query_reply {
                   5193:     my $queryid=shift;
1.240     www      5194:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5195:     my $reply='';
                   5196:     for (1..100) {
                   5197: 	sleep 2;
                   5198:         if (-e $replyfile.'.end') {
1.448     albertel 5199: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5200: 		$reply = join('',<$fh>);
                   5201: 		close($fh);
1.240     www      5202: 	   } else { return 'error: reply_file_error'; }
1.242     www      5203:            return &unescape($reply);
                   5204: 	}
1.240     www      5205:     }
1.242     www      5206:     return 'timeout:'.$queryid;
1.240     www      5207: }
                   5208: 
                   5209: sub courselog_query {
1.241     www      5210: #
                   5211: # possible filters:
                   5212: # url: url or symb
                   5213: # username
                   5214: # domain
                   5215: # action: view, submit, grade
                   5216: # start: timestamp
                   5217: # end: timestamp
                   5218: #
1.240     www      5219:     my (%filters)=@_;
1.620     albertel 5220:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5221:     if ($filters{'url'}) {
                   5222: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5223:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5224:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5225:     }
1.620     albertel 5226:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5227:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5228:     return &log_query($cname,$cdom,'courselog',%filters);
                   5229: }
                   5230: 
                   5231: sub userlog_query {
1.858     raeburn  5232: #
                   5233: # possible filters:
                   5234: # action: log check role
                   5235: # start: timestamp
                   5236: # end: timestamp
                   5237: #
1.240     www      5238:     my ($uname,$udom,%filters)=@_;
                   5239:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5240: }
                   5241: 
1.506     raeburn  5242: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5243: 
                   5244: sub auto_run {
1.508     raeburn  5245:     my ($cnum,$cdom) = @_;
1.876     raeburn  5246:     my $response = 0;
                   5247:     my $settings;
                   5248:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5249:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5250:         $settings = $domconfig{'autoenroll'};
                   5251:         if ($settings->{'run'} eq '1') {
                   5252:             $response = 1;
                   5253:         }
                   5254:     } else {
1.934     raeburn  5255:         my $homeserver;
                   5256:         if (&is_course($cdom,$cnum)) {
                   5257:             $homeserver = &homeserver($cnum,$cdom);
                   5258:         } else {
                   5259:             $homeserver = &domain($cdom,'primary');
                   5260:         }
                   5261:         if ($homeserver ne 'no_host') {
                   5262:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5263:         }
1.876     raeburn  5264:     }
1.506     raeburn  5265:     return $response;
                   5266: }
1.776     albertel 5267: 
1.506     raeburn  5268: sub auto_get_sections {
1.508     raeburn  5269:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5270:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5271:     my @secs = ();
1.511     raeburn  5272:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5273:     unless ($response eq 'refused') {
1.901     albertel 5274:         @secs = split(/:/,$response);
1.506     raeburn  5275:     }
                   5276:     return @secs;
                   5277: }
1.776     albertel 5278: 
1.506     raeburn  5279: sub auto_new_course {
1.508     raeburn  5280:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5281:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5282:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5283:     return $response;
                   5284: }
1.776     albertel 5285: 
1.506     raeburn  5286: sub auto_validate_courseID {
1.508     raeburn  5287:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5288:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5289:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5290:     return $response;
                   5291: }
1.776     albertel 5292: 
1.506     raeburn  5293: sub auto_create_password {
1.873     raeburn  5294:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5295:     my ($homeserver,$response);
1.506     raeburn  5296:     my $create_passwd = 0;
                   5297:     my $authchk = '';
1.873     raeburn  5298:     if ($udom =~ /^$match_domain$/) {
                   5299:         $homeserver = &domain($udom,'primary');
                   5300:     }
                   5301:     if ($homeserver eq '') {
                   5302:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5303:             $homeserver = &homeserver($cnum,$cdom);
                   5304:         }
                   5305:     }
                   5306:     if ($homeserver eq '') {
                   5307:         $authchk = 'nodomain';
1.506     raeburn  5308:     } else {
1.873     raeburn  5309:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5310:         if ($response eq 'refused') {
                   5311:             $authchk = 'refused';
                   5312:         } else {
1.901     albertel 5313:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5314:         }
1.506     raeburn  5315:     }
                   5316:     return ($authparam,$create_passwd,$authchk);
                   5317: }
                   5318: 
1.706     raeburn  5319: sub auto_photo_permission {
                   5320:     my ($cnum,$cdom,$students) = @_;
                   5321:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5322:     my ($outcome,$perm_reqd,$conditions) = 
                   5323: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5324:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5325: 	return (undef,undef);
                   5326:     }
1.706     raeburn  5327:     return ($outcome,$perm_reqd,$conditions);
                   5328: }
                   5329: 
                   5330: sub auto_checkphotos {
                   5331:     my ($uname,$udom,$pid) = @_;
                   5332:     my $homeserver = &homeserver($uname,$udom);
                   5333:     my ($result,$resulttype);
                   5334:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5335: 				   &escape($uname).':'.&escape($pid),
                   5336: 				   $homeserver));
1.709     albertel 5337:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5338: 	return (undef,undef);
                   5339:     }
1.706     raeburn  5340:     if ($outcome) {
                   5341:         ($result,$resulttype) = split(/:/,$outcome);
                   5342:     } 
                   5343:     return ($result,$resulttype);
                   5344: }
                   5345: 
                   5346: sub auto_photochoice {
                   5347:     my ($cnum,$cdom) = @_;
                   5348:     my $homeserver = &homeserver($cnum,$cdom);
                   5349:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5350: 						       &escape($cdom),
                   5351: 						       $homeserver)));
1.709     albertel 5352:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5353: 	return (undef,undef);
                   5354:     }
1.706     raeburn  5355:     return ($update,$comment);
                   5356: }
                   5357: 
                   5358: sub auto_photoupdate {
                   5359:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5360:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5361:     my $host=&hostname($homeserver);
1.706     raeburn  5362:     my $cmd = '';
                   5363:     my $maxtries = 1;
1.800     albertel 5364:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5365:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5366:     }
                   5367:     $cmd =~ s/%%$//;
                   5368:     $cmd = &escape($cmd);
                   5369:     my $query = 'institutionalphotos';
                   5370:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5371:     unless ($queryid=~/^\Q$host\E\_/) {
                   5372:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5373:         return 'error: '.$queryid;
                   5374:     }
                   5375:     my $reply = &get_query_reply($queryid);
                   5376:     my $tries = 1;
                   5377:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5378:         $reply = &get_query_reply($queryid);
                   5379:         $tries ++;
                   5380:     }
                   5381:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5382:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5383:     } else {
                   5384:         my @responses = split(/:/,$reply);
                   5385:         my $outcome = shift(@responses); 
                   5386:         foreach my $item (@responses) {
                   5387:             my ($key,$value) = split(/=/,$item);
                   5388:             $$photo{$key} = $value;
                   5389:         }
                   5390:         return $outcome;
                   5391:     }
                   5392:     return 'error';
                   5393: }
                   5394: 
1.521     raeburn  5395: sub auto_instcode_format {
1.793     albertel 5396:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5397: 	$cat_order) = @_;
1.521     raeburn  5398:     my $courses = '';
1.772     raeburn  5399:     my @homeservers;
1.521     raeburn  5400:     if ($caller eq 'global') {
1.841     albertel 5401: 	my %servers = &get_servers($codedom,'library');
                   5402: 	foreach my $tryserver (keys(%servers)) {
                   5403: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5404: 		push(@homeservers,$tryserver);
                   5405: 	    }
1.584     raeburn  5406:         }
1.521     raeburn  5407:     } else {
1.772     raeburn  5408:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5409:     }
1.793     albertel 5410:     foreach my $code (keys(%{$instcodes})) {
                   5411:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5412:     }
                   5413:     chop($courses);
1.772     raeburn  5414:     my $ok_response = 0;
                   5415:     my $response;
                   5416:     while (@homeservers > 0 && $ok_response == 0) {
                   5417:         my $server = shift(@homeservers); 
                   5418:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5419:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5420:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5421: 		split(/:/,$response);
1.772     raeburn  5422:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5423:             push(@{$codetitles},&str2array($codetitles_str));
                   5424:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5425:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5426:             $ok_response = 1;
                   5427:         }
                   5428:     }
                   5429:     if ($ok_response) {
1.521     raeburn  5430:         return 'ok';
1.772     raeburn  5431:     } else {
                   5432:         return $response;
1.521     raeburn  5433:     }
                   5434: }
                   5435: 
1.792     raeburn  5436: sub auto_instcode_defaults {
                   5437:     my ($domain,$returnhash,$code_order) = @_;
                   5438:     my @homeservers;
1.841     albertel 5439: 
                   5440:     my %servers = &get_servers($domain,'library');
                   5441:     foreach my $tryserver (keys(%servers)) {
                   5442: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5443: 	    push(@homeservers,$tryserver);
                   5444: 	}
1.792     raeburn  5445:     }
1.841     albertel 5446: 
1.792     raeburn  5447:     my $response;
1.841     albertel 5448:     foreach my $server (@homeservers) {
1.792     raeburn  5449:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5450:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5451: 	
                   5452: 	foreach my $pair (split(/\&/,$response)) {
                   5453: 	    my ($name,$value)=split(/\=/,$pair);
                   5454: 	    if ($name eq 'code_order') {
                   5455: 		@{$code_order} = split(/\&/,&unescape($value));
                   5456: 	    } else {
                   5457: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5458: 	    }
                   5459: 	}
                   5460: 	return 'ok';
1.792     raeburn  5461:     }
1.841     albertel 5462: 
                   5463:     return $response;
1.792     raeburn  5464: } 
                   5465: 
1.777     albertel 5466: sub auto_validate_class_sec {
1.918     raeburn  5467:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5468:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5469:     my $ownerlist;
                   5470:     if (ref($owners) eq 'ARRAY') {
                   5471:         $ownerlist = join(',',@{$owners});
                   5472:     } else {
                   5473:         $ownerlist = $owners;
                   5474:     }
1.773     raeburn  5475:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5476:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5477:     return $response;
                   5478: }
                   5479: 
1.679     raeburn  5480: # ------------------------------------------------------- Course Group routines
                   5481: 
                   5482: sub get_coursegroups {
1.809     raeburn  5483:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5484:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5485: }
                   5486: 
1.679     raeburn  5487: sub modify_coursegroup {
                   5488:     my ($cdom,$cnum,$groupsettings) = @_;
                   5489:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5490: }
                   5491: 
1.809     raeburn  5492: sub toggle_coursegroup_status {
                   5493:     my ($cdom,$cnum,$group,$action) = @_;
                   5494:     my ($from_namespace,$to_namespace);
                   5495:     if ($action eq 'delete') {
                   5496:         $from_namespace = 'coursegroups';
                   5497:         $to_namespace = 'deleted_groups';
                   5498:     } else {
                   5499:         $from_namespace = 'deleted_groups';
                   5500:         $to_namespace = 'coursegroups';
                   5501:     }
                   5502:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5503:     if (my $tmp = &error(%curr_group)) {
                   5504:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5505:         return ('read error',$tmp);
                   5506:     } else {
                   5507:         my %savedsettings = %curr_group; 
1.809     raeburn  5508:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5509:         my $deloutcome;
                   5510:         if ($result eq 'ok') {
1.809     raeburn  5511:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5512:         } else {
                   5513:             return ('write error',$result);
                   5514:         }
                   5515:         if ($deloutcome eq 'ok') {
                   5516:             return 'ok';
                   5517:         } else {
                   5518:             return ('delete error',$deloutcome);
                   5519:         }
                   5520:     }
                   5521: }
                   5522: 
1.679     raeburn  5523: sub modify_group_roles {
1.957     raeburn  5524:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5525:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5526:     my $role = 'gr/'.&escape($userprivs);
                   5527:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5528:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5529:     if ($result eq 'ok') {
                   5530:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5531:     }
1.679     raeburn  5532:     return $result;
                   5533: }
                   5534: 
                   5535: sub modify_coursegroup_membership {
                   5536:     my ($cdom,$cnum,$membership) = @_;
                   5537:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5538:     return $result;
                   5539: }
                   5540: 
1.682     raeburn  5541: sub get_active_groups {
                   5542:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5543:     my $now = time;
                   5544:     my %groups = ();
                   5545:     foreach my $key (keys(%env)) {
1.811     albertel 5546:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5547:             my ($start,$end) = split(/\./,$env{$key});
                   5548:             if (($end!=0) && ($end<$now)) { next; }
                   5549:             if (($start!=0) && ($start>$now)) { next; }
                   5550:             if ($1 eq $cdom && $2 eq $cnum) {
                   5551:                 $groups{$3} = $env{$key} ;
                   5552:             }
                   5553:         }
                   5554:     }
                   5555:     return %groups;
                   5556: }
                   5557: 
1.683     raeburn  5558: sub get_group_membership {
                   5559:     my ($cdom,$cnum,$group) = @_;
                   5560:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5561: }
                   5562: 
                   5563: sub get_users_groups {
                   5564:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5565:     my @usersgroups;
1.683     raeburn  5566:     my $cachetime=1800;
                   5567: 
                   5568:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5569:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5570:     if (defined($cached)) {
1.734     albertel 5571:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5572:     } else {  
                   5573:         $grouplist = '';
1.816     raeburn  5574:         my $courseurl = &courseid_to_courseurl($courseid);
                   5575:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5576:         my $access_end = $env{'course.'.$courseid.
                   5577:                               '.default_enrollment_end_date'};
                   5578:         my $now = time;
                   5579:         foreach my $key (keys(%roleshash)) {
                   5580:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5581:                 my $group = $1;
                   5582:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5583:                     my $start = $2;
                   5584:                     my $end = $1;
                   5585:                     if ($start == -1) { next; } # deleted from group
                   5586:                     if (($start!=0) && ($start>$now)) { next; }
                   5587:                     if (($end!=0) && ($end<$now)) {
                   5588:                         if ($access_end && $access_end < $now) {
                   5589:                             if ($access_end - $end < 86400) {
                   5590:                                 push(@usersgroups,$group);
1.733     raeburn  5591:                             }
                   5592:                         }
1.817     raeburn  5593:                         next;
1.733     raeburn  5594:                     }
1.817     raeburn  5595:                     push(@usersgroups,$group);
1.683     raeburn  5596:                 }
                   5597:             }
                   5598:         }
1.817     raeburn  5599:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5600:         $grouplist = join(':',@usersgroups);
                   5601:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5602:     }
1.733     raeburn  5603:     return @usersgroups;
1.683     raeburn  5604: }
                   5605: 
                   5606: sub devalidate_getgroups_cache {
                   5607:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5608:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5609: 
1.683     raeburn  5610:     my $hashid="$udom:$uname:$courseid";
                   5611:     &devalidate_cache_new('getgroups',$hashid);
                   5612: }
                   5613: 
1.12      www      5614: # ------------------------------------------------------------------ Plain Text
                   5615: 
                   5616: sub plaintext {
1.742     raeburn  5617:     my ($short,$type,$cid) = @_;
1.758     albertel 5618:     if ($short =~ /^cr/) {
                   5619: 	return (split('/',$short))[-1];
                   5620:     }
1.742     raeburn  5621:     if (!defined($cid)) {
                   5622:         $cid = $env{'request.course.id'};
                   5623:     }
                   5624:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5625:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5626:                                           '.plaintext'});
                   5627:     }
                   5628:     my %rolenames = (
                   5629:                       Course => 'std',
                   5630:                       Group => 'alt1',
                   5631:                     );
                   5632:     if (defined($type) && 
                   5633:          defined($rolenames{$type}) && 
                   5634:          defined($prp{$short}{$rolenames{$type}})) {
                   5635:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5636:     } else {
                   5637:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5638:     }
1.12      www      5639: }
                   5640: 
                   5641: # ----------------------------------------------------------------- Assign Role
                   5642: 
                   5643: sub assignrole {
1.957     raeburn  5644:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5645:         $context)=@_;
1.21      www      5646:     my $mrole;
                   5647:     if ($role =~ /^cr\//) {
1.393     www      5648:         my $cwosec=$url;
1.811     albertel 5649:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5650: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5651:            &logthis('Refused custom assignrole: '.
                   5652:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5653: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5654:            return 'refused'; 
                   5655:         }
1.21      www      5656:         $mrole='cr';
1.678     raeburn  5657:     } elsif ($role =~ /^gr\//) {
                   5658:         my $cwogrp=$url;
1.811     albertel 5659:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5660:         unless (&allowed('mdg',$cwogrp)) {
                   5661:             &logthis('Refused group assignrole: '.
                   5662:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5663:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5664:             return 'refused';
                   5665:         }
                   5666:         $mrole='gr';
1.21      www      5667:     } else {
1.82      www      5668:         my $cwosec=$url;
1.811     albertel 5669:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5670:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5671:             my $refused;
                   5672:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5673:                 if (!(&allowed('c'.$role,$url))) {
                   5674:                     $refused = 1;
                   5675:                 }
                   5676:             } else {
                   5677:                 $refused = 1;
                   5678:             }
1.947     raeburn  5679:             if ($refused) {
                   5680:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5681:                     $refused = '';
                   5682:                 } else {
                   5683:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5684:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5685: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5686:                     return 'refused';
                   5687:                 }
1.932     raeburn  5688:             }
1.104     www      5689:         }
1.21      www      5690:         $mrole=$role;
                   5691:     }
1.620     albertel 5692:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5693:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5694:     if ($end) { $command.='_'.$end; }
1.21      www      5695:     if ($start) {
                   5696: 	if ($end) { 
1.81      www      5697:            $command.='_'.$start; 
1.21      www      5698:         } else {
1.81      www      5699:            $command.='_0_'.$start;
1.21      www      5700:         }
                   5701:     }
1.739     raeburn  5702:     my $origstart = $start;
                   5703:     my $origend = $end;
1.957     raeburn  5704:     my $delflag;
1.357     www      5705: # actually delete
                   5706:     if ($deleteflag) {
1.373     www      5707: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5708: # modify command to delete the role
1.620     albertel 5709:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5710:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5711: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5712: # set start and finish to negative values for userrolelog
                   5713:            $start=-1;
                   5714:            $end=-1;
1.957     raeburn  5715:            $delflag = 1;
1.357     www      5716:         }
                   5717:     }
                   5718: # send command
1.349     www      5719:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5720: # log new user role if status is ok
1.349     www      5721:     if ($answer eq 'ok') {
1.663     raeburn  5722: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5723: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5724:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5725:         unless ($role =~ /^gr/) {
                   5726:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5727:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5728:         }
1.349     www      5729:     }
                   5730:     return $answer;
1.169     harris41 5731: }
                   5732: 
                   5733: # -------------------------------------------------- Modify user authentication
1.197     www      5734: # Overrides without validation
                   5735: 
1.169     harris41 5736: sub modifyuserauth {
                   5737:     my ($udom,$uname,$umode,$upass)=@_;
                   5738:     my $uhome=&homeserver($uname,$udom);
1.197     www      5739:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5740:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5741:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5742:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5743:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5744: 		     &escape($upass),$uhome);
1.620     albertel 5745:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5746:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5747:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5748:     &log($udom,,$uname,$uhome,
1.620     albertel 5749:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5750:                                      $env{'user.name'}.', '.$umode.
1.197     www      5751:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5752:     unless ($reply eq 'ok') {
1.197     www      5753:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5754: 	return 'error: '.$reply;
                   5755:     }   
1.170     harris41 5756:     return 'ok';
1.80      www      5757: }
                   5758: 
1.81      www      5759: # --------------------------------------------------------------- Modify a user
1.80      www      5760: 
1.81      www      5761: sub modifyuser {
1.206     matthew  5762:     my ($udom,    $uname, $uid,
                   5763:         $umode,   $upass, $first,
                   5764:         $middle,  $last,  $gene,
1.963     raeburn  5765:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5766:     $udom= &LONCAPA::clean_domain($udom);
                   5767:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5768:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5769:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5770: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5771:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5772:                                      ' desiredhome not specified'). 
1.620     albertel 5773:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5774:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5775:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5776: # ----------------------------------------------------------------- Create User
1.406     albertel 5777:     if (($uhome eq 'no_host') && 
                   5778: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5779:         my $unhome='';
1.844     albertel 5780:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5781:             $unhome = $desiredhome;
1.620     albertel 5782: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5783: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5784:         } else { # load balancing routine for determining $unhome
1.81      www      5785:             my $loadm=10000000;
1.841     albertel 5786: 	    my %servers = &get_servers($udom,'library');
                   5787: 	    foreach my $tryserver (keys(%servers)) {
                   5788: 		my $answer=reply('load',$tryserver);
                   5789: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5790: 		    $loadm=$answer;
                   5791: 		    $unhome=$tryserver;
                   5792: 		}
1.80      www      5793: 	    }
                   5794:         }
                   5795:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5796: 	    return 'error: unable to find a home server for '.$uname.
                   5797:                    ' in domain '.$udom;
1.80      www      5798:         }
                   5799:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5800:                          &escape($upass),$unhome);
                   5801: 	unless ($reply eq 'ok') {
                   5802:             return 'error: '.$reply;
                   5803:         }   
1.230     stredwic 5804:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5805:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5806: 	    return 'error: unable verify users home machine.';
1.80      www      5807:         }
1.209     matthew  5808:     }   # End of creation of new user
1.80      www      5809: # ---------------------------------------------------------------------- Add ID
                   5810:     if ($uid) {
                   5811:        $uid=~tr/A-Z/a-z/;
                   5812:        my %uidhash=&idrget($udom,$uname);
1.196     www      5813:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5814:          && (!$forceid)) {
1.80      www      5815: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5816: 	      return 'error: user id "'.$uid.'" does not match '.
                   5817:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5818:           }
                   5819:        } else {
                   5820: 	  &idput($udom,($uname => $uid));
                   5821:        }
                   5822:     }
                   5823: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5824:     my @tmp=&get('environment',
1.899     raeburn  5825: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5826:                     'permanentemail','inststatus'],
1.134     albertel 5827: 		   $udom,$uname);
1.313     matthew  5828:     my %names;
                   5829:     if ($tmp[0] =~ m/^error:.*/) { 
                   5830:         %names=(); 
                   5831:     } else {
                   5832:         %names = @tmp;
                   5833:     }
1.388     www      5834: #
                   5835: # Make sure to not trash student environment if instructor does not bother
                   5836: # to supply name and email information
                   5837: #
                   5838:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5839:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5840:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5841:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5842:     if ($email) {
                   5843:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5844:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5845:     }
1.899     raeburn  5846:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5847:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5848:     my $reply = &put('environment', \%names, $udom,$uname);
                   5849:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5850:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5851:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5852:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5853:                  $umode.', '.$first.', '.$middle.', '.
                   5854: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5855:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5856:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5857:     } else {
                   5858:         $logmsg .= ' during self creation';
                   5859:     }
                   5860:     &logthis($logmsg);
1.134     albertel 5861:     return 'ok';
1.80      www      5862: }
                   5863: 
1.81      www      5864: # -------------------------------------------------------------- Modify student
1.80      www      5865: 
1.81      www      5866: sub modifystudent {
                   5867:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5868:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5869:         $selfenroll,$context)=@_;
1.455     albertel 5870:     if (!$cid) {
1.620     albertel 5871: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5872: 	    return 'not_in_class';
                   5873: 	}
1.80      www      5874:     }
                   5875: # --------------------------------------------------------------- Make the user
1.81      www      5876:     my $reply=&modifyuser
1.209     matthew  5877: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5878:          $desiredhome,$email);
1.80      www      5879:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5880:     # This will cause &modify_student_enrollment to get the uid from the
                   5881:     # students environment
                   5882:     $uid = undef if (!$forceid);
1.455     albertel 5883:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5884: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5885:     return $reply;
                   5886: }
                   5887: 
                   5888: sub modify_student_enrollment {
1.957     raeburn  5889:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5890:     my ($cdom,$cnum,$chome);
                   5891:     if (!$cid) {
1.620     albertel 5892: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5893: 	    return 'not_in_class';
                   5894: 	}
1.620     albertel 5895: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5896: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5897:     } else {
                   5898: 	($cdom,$cnum)=split(/_/,$cid);
                   5899:     }
1.620     albertel 5900:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5901:     if (!$chome) {
1.457     raeburn  5902: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5903:     }
1.455     albertel 5904:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5905:     # Make sure the user exists
1.81      www      5906:     my $uhome=&homeserver($uname,$udom);
                   5907:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5908: 	return 'error: no such user';
                   5909:     }
1.297     matthew  5910:     # Get student data if we were not given enough information
                   5911:     if (!defined($first)  || $first  eq '' || 
                   5912:         !defined($last)   || $last   eq '' || 
                   5913:         !defined($uid)    || $uid    eq '' || 
                   5914:         !defined($middle) || $middle eq '' || 
                   5915:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5916:         # They did not supply us with enough data to enroll the student, so
                   5917:         # we need to pick up more information.
1.297     matthew  5918:         my %tmp = &get('environment',
1.294     matthew  5919:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5920:                        ,$udom,$uname);
                   5921: 
1.800     albertel 5922:         #foreach my $key (keys(%tmp)) {
                   5923:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5924:         #}
1.294     matthew  5925:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5926:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5927:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5928:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5929:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5930:     }
1.556     albertel 5931:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5932:     my $reply=cput('classlist',
                   5933: 		   {"$uname:$udom" => 
1.515     raeburn  5934: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5935: 		   $cdom,$cnum);
1.81      www      5936:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5937: 	return 'error: '.$reply;
1.652     albertel 5938:     } else {
                   5939: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5940:     }
1.297     matthew  5941:     # Add student role to user
1.83      www      5942:     my $uurl='/'.$cid;
1.81      www      5943:     $uurl=~s/\_/\//g;
                   5944:     if ($usec) {
                   5945: 	$uurl.='/'.$usec;
                   5946:     }
1.957     raeburn  5947:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5948: }
                   5949: 
1.556     albertel 5950: sub format_name {
                   5951:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5952:     my $name;
                   5953:     if ($first ne 'lastname') {
                   5954: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5955:     } else {
                   5956: 	if ($lastname=~/\S/) {
                   5957: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5958: 	    $name=~s/\s+,/,/;
                   5959: 	} else {
                   5960: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5961: 	}
                   5962:     }
                   5963:     $name=~s/^\s+//;
                   5964:     $name=~s/\s+$//;
                   5965:     $name=~s/\s+/ /g;
                   5966:     return $name;
                   5967: }
                   5968: 
1.84      www      5969: # ------------------------------------------------- Write to course preferences
                   5970: 
                   5971: sub writecoursepref {
                   5972:     my ($courseid,%prefs)=@_;
                   5973:     $courseid=~s/^\///;
                   5974:     $courseid=~s/\_/\//g;
                   5975:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5976:     my $chome=homeserver($cnum,$cdomain);
                   5977:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5978: 	return 'error: no such course';
                   5979:     }
                   5980:     my $cstring='';
1.800     albertel 5981:     foreach my $pref (keys(%prefs)) {
                   5982: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5983:     }
1.84      www      5984:     $cstring=~s/\&$//;
                   5985:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5986: }
                   5987: 
                   5988: # ---------------------------------------------------------- Make/modify course
                   5989: 
                   5990: sub createcourse {
1.741     raeburn  5991:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5992:         $course_owner,$crstype)=@_;
1.84      www      5993:     $url=&declutter($url);
                   5994:     my $cid='';
1.264     matthew  5995:     unless (&allowed('ccc',$udom)) {
1.84      www      5996:         return 'refused';
                   5997:     }
                   5998: # ------------------------------------------------------------------- Create ID
1.674     www      5999:    my $uname=int(1+rand(9)).
                   6000:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6001:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6002:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6003: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6004:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6005:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6006:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6007:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6008:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6009:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6010:            return 'error: unable to generate unique course-ID';
                   6011:        } 
                   6012:    }
1.264     matthew  6013: # ------------------------------------------------ Check supplied server name
1.620     albertel 6014:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6015:     if (! &is_library($course_server)) {
1.264     matthew  6016:         return 'error:bad server name '.$course_server;
                   6017:     }
1.84      www      6018: # ------------------------------------------------------------- Make the course
                   6019:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6020:                       $course_server);
1.84      www      6021:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6022:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6023:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6024: 	return 'error: no such course';
                   6025:     }
1.271     www      6026: # ----------------------------------------------------------------- Course made
1.516     raeburn  6027: # log existence
1.918     raeburn  6028:     my $newcourse = {
                   6029:                     $udom.'_'.$uname => {
1.921     raeburn  6030:                                      description => $description,
                   6031:                                      inst_code   => $inst_code,
                   6032:                                      owner       => $course_owner,
                   6033:                                      type        => $crstype,
1.918     raeburn  6034:                                                 },
                   6035:                     };
1.921     raeburn  6036:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6037: # set toplevel url
1.271     www      6038:     my $topurl=$url;
                   6039:     unless ($nonstandard) {
                   6040: # ------------------------------------------ For standard courses, make top url
                   6041:         my $mapurl=&clutter($url);
1.278     www      6042:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6043:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6044: <map>
                   6045: <resource id="1" type="start"></resource>
                   6046: <resource id="2" src="$mapurl"></resource>
                   6047: <resource id="3" type="finish"></resource>
                   6048: <link index="1" from="1" to="2"></link>
                   6049: <link index="2" from="2" to="3"></link>
                   6050: </map>
                   6051: ENDINITMAP
                   6052:         $topurl=&declutter(
1.638     albertel 6053:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6054:                           );
                   6055:     }
                   6056: # ----------------------------------------------------------- Write preferences
1.84      www      6057:     &writecoursepref($udom.'_'.$uname,
                   6058:                      ('description' => $description,
1.271     www      6059:                       'url'         => $topurl));
1.84      www      6060:     return '/'.$udom.'/'.$uname;
                   6061: }
                   6062: 
1.813     albertel 6063: sub is_course {
                   6064:     my ($cdom,$cnum) = @_;
                   6065:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6066: 				undef,'.');
1.813     albertel 6067:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6068:         return 1;
                   6069:     }
                   6070:     return 0;
                   6071: }
                   6072: 
1.21      www      6073: # ---------------------------------------------------------- Assign Custom Role
                   6074: 
                   6075: sub assigncustomrole {
1.957     raeburn  6076:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6077:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6078:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6079: }
                   6080: 
                   6081: # ----------------------------------------------------------------- Revoke Role
                   6082: 
                   6083: sub revokerole {
1.957     raeburn  6084:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6085:     my $now=time;
1.965     raeburn  6086:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6087: }
                   6088: 
                   6089: # ---------------------------------------------------------- Revoke Custom Role
                   6090: 
                   6091: sub revokecustomrole {
1.957     raeburn  6092:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6093:     my $now=time;
1.357     www      6094:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6095:            $deleteflag,$selfenroll,$context);
1.17      www      6096: }
                   6097: 
1.533     banghart 6098: # ------------------------------------------------------------ Disk usage
1.535     albertel 6099: sub diskusage {
1.955     raeburn  6100:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6101:     $directorypath =~ s/\/$//;
                   6102:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6103:                        .&escape($getpropath).':'.&escape($uname).':'
                   6104:                        .&escape($udom),homeserver($uname,$udom));
                   6105:     if ($listing eq 'unknown_cmd') {
                   6106:         if ($getpropath) {
                   6107:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6108:         }
                   6109:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6110:     }
1.514     albertel 6111:     return $listing;
1.512     banghart 6112: }
                   6113: 
1.566     banghart 6114: sub is_locked {
                   6115:     my ($file_name, $domain, $user) = @_;
                   6116:     my @check;
                   6117:     my $is_locked;
                   6118:     push @check, $file_name;
1.613     albertel 6119:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6120: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6121:     my ($tmp)=keys(%locked);
                   6122:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6123:     
1.566     banghart 6124:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6125:         $is_locked = 'false';
                   6126:         foreach my $entry (@{$locked{$file_name}}) {
                   6127:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6128:                $is_locked = 'true';
                   6129:                last;
1.745     raeburn  6130:            }
                   6131:        }
1.566     banghart 6132:     } else {
                   6133:         $is_locked = 'false';
                   6134:     }
                   6135: }
                   6136: 
1.759     albertel 6137: sub declutter_portfile {
                   6138:     my ($file) = @_;
1.833     albertel 6139:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6140:     return $file;
                   6141: }
                   6142: 
1.559     banghart 6143: # ------------------------------------------------------------- Mark as Read Only
                   6144: 
                   6145: sub mark_as_readonly {
                   6146:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6147:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6148:     my ($tmp)=keys(%current_permissions);
                   6149:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6150:     foreach my $file (@{$files}) {
1.759     albertel 6151: 	$file = &declutter_portfile($file);
1.561     banghart 6152:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6153:     }
1.613     albertel 6154:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6155:     return;
                   6156: }
                   6157: 
1.572     banghart 6158: # ------------------------------------------------------------Save Selected Files
                   6159: 
                   6160: sub save_selected_files {
                   6161:     my ($user, $path, @files) = @_;
                   6162:     my $filename = $user."savedfiles";
1.573     banghart 6163:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6164:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6165:     foreach my $file (@files) {
1.620     albertel 6166:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6167:     }
                   6168:     foreach my $file (@other_files) {
1.574     banghart 6169:         print (OUT $file."\n");
1.572     banghart 6170:     }
1.574     banghart 6171:     close (OUT);
1.572     banghart 6172:     return 'ok';
                   6173: }
                   6174: 
1.574     banghart 6175: sub clear_selected_files {
                   6176:     my ($user) = @_;
                   6177:     my $filename = $user."savedfiles";
                   6178:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6179:     print (OUT undef);
                   6180:     close (OUT);
                   6181:     return ("ok");    
                   6182: }
                   6183: 
1.572     banghart 6184: sub files_in_path {
                   6185:     my ($user, $path) = @_;
                   6186:     my $filename = $user."savedfiles";
                   6187:     my %return_files;
1.574     banghart 6188:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6189:     while (my $line_in = <IN>) {
1.574     banghart 6190:         chomp ($line_in);
                   6191:         my @paths_and_file = split (m!/!, $line_in);
                   6192:         my $file_part = pop (@paths_and_file);
                   6193:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6194:         $path_part.='/';
                   6195:         my $path_and_file = $path_part.$file_part;
                   6196:         if ($path_part eq $path) {
                   6197:             $return_files{$file_part}= 'selected';
                   6198:         }
                   6199:     }
1.574     banghart 6200:     close (IN);
                   6201:     return (\%return_files);
1.572     banghart 6202: }
                   6203: 
                   6204: # called in portfolio select mode, to show files selected NOT in current directory
                   6205: sub files_not_in_path {
                   6206:     my ($user, $path) = @_;
                   6207:     my $filename = $user."savedfiles";
                   6208:     my @return_files;
                   6209:     my $path_part;
1.800     albertel 6210:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6211:     while (my $line = <IN>) {
1.572     banghart 6212:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6213:         my @paths_and_file = split(m|/|, $line);
                   6214:         my $file_part = pop(@paths_and_file);
                   6215:         chomp($file_part);
                   6216:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6217:         $path_part .= '/';
                   6218:         my $path_and_file = $path_part.$file_part;
                   6219:         if ($path_part ne $path) {
1.800     albertel 6220:             push(@return_files, ($path_and_file));
1.572     banghart 6221:         }
                   6222:     }
1.800     albertel 6223:     close(OUT);
1.574     banghart 6224:     return (@return_files);
1.572     banghart 6225: }
                   6226: 
1.745     raeburn  6227: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6228: 
1.745     raeburn  6229: sub get_portfile_permissions {
                   6230:     my ($domain,$user) = @_;
1.613     albertel 6231:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6232:     my ($tmp)=keys(%current_permissions);
                   6233:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6234:     return \%current_permissions;
                   6235: }
                   6236: 
                   6237: #---------------------------------------------Get portfolio file access controls
                   6238: 
1.749     raeburn  6239: sub get_access_controls {
1.745     raeburn  6240:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6241:     my %access;
                   6242:     my $real_file = $file;
                   6243:     $file =~ s/\.meta$//;
1.745     raeburn  6244:     if (defined($file)) {
1.749     raeburn  6245:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6246:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6247:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6248:             }
                   6249:         }
1.745     raeburn  6250:     } else {
1.749     raeburn  6251:         foreach my $key (keys(%{$current_permissions})) {
                   6252:             if ($key =~ /\0accesscontrol$/) {
                   6253:                 if (defined($group)) {
                   6254:                     if ($key !~ m-^\Q$group\E/-) {
                   6255:                         next;
                   6256:                     }
                   6257:                 }
                   6258:                 my ($fullpath) = split(/\0/,$key);
                   6259:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6260:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6261:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6262:                     }
                   6263:                 }
                   6264:             }
                   6265:         }
                   6266:     }
                   6267:     return %access;
                   6268: }
                   6269: 
                   6270: sub modify_access_controls {
                   6271:     my ($file_name,$changes,$domain,$user)=@_;
                   6272:     my ($outcome,$deloutcome);
                   6273:     my %store_permissions;
                   6274:     my %new_values;
                   6275:     my %new_control;
                   6276:     my %translation;
                   6277:     my @deletions = ();
                   6278:     my $now = time;
                   6279:     if (exists($$changes{'activate'})) {
                   6280:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6281:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6282:             my $numnew = scalar(@newitems);
                   6283:             for (my $i=0; $i<$numnew; $i++) {
                   6284:                 my $newkey = $newitems[$i];
                   6285:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6286:                 if ($newkey =~ /^\d+:/) { 
                   6287:                     $newkey =~ s/^(\d+)/$newid/;
                   6288:                     $translation{$1} = $newid;
                   6289:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6290:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6291:                     $translation{$1} = $newid;
                   6292:                 }
1.749     raeburn  6293:                 $new_values{$file_name."\0".$newkey} = 
                   6294:                                           $$changes{'activate'}{$newitems[$i]};
                   6295:                 $new_control{$newkey} = $now;
                   6296:             }
                   6297:         }
                   6298:     }
                   6299:     my %todelete;
                   6300:     my %changed_items;
                   6301:     foreach my $action ('delete','update') {
                   6302:         if (exists($$changes{$action})) {
                   6303:             if (ref($$changes{$action}) eq 'HASH') {
                   6304:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6305:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6306:                     if ($action eq 'delete') { 
                   6307:                         $todelete{$itemnum} = 1;
                   6308:                     } else {
                   6309:                         $changed_items{$itemnum} = $key;
                   6310:                     }
                   6311:                 }
1.745     raeburn  6312:             }
                   6313:         }
1.749     raeburn  6314:     }
                   6315:     # get lock on access controls for file.
                   6316:     my $lockhash = {
                   6317:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6318:                                                        ':'.$env{'user.domain'},
                   6319:                    }; 
                   6320:     my $tries = 0;
                   6321:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6322:    
                   6323:     while (($gotlock ne 'ok') && $tries <3) {
                   6324:         $tries ++;
                   6325:         sleep 1;
                   6326:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6327:     }
                   6328:     if ($gotlock eq 'ok') {
                   6329:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6330:         my ($tmp)=keys(%curr_permissions);
                   6331:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6332:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6333:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6334:             if (ref($curr_controls) eq 'HASH') {
                   6335:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6336:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6337:                     if (defined($todelete{$itemnum})) {
                   6338:                         push(@deletions,$file_name."\0".$control_item);
                   6339:                     } else {
                   6340:                         if (defined($changed_items{$itemnum})) {
                   6341:                             $new_control{$changed_items{$itemnum}} = $now;
                   6342:                             push(@deletions,$file_name."\0".$control_item);
                   6343:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6344:                         } else {
                   6345:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6346:                         }
                   6347:                     }
1.745     raeburn  6348:                 }
                   6349:             }
                   6350:         }
1.970     raeburn  6351:         my ($group);
                   6352:         if (&is_course($domain,$user)) {
                   6353:             ($group,my $file) = split(/\//,$file_name,2);
                   6354:         }
1.749     raeburn  6355:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6356:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6357:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6358:         #  remove lock
                   6359:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6360:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6361:         my $sqlresult =
1.970     raeburn  6362:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6363:                                     $group);
1.749     raeburn  6364:     } else {
                   6365:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6366:     }
1.749     raeburn  6367:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6368: }
                   6369: 
1.827     raeburn  6370: sub make_public_indefinitely {
                   6371:     my ($requrl) = @_;
                   6372:     my $now = time;
                   6373:     my $action = 'activate';
                   6374:     my $aclnum = 0;
                   6375:     if (&is_portfolio_url($requrl)) {
                   6376:         my (undef,$udom,$unum,$file_name,$group) =
                   6377:             &parse_portfolio_url($requrl);
                   6378:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6379:         my %access_controls = &get_access_controls($current_perms,
                   6380:                                                    $group,$file_name);
                   6381:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6382:             my ($num,$scope,$end,$start) = 
                   6383:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6384:             if ($scope eq 'public') {
                   6385:                 if ($start <= $now && $end == 0) {
                   6386:                     $action = 'none';
                   6387:                 } else {
                   6388:                     $action = 'update';
                   6389:                     $aclnum = $num;
                   6390:                 }
                   6391:                 last;
                   6392:             }
                   6393:         }
                   6394:         if ($action eq 'none') {
                   6395:              return 'ok';
                   6396:         } else {
                   6397:             my %changes;
                   6398:             my $newend = 0;
                   6399:             my $newstart = $now;
                   6400:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6401:             $changes{$action}{$newkey} = {
                   6402:                 type => 'public',
                   6403:                 time => {
                   6404:                     start => $newstart,
                   6405:                     end   => $newend,
                   6406:                 },
                   6407:             };
                   6408:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6409:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6410:             return $outcome;
                   6411:         }
                   6412:     } else {
                   6413:         return 'invalid';
                   6414:     }
                   6415: }
                   6416: 
1.745     raeburn  6417: #------------------------------------------------------Get Marked as Read Only
                   6418: 
                   6419: sub get_marked_as_readonly {
                   6420:     my ($domain,$user,$what,$group) = @_;
                   6421:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6422:     my @readonly_files;
1.629     banghart 6423:     my $cmp1=$what;
                   6424:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6425:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6426:         if (defined($group)) {
                   6427:             if ($file_name !~ m-^\Q$group\E/-) {
                   6428:                 next;
                   6429:             }
                   6430:         }
1.561     banghart 6431:         if (ref($value) eq "ARRAY"){
                   6432:             foreach my $stored_what (@{$value}) {
1.629     banghart 6433:                 my $cmp2=$stored_what;
1.759     albertel 6434:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6435:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6436:                 }
1.629     banghart 6437:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6438:                     push(@readonly_files, $file_name);
1.745     raeburn  6439:                     last;
1.563     banghart 6440:                 } elsif (!defined($what)) {
                   6441:                     push(@readonly_files, $file_name);
1.745     raeburn  6442:                     last;
1.561     banghart 6443:                 }
                   6444:             }
1.745     raeburn  6445:         }
1.561     banghart 6446:     }
                   6447:     return @readonly_files;
                   6448: }
1.577     banghart 6449: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6450: 
1.577     banghart 6451: sub get_marked_as_readonly_hash {
1.745     raeburn  6452:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6453:     my %readonly_files;
1.745     raeburn  6454:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6455:         if (defined($group)) {
                   6456:             if ($file_name !~ m-^\Q$group\E/-) {
                   6457:                 next;
                   6458:             }
                   6459:         }
1.577     banghart 6460:         if (ref($value) eq "ARRAY"){
                   6461:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6462:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6463:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6464:                         if ($lock_descriptor eq 'graded') {
                   6465:                             $readonly_files{$file_name} = 'graded';
                   6466:                         } elsif ($lock_descriptor eq 'handback') {
                   6467:                             $readonly_files{$file_name} = 'handback';
                   6468:                         } else {
                   6469:                             if (!exists($readonly_files{$file_name})) {
                   6470:                                 $readonly_files{$file_name} = 'locked';
                   6471:                             }
                   6472:                         }
1.745     raeburn  6473:                     }
1.750     banghart 6474:                 } 
1.577     banghart 6475:             }
                   6476:         } 
                   6477:     }
                   6478:     return %readonly_files;
                   6479: }
1.559     banghart 6480: # ------------------------------------------------------------ Unmark as Read Only
                   6481: 
                   6482: sub unmark_as_readonly {
1.629     banghart 6483:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6484:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6485:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6486:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6487:     my $symb_crs = $what;
                   6488:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6489:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6490:     my ($tmp)=keys(%current_permissions);
                   6491:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6492:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6493:     foreach my $file (@readonly_files) {
1.759     albertel 6494: 	my $clean_file = &declutter_portfile($file);
                   6495: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6496: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6497:         my @new_locks;
                   6498:         my @del_keys;
                   6499:         if (ref($current_locks) eq "ARRAY"){
                   6500:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6501:                 my $compare=$locker;
1.749     raeburn  6502:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6503:                     $compare=join('',@{$locker});
1.746     raeburn  6504:                     if ($compare ne $symb_crs) {
                   6505:                         push(@new_locks, $locker);
                   6506:                     }
1.563     banghart 6507:                 }
                   6508:             }
1.650     albertel 6509:             if (scalar(@new_locks) > 0) {
1.563     banghart 6510:                 $current_permissions{$file} = \@new_locks;
                   6511:             } else {
                   6512:                 push(@del_keys, $file);
1.613     albertel 6513:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6514:                 delete($current_permissions{$file});
1.563     banghart 6515:             }
                   6516:         }
1.561     banghart 6517:     }
1.613     albertel 6518:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6519:     return;
                   6520: }
1.512     banghart 6521: 
1.17      www      6522: # ------------------------------------------------------------ Directory lister
                   6523: 
                   6524: sub dirlist {
1.955     raeburn  6525:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6526:     $uri=~s/^\///;
                   6527:     $uri=~s/\/$//;
1.253     stredwic 6528:     my ($udom, $uname);
1.955     raeburn  6529:     if ($getuserdir) {
1.253     stredwic 6530:         $udom = $userdomain;
                   6531:         $uname = $username;
1.955     raeburn  6532:     } else {
                   6533:         (undef,$udom,$uname)=split(/\//,$uri);
                   6534:         if(defined($userdomain)) {
                   6535:             $udom = $userdomain;
                   6536:         }
                   6537:         if(defined($username)) {
                   6538:             $uname = $username;
                   6539:         }
1.253     stredwic 6540:     }
1.955     raeburn  6541:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6542: 
1.955     raeburn  6543:     $dirRoot = $perlvar{'lonDocRoot'};
                   6544:     if (defined($getpropath)) {
                   6545:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6546:         $dirRoot =~ s/\/$//;
1.955     raeburn  6547:     } elsif (defined($getuserdir)) {
                   6548:         my $subdir=$uname.'__';
                   6549:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6550:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6551:                    ."/$udom/$subdir/$uname";
                   6552:     } elsif (defined($alternateRoot)) {
                   6553:         $dirRoot = $alternateRoot;
1.751     banghart 6554:     }
1.253     stredwic 6555: 
                   6556:     if($udom) {
                   6557:         if($uname) {
1.955     raeburn  6558:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6559:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6560:                               .':'.&escape($uname).':'.&escape($udom),
                   6561:                               &homeserver($uname,$udom));
                   6562:             if ($listing eq 'unknown_cmd') {
                   6563:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6564:                                   &homeserver($uname,$udom));
                   6565:             } else {
                   6566:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6567:             }
1.605     matthew  6568:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6569:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6570: 				  &homeserver($uname,$udom));
1.605     matthew  6571:                 @listing_results = split(/:/,$listing);
                   6572:             } else {
                   6573:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6574:             }
                   6575:             return @listing_results;
1.955     raeburn  6576:         } elsif(!$alternateRoot) {
1.800     albertel 6577:             my %allusers;
1.841     albertel 6578: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6579:  	    foreach my $tryserver (keys(%servers)) {
                   6580:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6581:                                   &escape($udom),$tryserver);
                   6582:                 if ($listing eq 'unknown_cmd') {
                   6583: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6584: 				      $udom, $tryserver);
                   6585:                 } else {
                   6586:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6587:                 }
1.841     albertel 6588: 		if ($listing eq 'unknown_cmd') {
                   6589: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6590: 				      $udom, $tryserver);
                   6591: 		    @listing_results = split(/:/,$listing);
                   6592: 		} else {
                   6593: 		    @listing_results =
                   6594: 			map { &unescape($_); } split(/:/,$listing);
                   6595: 		}
                   6596: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6597: 		    $listing_results[0] ne 'empty'       &&
                   6598: 		    $listing_results[0] ne 'con_lost') {
                   6599: 		    foreach my $line (@listing_results) {
                   6600: 			my ($entry) = split(/&/,$line,2);
                   6601: 			$allusers{$entry} = 1;
                   6602: 		    }
                   6603: 		}
1.253     stredwic 6604:             }
                   6605:             my $alluserstr='';
1.800     albertel 6606:             foreach my $user (sort(keys(%allusers))) {
                   6607:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6608:             }
                   6609:             $alluserstr=~s/:$//;
                   6610:             return split(/:/,$alluserstr);
                   6611:         } else {
1.800     albertel 6612:             return ('missing user name');
1.253     stredwic 6613:         }
1.955     raeburn  6614:     } elsif(!defined($getpropath)) {
1.841     albertel 6615:         my @all_domains = sort(&all_domains());
1.955     raeburn  6616:         foreach my $domain (@all_domains) {
                   6617:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6618:         }
                   6619:         return @all_domains;
                   6620:     } else {
1.800     albertel 6621:         return ('missing domain');
1.275     stredwic 6622:     }
                   6623: }
                   6624: 
                   6625: # --------------------------------------------- GetFileTimestamp
                   6626: # This function utilizes dirlist and returns the date stamp for
                   6627: # when it was last modified.  It will also return an error of -1
                   6628: # if an error occurs
                   6629: 
                   6630: sub GetFileTimestamp {
1.955     raeburn  6631:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6632:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6633:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6634:     my ($fileStat) = 
                   6635:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6636:                                  undef,$getuserdir);
1.275     stredwic 6637:     my @stats = split('&', $fileStat);
                   6638:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6639:         # @stats contains first the filename, then the stat output
                   6640:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6641:     } else {
                   6642:         return -1;
1.253     stredwic 6643:     }
1.26      www      6644: }
                   6645: 
1.712     albertel 6646: sub stat_file {
                   6647:     my ($uri) = @_;
1.787     albertel 6648:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6649: 
1.955     raeburn  6650:     my ($udom,$uname,$file);
1.712     albertel 6651:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6652: 	($udom,$uname,$file) =
1.811     albertel 6653: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6654: 	$file = 'userfiles/'.$file;
                   6655:     }
                   6656:     if ($uri =~ m-^/res/-) {
                   6657: 	($udom,$uname) = 
1.807     albertel 6658: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6659: 	$file = $uri;
                   6660:     }
                   6661: 
                   6662:     if (!$udom || !$uname || !$file) {
                   6663: 	# unable to handle the uri
                   6664: 	return ();
                   6665:     }
1.956     raeburn  6666:     my $getpropath;
                   6667:     if ($file =~ /^userfiles\//) {
                   6668:         $getpropath = 1;
                   6669:     }
1.955     raeburn  6670:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6671:     my @stats = split('&', $result);
1.721     banghart 6672:     
1.712     albertel 6673:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6674: 	shift(@stats); #filename is first
                   6675: 	return @stats;
                   6676:     }
                   6677:     return ();
                   6678: }
                   6679: 
1.26      www      6680: # -------------------------------------------------------- Value of a Condition
                   6681: 
1.713     albertel 6682: # gets the value of a specific preevaluated condition
                   6683: #    stored in the string  $env{user.state.<cid>}
                   6684: # or looks up a condition reference in the bighash and if if hasn't
                   6685: # already been evaluated recurses into docondval to get the value of
                   6686: # the condition, then memoizing it to 
                   6687: #   $env{user.state.<cid>.<condition>}
1.40      www      6688: sub directcondval {
                   6689:     my $number=shift;
1.620     albertel 6690:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6691: 	&Apache::lonuserstate::evalstate();
                   6692:     }
1.713     albertel 6693:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6694: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6695:     } elsif ($number =~ /^_/) {
                   6696: 	my $sub_condition;
                   6697: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6698: 		&GDBM_READER(),0640)) {
                   6699: 	    $sub_condition=$bighash{'conditions'.$number};
                   6700: 	    untie(%bighash);
                   6701: 	}
                   6702: 	my $value = &docondval($sub_condition);
1.949     raeburn  6703: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6704: 	return $value;
                   6705:     }
1.620     albertel 6706:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6707:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6708:     } else {
                   6709:        return 2;
                   6710:     }
                   6711: }
                   6712: 
1.713     albertel 6713: # get the collection of conditions for this resource
1.26      www      6714: sub condval {
                   6715:     my $condidx=shift;
1.54      www      6716:     my $allpathcond='';
1.713     albertel 6717:     foreach my $cond (split(/\|/,$condidx)) {
                   6718: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6719: 	    $allpathcond.=
                   6720: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6721: 	}
1.191     harris41 6722:     }
1.54      www      6723:     $allpathcond=~s/\|$//;
1.713     albertel 6724:     return &docondval($allpathcond);
                   6725: }
                   6726: 
                   6727: #evaluates an expression of conditions
                   6728: sub docondval {
                   6729:     my ($allpathcond) = @_;
                   6730:     my $result=0;
                   6731:     if ($env{'request.course.id'}
                   6732: 	&& defined($allpathcond)) {
                   6733: 	my $operand='|';
                   6734: 	my @stack;
                   6735: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6736: 	    if ($chunk eq '(') {
                   6737: 		push @stack,($operand,$result);
                   6738: 	    } elsif ($chunk eq ')') {
                   6739: 		my $before=pop @stack;
                   6740: 		if (pop @stack eq '&') {
                   6741: 		    $result=$result>$before?$before:$result;
                   6742: 		} else {
                   6743: 		    $result=$result>$before?$result:$before;
                   6744: 		}
                   6745: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6746: 		$operand=$chunk;
                   6747: 	    } else {
                   6748: 		my $new=directcondval($chunk);
                   6749: 		if ($operand eq '&') {
                   6750: 		    $result=$result>$new?$new:$result;
                   6751: 		} else {
                   6752: 		    $result=$result>$new?$result:$new;
                   6753: 		}
                   6754: 	    }
                   6755: 	}
1.26      www      6756:     }
                   6757:     return $result;
1.421     albertel 6758: }
                   6759: 
                   6760: # ---------------------------------------------------- Devalidate courseresdata
                   6761: 
                   6762: sub devalidatecourseresdata {
                   6763:     my ($coursenum,$coursedomain)=@_;
                   6764:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6765:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6766: }
                   6767: 
1.763     www      6768: 
1.200     www      6769: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6770: #
                   6771: #  Parameters:
                   6772: #      $coursenum    - Number of the course.
                   6773: #      $coursedomain - Domain at which the course was created.
                   6774: #  Returns:
                   6775: #     A hash of the course parameters along (I think) with timestamps
                   6776: #     and version info.
1.877     foxr     6777: 
1.624     albertel 6778: sub get_courseresdata {
                   6779:     my ($coursenum,$coursedomain)=@_;
1.200     www      6780:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6781:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6782:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6783:     my %dumpreply;
1.417     albertel 6784:     unless (defined($cached)) {
1.624     albertel 6785: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6786: 	$result=\%dumpreply;
1.251     albertel 6787: 	my ($tmp) = keys(%dumpreply);
                   6788: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6789: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6790: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6791: 	    return $tmp;
1.416     albertel 6792: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6793: 	    $result=undef;
1.599     albertel 6794: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6795: 	}
                   6796:     }
1.624     albertel 6797:     return $result;
                   6798: }
                   6799: 
1.633     albertel 6800: sub devalidateuserresdata {
                   6801:     my ($uname,$udom)=@_;
                   6802:     my $hashid="$udom:$uname";
                   6803:     &devalidate_cache_new('userres',$hashid);
                   6804: }
                   6805: 
1.624     albertel 6806: sub get_userresdata {
                   6807:     my ($uname,$udom)=@_;
                   6808:     #most student don\'t have any data set, check if there is some data
                   6809:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6810: 
                   6811:     my $hashid="$udom:$uname";
                   6812:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6813:     if (!defined($cached)) {
                   6814: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6815: 	$result=\%resourcedata;
                   6816: 	&do_cache_new('userres',$hashid,$result,600);
                   6817:     }
                   6818:     my ($tmp)=keys(%$result);
                   6819:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6820: 	return $result;
                   6821:     }
                   6822:     #error 2 occurs when the .db doesn't exist
                   6823:     if ($tmp!~/error: 2 /) {
1.672     albertel 6824: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6825: 		 " Trying to get resource data for ".
                   6826: 		 $uname." at ".$udom.": ".
                   6827: 		 $tmp."</font>");
                   6828:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6829: 	#&EXT_cache_set($udom,$uname);
                   6830: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6831: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6832:     }
                   6833:     return $tmp;
                   6834: }
1.879     foxr     6835: #----------------------------------------------- resdata - return resource data
                   6836: #  Purpose:
                   6837: #    Return resource data for either users or for a course.
                   6838: #  Parameters:
                   6839: #     $name      - Course/user name.
                   6840: #     $domain    - Name of the domain the user/course is registered on.
                   6841: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6842: #     @which     - Array of names of resources desired.
                   6843: #  Returns:
                   6844: #     The value of the first reasource in @which that is found in the
                   6845: #     resource hash.
                   6846: #  Exceptional Conditions:
                   6847: #     If the $type passed in is not valid (not the string 'course' or 
                   6848: #     'user', an undefined  reference is returned.
                   6849: #     If none of the resources are found, an undef is returned
1.624     albertel 6850: sub resdata {
                   6851:     my ($name,$domain,$type,@which)=@_;
                   6852:     my $result;
                   6853:     if ($type eq 'course') {
                   6854: 	$result=&get_courseresdata($name,$domain);
                   6855:     } elsif ($type eq 'user') {
                   6856: 	$result=&get_userresdata($name,$domain);
                   6857:     }
                   6858:     if (!ref($result)) { return $result; }    
1.251     albertel 6859:     foreach my $item (@which) {
1.927     albertel 6860: 	if (defined($result->{$item->[0]})) {
                   6861: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6862: 	}
1.250     albertel 6863:     }
1.291     albertel 6864:     return undef;
1.200     www      6865: }
                   6866: 
1.379     matthew  6867: #
                   6868: # EXT resource caching routines
                   6869: #
                   6870: 
                   6871: sub clear_EXT_cache_status {
1.383     albertel 6872:     &delenv('cache.EXT.');
1.379     matthew  6873: }
                   6874: 
                   6875: sub EXT_cache_status {
                   6876:     my ($target_domain,$target_user) = @_;
1.383     albertel 6877:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6878:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6879:         # We know already the user has no data
                   6880:         return 1;
                   6881:     } else {
                   6882:         return 0;
                   6883:     }
                   6884: }
                   6885: 
                   6886: sub EXT_cache_set {
                   6887:     my ($target_domain,$target_user) = @_;
1.383     albertel 6888:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6889:     #&appenv({$cachename => time});
1.379     matthew  6890: }
                   6891: 
1.28      www      6892: # --------------------------------------------------------- Value of a Variable
1.58      www      6893: sub EXT {
1.715     albertel 6894: 
1.395     albertel 6895:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6896:     unless ($varname) { return ''; }
1.218     albertel 6897:     #get real user name/domain, courseid and symb
                   6898:     my $courseid;
1.359     albertel 6899:     my $publicuser;
1.427     www      6900:     if ($symbparm) {
                   6901: 	$symbparm=&get_symb_from_alias($symbparm);
                   6902:     }
1.218     albertel 6903:     if (!($uname && $udom)) {
1.790     albertel 6904:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6905:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6906:     } else {
1.620     albertel 6907: 	$courseid=$env{'request.course.id'};
1.218     albertel 6908:     }
1.48      www      6909:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6910:     my $rest;
1.320     albertel 6911:     if (defined($therest[0])) {
1.48      www      6912:        $rest=join('.',@therest);
                   6913:     } else {
                   6914:        $rest='';
                   6915:     }
1.320     albertel 6916: 
1.57      www      6917:     my $qualifierrest=$qualifier;
                   6918:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6919:     my $spacequalifierrest=$space;
                   6920:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6921:     if ($realm eq 'user') {
1.48      www      6922: # --------------------------------------------------------------- user.resource
                   6923: 	if ($space eq 'resource') {
1.651     albertel 6924: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6925: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6926: 		 &&
1.744     albertel 6927: 		 ($symbparm eq &symbread()) ) {	
                   6928: 		# if we are in the middle of processing the resource the
                   6929: 		# get the value we are planning on committing
                   6930:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6931:                     return $Apache::lonhomework::results{$qualifierrest};
                   6932:                 } else {
                   6933:                     return $Apache::lonhomework::history{$qualifierrest};
                   6934:                 }
1.335     albertel 6935: 	    } else {
1.359     albertel 6936: 		my %restored;
1.620     albertel 6937: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6938: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6939: 		} else {
                   6940: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6941: 		}
1.335     albertel 6942: 		return $restored{$qualifierrest};
                   6943: 	    }
1.48      www      6944: # ----------------------------------------------------------------- user.access
                   6945:         } elsif ($space eq 'access') {
1.218     albertel 6946: 	    # FIXME - not supporting calls for a specific user
1.48      www      6947:             return &allowed($qualifier,$rest);
                   6948: # ------------------------------------------ user.preferences, user.environment
                   6949:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6950: 	    if (($uname eq $env{'user.name'}) &&
                   6951: 		($udom eq $env{'user.domain'})) {
                   6952: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6953: 	    } else {
1.359     albertel 6954: 		my %returnhash;
                   6955: 		if (!$publicuser) {
                   6956: 		    %returnhash=&userenvironment($udom,$uname,
                   6957: 						 $qualifierrest);
                   6958: 		}
1.218     albertel 6959: 		return $returnhash{$qualifierrest};
                   6960: 	    }
1.48      www      6961: # ----------------------------------------------------------------- user.course
                   6962:         } elsif ($space eq 'course') {
1.218     albertel 6963: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6964:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6965: # ------------------------------------------------------------------- user.role
                   6966:         } elsif ($space eq 'role') {
1.218     albertel 6967: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6968:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6969:             if ($qualifier eq 'value') {
                   6970: 		return $role;
                   6971:             } elsif ($qualifier eq 'extent') {
                   6972:                 return $where;
                   6973:             }
                   6974: # ----------------------------------------------------------------- user.domain
                   6975:         } elsif ($space eq 'domain') {
1.218     albertel 6976:             return $udom;
1.48      www      6977: # ------------------------------------------------------------------- user.name
                   6978:         } elsif ($space eq 'name') {
1.218     albertel 6979:             return $uname;
1.48      www      6980: # ---------------------------------------------------- Any other user namespace
1.29      www      6981:         } else {
1.359     albertel 6982: 	    my %reply;
                   6983: 	    if (!$publicuser) {
                   6984: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6985: 	    }
                   6986: 	    return $reply{$qualifierrest};
1.48      www      6987:         }
1.236     www      6988:     } elsif ($realm eq 'query') {
                   6989: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6990:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6991: 						[$spacequalifierrest]);
1.620     albertel 6992: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6993:    } elsif ($realm eq 'request') {
1.48      www      6994: # ------------------------------------------------------------- request.browser
                   6995:         if ($space eq 'browser') {
1.430     www      6996: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6997: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6998: 		    return 1;
                   6999: 		} else {
                   7000: 		    return 0;
                   7001: 		}
                   7002: 	    } else {
1.620     albertel 7003: 		return $env{'browser.'.$qualifier};
1.430     www      7004: 	    }
1.57      www      7005: # ------------------------------------------------------------ request.filename
                   7006:         } else {
1.620     albertel 7007:             return $env{'request.'.$spacequalifierrest};
1.29      www      7008:         }
1.28      www      7009:     } elsif ($realm eq 'course') {
1.48      www      7010: # ---------------------------------------------------------- course.description
1.620     albertel 7011:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7012:     } elsif ($realm eq 'resource') {
1.165     www      7013: 
1.620     albertel 7014: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7015: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7016: 	}
1.693     albertel 7017: 
                   7018: 	if ($space eq 'title') {
                   7019: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7020: 	    return &gettitle($symbparm);
                   7021: 	}
                   7022: 	
                   7023: 	if ($space eq 'map') {
                   7024: 	    my ($map) = &decode_symb($symbparm);
                   7025: 	    return &symbread($map);
                   7026: 	}
1.905     albertel 7027: 	if ($space eq 'filename') {
                   7028: 	    if ($symbparm) {
                   7029: 		return &clutter((&decode_symb($symbparm))[2]);
                   7030: 	    }
                   7031: 	    return &hreflocation('',$env{'request.filename'});
                   7032: 	}
1.693     albertel 7033: 
                   7034: 	my ($section, $group, @groups);
1.593     albertel 7035: 	my ($courselevelm,$courselevel);
1.539     albertel 7036: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7037: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7038: 
1.218     albertel 7039: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7040: 
1.60      www      7041: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7042: 	    my $symbp=$symbparm;
1.735     albertel 7043: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7044: 
                   7045: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7046: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7047: 
1.620     albertel 7048: 	    if (($env{'user.name'} eq $uname) &&
                   7049: 		($env{'user.domain'} eq $udom)) {
                   7050: 		$section=$env{'request.course.sec'};
1.733     raeburn  7051:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7052:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7053: 	    } else {
1.539     albertel 7054: 		if (! defined($usection)) {
1.551     albertel 7055: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7056: 		} else {
                   7057: 		    $section = $usection;
                   7058: 		}
1.733     raeburn  7059:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7060: 	    }
                   7061: 
                   7062: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7063: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7064: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7065: 
1.593     albertel 7066: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7067: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7068: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7069: 
1.60      www      7070: # ----------------------------------------------------------- first, check user
1.624     albertel 7071: 
                   7072: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7073: 				       ([$courselevelr,'resource'],
                   7074: 					[$courselevelm,'map'     ],
                   7075: 					[$courselevel, 'course'  ]));
1.931     albertel 7076: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7077: 
1.594     albertel 7078: # ------------------------------------------------ second, check some of course
1.684     raeburn  7079:             my $coursereply;
1.691     raeburn  7080:             if (@groups > 0) {
                   7081:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7082:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7083:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7084:             }
1.96      www      7085: 
1.684     raeburn  7086: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7087: 				  $env{'course.'.$courseid.'.domain'},
                   7088: 				  'course',
                   7089: 				  ([$seclevelr,   'resource'],
                   7090: 				   [$seclevelm,   'map'     ],
                   7091: 				   [$seclevel,    'course'  ],
                   7092: 				   [$courselevelr,'resource']));
                   7093: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7094: 
1.60      www      7095: # ------------------------------------------------------ third, check map parms
1.218     albertel 7096: 	    my %parmhash=();
                   7097: 	    my $thisparm='';
                   7098: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7099: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7100: 		    &GDBM_READER(),0640)) {
1.218     albertel 7101: 		$thisparm=$parmhash{$symbparm};
                   7102: 		untie(%parmhash);
                   7103: 	    }
1.927     albertel 7104: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7105: 	}
1.594     albertel 7106: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7107: 
1.218     albertel 7108: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7109: 	my $filename;
                   7110: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7111: 	if ($symbparm) {
1.409     www      7112: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7113: 	} else {
1.620     albertel 7114: 	    $filename=$env{'request.filename'};
1.282     albertel 7115: 	}
                   7116: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7117: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7118: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7119: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7120: 
1.927     albertel 7121: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7122: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7123: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7124: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7125: 				     $env{'course.'.$courseid.'.domain'},
                   7126: 				     'course',
1.927     albertel 7127: 				     ([$courselevelm,'map'   ],
                   7128: 				      [$courselevel, 'course']));
                   7129: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7130: 	}
1.145     www      7131: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7132: 	unless ($space eq '0') {
1.336     albertel 7133: 	    my @parts=split(/_/,$space);
                   7134: 	    my $id=pop(@parts);
                   7135: 	    my $part=join('_',@parts);
                   7136: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7137: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7138: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7139: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7140: 	}
1.395     albertel 7141: 	if ($recurse) { return undef; }
                   7142: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7143: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7144: # ---------------------------------------------------- Any other user namespace
                   7145:     } elsif ($realm eq 'environment') {
                   7146: # ----------------------------------------------------------------- environment
1.620     albertel 7147: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7148: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7149: 	} else {
1.770     albertel 7150: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7151: 		return '';
                   7152: 	    }
1.219     albertel 7153: 	    my %returnhash=&userenvironment($udom,$uname,
                   7154: 					    $spacequalifierrest);
                   7155: 	    return $returnhash{$spacequalifierrest};
                   7156: 	}
1.28      www      7157:     } elsif ($realm eq 'system') {
1.48      www      7158: # ----------------------------------------------------------------- system.time
                   7159: 	if ($space eq 'time') {
                   7160: 	    return time;
                   7161:         }
1.696     albertel 7162:     } elsif ($realm eq 'server') {
                   7163: # ----------------------------------------------------------------- system.time
                   7164: 	if ($space eq 'name') {
                   7165: 	    return $ENV{'SERVER_NAME'};
                   7166:         }
1.28      www      7167:     }
1.48      www      7168:     return '';
1.61      www      7169: }
                   7170: 
1.927     albertel 7171: sub get_reply {
                   7172:     my ($reply_value) = @_;
1.940     raeburn  7173:     if (ref($reply_value) eq 'ARRAY') {
                   7174:         if (wantarray) {
                   7175: 	    return @$reply_value;
                   7176:         }
                   7177:         return $reply_value->[0];
                   7178:     } else {
                   7179:         return $reply_value;
1.927     albertel 7180:     }
                   7181: }
                   7182: 
1.691     raeburn  7183: sub check_group_parms {
                   7184:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7185:     my @groupitems = ();
                   7186:     my $resultitem;
1.927     albertel 7187:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7188:     foreach my $group (@{$groups}) {
                   7189:         foreach my $level (@levels) {
1.927     albertel 7190:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7191:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7192:         }
                   7193:     }
                   7194:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7195:                             $env{'course.'.$courseid.'.domain'},
                   7196:                                      'course',@groupitems);
                   7197:     return $coursereply;
                   7198: }
                   7199: 
                   7200: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7201:     my ($courseid,@groups) = @_;
                   7202:     @groups = sort(@groups);
1.691     raeburn  7203:     return @groups;
                   7204: }
                   7205: 
1.395     albertel 7206: sub packages_tab_default {
                   7207:     my ($uri,$varname)=@_;
                   7208:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7209: 
                   7210:     my (@extension,@specifics,$do_default);
                   7211:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7212: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7213: 	if ($pack_type eq 'default') {
                   7214: 	    $do_default=1;
                   7215: 	} elsif ($pack_type eq 'extension') {
                   7216: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7217: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7218: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7219: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7220: 	}
                   7221:     }
                   7222:     # first look for a package that matches the requested part id
                   7223:     foreach my $package (@specifics) {
                   7224: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7225: 	next if ($pack_part ne $part);
                   7226: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7227: 	    return $packagetab{"$pack_type&$name&default"};
                   7228: 	}
                   7229:     }
                   7230:     # look for any possible matching non extension_ package
                   7231:     foreach my $package (@specifics) {
                   7232: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7233: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7234: 	    return $packagetab{"$pack_type&$name&default"};
                   7235: 	}
1.585     albertel 7236: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7237: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7238: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7239: 	}
                   7240:     }
1.738     albertel 7241:     # look for any posible extension_ match
                   7242:     foreach my $package (@extension) {
                   7243: 	my ($package,$pack_type)=@{$package};
                   7244: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7245: 	    return $packagetab{"$pack_type&$name&default"};
                   7246: 	}
                   7247: 	if (defined($packagetab{$package."&$name&default"})) {
                   7248: 	    return $packagetab{$package."&$name&default"};
                   7249: 	}
                   7250:     }
                   7251:     # look for a global default setting
                   7252:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7253: 	return $packagetab{"default&$name&default"};
                   7254:     }
1.395     albertel 7255:     return undef;
                   7256: }
                   7257: 
1.334     albertel 7258: sub add_prefix_and_part {
                   7259:     my ($prefix,$part)=@_;
                   7260:     my $keyroot;
                   7261:     if (defined($prefix) && $prefix !~ /^__/) {
                   7262: 	# prefix that has a part already
                   7263: 	$keyroot=$prefix;
                   7264:     } elsif (defined($prefix)) {
                   7265: 	# prefix that is missing a part
                   7266: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7267:     } else {
                   7268: 	# no prefix at all
                   7269: 	if (defined($part)) { $keyroot='_'.$part; }
                   7270:     }
                   7271:     return $keyroot;
                   7272: }
                   7273: 
1.71      www      7274: # ---------------------------------------------------------------- Get metadata
                   7275: 
1.599     albertel 7276: my %metaentry;
1.71      www      7277: sub metadata {
1.176     www      7278:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7279:     $uri=&declutter($uri);
1.288     albertel 7280:     # if it is a non metadata possible uri return quickly
1.529     albertel 7281:     if (($uri eq '') || 
                   7282: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7283: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7284:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7285: 	return undef;
                   7286:     }
                   7287:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7288: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7289: 	return undef;
1.288     albertel 7290:     }
1.73      www      7291:     my $filename=$uri;
                   7292:     $uri=~s/\.meta$//;
1.172     www      7293: #
                   7294: # Is the metadata already cached?
1.177     www      7295: # Look at timestamp of caching
1.172     www      7296: # Everything is cached by the main uri, libraries are never directly cached
                   7297: #
1.428     albertel 7298:     if (!defined($liburi)) {
1.599     albertel 7299: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7300: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7301:     }
                   7302:     {
1.172     www      7303: #
                   7304: # Is this a recursive call for a library?
                   7305: #
1.599     albertel 7306: #	if (! exists($metacache{$uri})) {
                   7307: #	    $metacache{$uri}={};
                   7308: #	}
1.924     albertel 7309: 	my $cachetime = 60*60;
1.171     www      7310:         if ($liburi) {
                   7311: 	    $liburi=&declutter($liburi);
                   7312:             $filename=$liburi;
1.401     bowersj2 7313:         } else {
1.599     albertel 7314: 	    &devalidate_cache_new('meta',$uri);
                   7315: 	    undef(%metaentry);
1.401     bowersj2 7316: 	}
1.140     www      7317:         my %metathesekeys=();
1.73      www      7318:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7319: 	my $metastring;
1.924     albertel 7320: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7321: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7322: 	    $metastring = 
1.929     albertel 7323: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7324: 					  ('grade_target' => 'meta'));
                   7325: 	    $cachetime = 1; # only want this cached in the child not long term
                   7326: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7327: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7328: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7329: 	    $metastring=&getfile($file);
1.489     albertel 7330: 	}
1.208     albertel 7331:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7332:         my $token;
1.140     www      7333:         undef %metathesekeys;
1.71      www      7334:         while ($token=$parser->get_token) {
1.339     albertel 7335: 	    if ($token->[0] eq 'S') {
                   7336: 		if (defined($token->[2]->{'package'})) {
1.172     www      7337: #
                   7338: # This is a package - get package info
                   7339: #
1.339     albertel 7340: 		    my $package=$token->[2]->{'package'};
                   7341: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7342: 		    if (defined($token->[2]->{'id'})) { 
                   7343: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7344: 		    }
1.599     albertel 7345: 		    if ($metaentry{':packages'}) {
                   7346: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7347: 		    } else {
1.599     albertel 7348: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7349: 		    }
1.736     albertel 7350: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7351: 			my $part=$keyroot;
                   7352: 			$part=~s/^\_//;
1.736     albertel 7353: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7354: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7355: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7356: 			    # ignore package.tab specified default values
                   7357:                             # here &package_tab_default() will fetch those
                   7358: 			    if ($subp eq 'default') { next; }
1.736     albertel 7359: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7360: 			    my $unikey;
                   7361: 			    if ($pack =~ /_0$/) {
                   7362: 				$unikey='parameter_0_'.$name;
                   7363: 				$part=0;
                   7364: 			    } else {
                   7365: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7366: 			    }
1.339     albertel 7367: 			    if ($subp eq 'display') {
                   7368: 				$value.=' [Part: '.$part.']';
                   7369: 			    }
1.599     albertel 7370: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7371: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7372: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7373: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7374: 			    }
1.599     albertel 7375: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7376: 				$metaentry{':'.$unikey}=
                   7377: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7378: 			    }
1.339     albertel 7379: 			}
                   7380: 		    }
                   7381: 		} else {
1.172     www      7382: #
                   7383: # This is not a package - some other kind of start tag
1.339     albertel 7384: #
                   7385: 		    my $entry=$token->[1];
                   7386: 		    my $unikey;
                   7387: 		    if ($entry eq 'import') {
                   7388: 			$unikey='';
                   7389: 		    } else {
                   7390: 			$unikey=$entry;
                   7391: 		    }
                   7392: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7393: 
                   7394: 		    if (defined($token->[2]->{'id'})) { 
                   7395: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7396: 		    }
1.175     www      7397: 
1.339     albertel 7398: 		    if ($entry eq 'import') {
1.175     www      7399: #
                   7400: # Importing a library here
1.339     albertel 7401: #
                   7402: 			if ($depthcount<20) {
                   7403: 			    my $location=$parser->get_text('/import');
                   7404: 			    my $dir=$filename;
                   7405: 			    $dir=~s|[^/]*$||;
                   7406: 			    $location=&filelocation($dir,$location);
1.736     albertel 7407: 			    my $metadata = 
                   7408: 				&metadata($uri,'keys', $location,$unikey,
                   7409: 					  $depthcount+1);
                   7410: 			    foreach my $meta (split(',',$metadata)) {
                   7411: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7412: 				$metathesekeys{$meta}=1;
1.339     albertel 7413: 			    }
                   7414: 			}
                   7415: 		    } else { 
                   7416: 			
                   7417: 			if (defined($token->[2]->{'name'})) { 
                   7418: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7419: 			}
                   7420: 			$metathesekeys{$unikey}=1;
1.736     albertel 7421: 			foreach my $param (@{$token->[3]}) {
                   7422: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7423: 				$token->[2]->{$param};
1.339     albertel 7424: 			}
                   7425: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7426: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7427: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7428: 		 # only ws inside the tag, and not in default, so use default
                   7429: 		 # as value
1.599     albertel 7430: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7431: 			} elsif ( $internaltext =~ /\S/ ) {
                   7432: 		  # something interesting inside the tag
                   7433: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7434: 			} else {
1.908     albertel 7435: 		  # no interesting values, don't set a default
1.339     albertel 7436: 			}
1.172     www      7437: # end of not-a-package not-a-library import
1.339     albertel 7438: 		    }
1.172     www      7439: # end of not-a-package start tag
1.339     albertel 7440: 		}
1.172     www      7441: # the next is the end of "start tag"
1.339     albertel 7442: 	    }
                   7443: 	}
1.483     albertel 7444: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7445: 	$extension = lc($extension);
                   7446: 	if ($extension eq 'htm') { $extension='html'; }
                   7447: 
1.737     albertel 7448: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7449: 	    #no specific packages #how's our extension
                   7450: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7451: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7452: 					 \%metathesekeys);
                   7453: 	}
1.883     albertel 7454: 
                   7455: 	if (!exists($metaentry{':packages'})
                   7456: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7457: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7458: 		#no specific packages well let's get default then
                   7459: 		if ($key!~/^default&/) { next; }
1.488     albertel 7460: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7461: 					     \%metathesekeys);
                   7462: 	    }
                   7463: 	}
1.338     www      7464: # are there custom rights to evaluate
1.599     albertel 7465: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7466: 
1.338     www      7467:     #
                   7468:     # Importing a rights file here
1.339     albertel 7469:     #
                   7470: 	    unless ($depthcount) {
1.599     albertel 7471: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7472: 		my $dir=$filename;
                   7473: 		$dir=~s|[^/]*$||;
                   7474: 		$location=&filelocation($dir,$location);
1.736     albertel 7475: 		my $rights_metadata =
                   7476: 		    &metadata($uri,'keys',$location,'_rights',
                   7477: 			      $depthcount+1);
                   7478: 		foreach my $rights (split(',',$rights_metadata)) {
                   7479: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7480: 		    $metathesekeys{$rights}=1;
1.339     albertel 7481: 		}
                   7482: 	    }
                   7483: 	}
1.737     albertel 7484: 	# uniqifiy package listing
                   7485: 	my %seen;
                   7486: 	my @uniq_packages =
                   7487: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7488: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7489: 
                   7490: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7491: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7492: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7493: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7494: # this is the end of "was not already recently cached
1.71      www      7495:     }
1.599     albertel 7496:     return $metaentry{':'.$what};
1.261     albertel 7497: }
                   7498: 
1.488     albertel 7499: sub metadata_create_package_def {
1.483     albertel 7500:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7501:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7502:     if ($subp eq 'default') { next; }
                   7503:     
1.599     albertel 7504:     if (defined($metaentry{':packages'})) {
                   7505: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7506:     } else {
1.599     albertel 7507: 	$metaentry{':packages'}=$package;
1.483     albertel 7508:     }
                   7509:     my $value=$packagetab{$key};
                   7510:     my $unikey;
                   7511:     $unikey='parameter_0_'.$name;
1.599     albertel 7512:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7513:     $$metathesekeys{$unikey}=1;
1.599     albertel 7514:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7515: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7516:     }
1.599     albertel 7517:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7518: 	$metaentry{':'.$unikey}=
                   7519: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7520:     }
                   7521: }
                   7522: 
1.261     albertel 7523: sub metadata_generate_part0 {
                   7524:     my ($metadata,$metacache,$uri) = @_;
                   7525:     my %allnames;
1.737     albertel 7526:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7527: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7528: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7529: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7530: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7531: 	    $allnames{$name}=$part;
                   7532: 	  }
                   7533: 	}
                   7534:     }
                   7535:     foreach my $name (keys(%allnames)) {
                   7536:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7537:       my $key=":parameter_0_$name";
1.261     albertel 7538:       $$metacache{"$key.part"}='0';
                   7539:       $$metacache{"$key.name"}=$name;
1.428     albertel 7540:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7541: 					   $allnames{$name}.'_'.$name.
                   7542: 					   '.type'};
1.428     albertel 7543:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7544: 			     '.display'};
1.644     www      7545:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7546:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7547:       $$metacache{"$key.display"}=$olddis;
                   7548:     }
1.71      www      7549: }
                   7550: 
1.764     albertel 7551: # ------------------------------------------------------ Devalidate title cache
                   7552: 
                   7553: sub devalidate_title_cache {
                   7554:     my ($url)=@_;
                   7555:     if (!$env{'request.course.id'}) { return; }
                   7556:     my $symb=&symbread($url);
                   7557:     if (!$symb) { return; }
                   7558:     my $key=$env{'request.course.id'}."\0".$symb;
                   7559:     &devalidate_cache_new('title',$key);
                   7560: }
                   7561: 
1.301     www      7562: # ------------------------------------------------- Get the title of a resource
                   7563: 
                   7564: sub gettitle {
                   7565:     my $urlsymb=shift;
                   7566:     my $symb=&symbread($urlsymb);
1.534     albertel 7567:     if ($symb) {
1.620     albertel 7568: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7569: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7570: 	if (defined($cached)) { 
                   7571: 	    return $result;
                   7572: 	}
1.534     albertel 7573: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7574: 	my $title='';
1.907     albertel 7575: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7576: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7577: 	} else {
                   7578: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7579: 		    &GDBM_READER(),0640)) {
                   7580: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7581: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7582: 		untie(%bighash);
                   7583: 	    }
1.534     albertel 7584: 	}
                   7585: 	$title=~s/\&colon\;/\:/gs;
                   7586: 	if ($title) {
1.599     albertel 7587: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7588: 	}
                   7589: 	$urlsymb=$url;
                   7590:     }
                   7591:     my $title=&metadata($urlsymb,'title');
                   7592:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7593:     return $title;
1.301     www      7594: }
1.613     albertel 7595: 
1.614     albertel 7596: sub get_slot {
                   7597:     my ($which,$cnum,$cdom)=@_;
                   7598:     if (!$cnum || !$cdom) {
1.790     albertel 7599: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7600: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7601: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7602:     }
1.703     albertel 7603:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7604:     my %slotinfo;
                   7605:     if (exists($remembered{$key})) {
                   7606: 	$slotinfo{$which} = $remembered{$key};
                   7607:     } else {
                   7608: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7609: 	&Apache::lonhomework::showhash(%slotinfo);
                   7610: 	my ($tmp)=keys(%slotinfo);
                   7611: 	if ($tmp=~/^error:/) { return (); }
                   7612: 	$remembered{$key} = $slotinfo{$which};
                   7613:     }
1.616     albertel 7614:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7615: 	return %{$slotinfo{$which}};
                   7616:     }
                   7617:     return $slotinfo{$which};
1.614     albertel 7618: }
1.31      www      7619: # ------------------------------------------------- Update symbolic store links
                   7620: 
                   7621: sub symblist {
                   7622:     my ($mapname,%newhash)=@_;
1.438     www      7623:     $mapname=&deversion(&declutter($mapname));
1.31      www      7624:     my %hash;
1.620     albertel 7625:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7626:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7627:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7628: 	    foreach my $url (keys %newhash) {
                   7629: 		next if ($url eq 'last_known'
                   7630: 			 && $env{'form.no_update_last_known'});
                   7631: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7632: 						    $newhash{$url}->[1],
                   7633: 						    $newhash{$url}->[0]);
1.191     harris41 7634:             }
1.31      www      7635:             if (untie(%hash)) {
                   7636: 		return 'ok';
                   7637:             }
                   7638:         }
                   7639:     }
                   7640:     return 'error';
1.212     www      7641: }
                   7642: 
                   7643: # --------------------------------------------------------------- Verify a symb
                   7644: 
                   7645: sub symbverify {
1.510     www      7646:     my ($symb,$thisurl)=@_;
                   7647:     my $thisfn=$thisurl;
1.439     www      7648:     $thisfn=&declutter($thisfn);
1.215     www      7649: # direct jump to resource in page or to a sequence - will construct own symbs
                   7650:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7651: # check URL part
1.409     www      7652:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7653: 
1.431     www      7654:     unless ($url eq $thisfn) { return 0; }
1.213     www      7655: 
1.216     www      7656:     $symb=&symbclean($symb);
1.510     www      7657:     $thisurl=&deversion($thisurl);
1.439     www      7658:     $thisfn=&deversion($thisfn);
1.213     www      7659: 
                   7660:     my %bighash;
                   7661:     my $okay=0;
1.431     www      7662: 
1.620     albertel 7663:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7664:                             &GDBM_READER(),0640)) {
1.510     www      7665:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7666:         unless ($ids) { 
1.510     www      7667:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7668:         }
                   7669:         if ($ids) {
                   7670: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7671: 	    foreach my $id (split(/\,/,$ids)) {
                   7672: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7673:                if (
                   7674:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7675:    eq $symb) { 
1.620     albertel 7676: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7677: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7678: 		       $okay=1; 
                   7679: 		   }
                   7680: 	       }
1.216     www      7681: 	   }
                   7682:         }
1.213     www      7683: 	untie(%bighash);
                   7684:     }
                   7685:     return $okay;
1.31      www      7686: }
                   7687: 
1.210     www      7688: # --------------------------------------------------------------- Clean-up symb
                   7689: 
                   7690: sub symbclean {
                   7691:     my $symb=shift;
1.568     albertel 7692:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7693: # remove version from map
                   7694:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7695: 
1.210     www      7696: # remove version from URL
                   7697:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7698: 
1.507     www      7699: # remove wrapper
                   7700: 
1.510     www      7701:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7702:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7703:     return $symb;
1.409     www      7704: }
                   7705: 
                   7706: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7707: 
                   7708: sub encode_symb {
                   7709:     my ($map,$resid,$url)=@_;
                   7710:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7711: }
1.409     www      7712: 
                   7713: sub decode_symb {
1.568     albertel 7714:     my $symb=shift;
                   7715:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7716:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7717:     return (&fixversion($map),$resid,&fixversion($url));
                   7718: }
                   7719: 
                   7720: sub fixversion {
                   7721:     my $fn=shift;
1.609     banghart 7722:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7723:     my %bighash;
                   7724:     my $uri=&clutter($fn);
1.620     albertel 7725:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7726: # is this cached?
1.599     albertel 7727:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7728:     if (defined($cached)) { return $result; }
                   7729: # unfortunately not cached, or expired
1.620     albertel 7730:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7731: 	    &GDBM_READER(),0640)) {
                   7732:  	if ($bighash{'version_'.$uri}) {
                   7733:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7734:  	    unless (($version eq 'mostrecent') || 
                   7735: 		    ($version==&getversion($uri))) {
1.440     www      7736:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7737:  	    }
                   7738:  	}
                   7739:  	untie %bighash;
1.413     www      7740:     }
1.599     albertel 7741:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7742: }
                   7743: 
                   7744: sub deversion {
                   7745:     my $url=shift;
                   7746:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7747:     return $url;
1.210     www      7748: }
                   7749: 
1.31      www      7750: # ------------------------------------------------------ Return symb list entry
                   7751: 
                   7752: sub symbread {
1.249     www      7753:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7754:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7755:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7756: # no filename provided? try from environment
1.44      www      7757:     unless ($thisfn) {
1.620     albertel 7758:         if ($env{'request.symb'}) {
                   7759: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7760: 	}
1.620     albertel 7761: 	$thisfn=$env{'request.filename'};
1.44      www      7762:     }
1.569     albertel 7763:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7764: # is that filename actually a symb? Verify, clean, and return
                   7765:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7766: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7767: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7768: 	}
1.242     www      7769:     }
1.44      www      7770:     $thisfn=declutter($thisfn);
1.31      www      7771:     my %hash;
1.37      www      7772:     my %bighash;
                   7773:     my $syval='';
1.620     albertel 7774:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7775:         my $targetfn = $thisfn;
1.609     banghart 7776:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7777:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7778:         }
1.687     albertel 7779: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7780: 	    $targetfn=$1;
                   7781: 	}
1.620     albertel 7782:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7783:                       &GDBM_READER(),0640)) {
1.481     raeburn  7784: 	    $syval=$hash{$targetfn};
1.37      www      7785:             untie(%hash);
                   7786:         }
                   7787: # ---------------------------------------------------------- There was an entry
                   7788:         if ($syval) {
1.601     albertel 7789: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7790: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7791: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7792: 		    #return $env{$cache_str}='';
1.601     albertel 7793: 		#}    
                   7794: 		#$syval.=$1;
                   7795: 	    #}
1.37      www      7796:         } else {
                   7797: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7798:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7799:                             &GDBM_READER(),0640)) {
1.37      www      7800: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7801:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7802:               unless ($ids) { 
                   7803:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7804:               }
                   7805:               unless ($ids) {
                   7806: # alias?
                   7807: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7808:               }
1.37      www      7809:               if ($ids) {
                   7810: # ------------------------------------------------------------------- Has ID(s)
                   7811:                  my @possibilities=split(/\,/,$ids);
1.39      www      7812:                  if ($#possibilities==0) {
                   7813: # ----------------------------------------------- There is only one possibility
1.37      www      7814: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7815: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7816: 						    $resid,$thisfn);
1.249     www      7817:                  } elsif (!$donotrecurse) {
1.39      www      7818: # ------------------------------------------ There is more than one possibility
                   7819:                      my $realpossible=0;
1.800     albertel 7820:                      foreach my $id (@possibilities) {
                   7821: 			 my $file=$bighash{'src_'.$id};
1.39      www      7822:                          if (&allowed('bre',$file)) {
1.800     albertel 7823:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7824:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7825: 				$realpossible++;
1.626     albertel 7826:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7827: 						    $resid,$thisfn);
1.39      www      7828:                             }
                   7829: 			 }
1.191     harris41 7830:                      }
1.39      www      7831: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7832:                  } else {
                   7833:                      $syval='';
1.37      www      7834:                  }
                   7835: 	      }
                   7836:               untie(%bighash)
1.481     raeburn  7837:            }
1.31      www      7838:         }
1.62      www      7839:         if ($syval) {
1.620     albertel 7840: 	    return $env{$cache_str}=$syval;
1.62      www      7841:         }
1.31      www      7842:     }
1.949     raeburn  7843:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7844:     return $env{$cache_str}='';
1.31      www      7845: }
                   7846: 
                   7847: # ---------------------------------------------------------- Return random seed
                   7848: 
1.32      www      7849: sub numval {
                   7850:     my $txt=shift;
                   7851:     $txt=~tr/A-J/0-9/;
                   7852:     $txt=~tr/a-j/0-9/;
                   7853:     $txt=~tr/K-T/0-9/;
                   7854:     $txt=~tr/k-t/0-9/;
                   7855:     $txt=~tr/U-Z/0-5/;
                   7856:     $txt=~tr/u-z/0-5/;
                   7857:     $txt=~s/\D//g;
1.564     albertel 7858:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7859:     return int($txt);
1.368     albertel 7860: }
                   7861: 
1.484     albertel 7862: sub numval2 {
                   7863:     my $txt=shift;
                   7864:     $txt=~tr/A-J/0-9/;
                   7865:     $txt=~tr/a-j/0-9/;
                   7866:     $txt=~tr/K-T/0-9/;
                   7867:     $txt=~tr/k-t/0-9/;
                   7868:     $txt=~tr/U-Z/0-5/;
                   7869:     $txt=~tr/u-z/0-5/;
                   7870:     $txt=~s/\D//g;
                   7871:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7872:     my $total;
                   7873:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7874:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7875:     return int($total);
                   7876: }
                   7877: 
1.575     albertel 7878: sub numval3 {
                   7879:     use integer;
                   7880:     my $txt=shift;
                   7881:     $txt=~tr/A-J/0-9/;
                   7882:     $txt=~tr/a-j/0-9/;
                   7883:     $txt=~tr/K-T/0-9/;
                   7884:     $txt=~tr/k-t/0-9/;
                   7885:     $txt=~tr/U-Z/0-5/;
                   7886:     $txt=~tr/u-z/0-5/;
                   7887:     $txt=~s/\D//g;
                   7888:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7889:     my $total;
                   7890:     foreach my $val (@txts) { $total+=$val; }
                   7891:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7892:     return $total;
                   7893: }
                   7894: 
1.675     albertel 7895: sub digest {
                   7896:     my ($data)=@_;
                   7897:     my $digest=&Digest::MD5::md5($data);
                   7898:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7899:     my ($e,$f);
                   7900:     {
                   7901:         use integer;
                   7902:         $e=($a+$b);
                   7903:         $f=($c+$d);
                   7904:         if ($_64bit) {
                   7905:             $e=(($e<<32)>>32);
                   7906:             $f=(($f<<32)>>32);
                   7907:         }
                   7908:     }
                   7909:     if (wantarray) {
                   7910: 	return ($e,$f);
                   7911:     } else {
                   7912: 	my $g;
                   7913: 	{
                   7914: 	    use integer;
                   7915: 	    $g=($e+$f);
                   7916: 	    if ($_64bit) {
                   7917: 		$g=(($g<<32)>>32);
                   7918: 	    }
                   7919: 	}
                   7920: 	return $g;
                   7921:     }
                   7922: }
                   7923: 
1.368     albertel 7924: sub latest_rnd_algorithm_id {
1.675     albertel 7925:     return '64bit5';
1.366     albertel 7926: }
1.32      www      7927: 
1.503     albertel 7928: sub get_rand_alg {
                   7929:     my ($courseid)=@_;
1.790     albertel 7930:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7931:     if ($courseid) {
1.620     albertel 7932: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7933:     }
                   7934:     return &latest_rnd_algorithm_id();
                   7935: }
                   7936: 
1.562     albertel 7937: sub validCODE {
                   7938:     my ($CODE)=@_;
                   7939:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7940:     return 0;
                   7941: }
                   7942: 
1.491     albertel 7943: sub getCODE {
1.620     albertel 7944:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7945:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7946: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7947: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7948: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7949:     }
                   7950:     return undef;
                   7951: }
                   7952: 
1.31      www      7953: sub rndseed {
1.155     albertel 7954:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7955:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7956:     if (!defined($symb)) {
1.366     albertel 7957: 	unless ($symb=$wsymb) { return time; }
                   7958:     }
                   7959:     if (!$courseid) { $courseid=$wcourseid; }
                   7960:     if (!$domain) { $domain=$wdomain; }
                   7961:     if (!$username) { $username=$wusername }
1.503     albertel 7962:     my $which=&get_rand_alg();
1.803     albertel 7963: 
1.491     albertel 7964:     if (defined(&getCODE())) {
1.675     albertel 7965: 	if ($which eq '64bit5') {
                   7966: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7967: 	} elsif ($which eq '64bit4') {
1.575     albertel 7968: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7969: 	} else {
                   7970: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7971: 	}
1.675     albertel 7972:     } elsif ($which eq '64bit5') {
                   7973: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7974:     } elsif ($which eq '64bit4') {
                   7975: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7976:     } elsif ($which eq '64bit3') {
                   7977: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7978:     } elsif ($which eq '64bit2') {
                   7979: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7980:     } elsif ($which eq '64bit') {
                   7981: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7982:     }
                   7983:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7984: }
                   7985: 
                   7986: sub rndseed_32bit {
                   7987:     my ($symb,$courseid,$domain,$username)=@_;
                   7988:     {
                   7989: 	use integer;
                   7990: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7991: 	my $symbseed=numval($symb) << 22;
                   7992: 	my $namechck=unpack("%32C*",$username) << 17;
                   7993: 	my $nameseed=numval($username) << 12;
                   7994: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7995: 	my $courseseed=unpack("%32C*",$courseid);
                   7996: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7997: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7998: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7999: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8000: 	return $num;
                   8001:     }
                   8002: }
                   8003: 
                   8004: sub rndseed_64bit {
                   8005:     my ($symb,$courseid,$domain,$username)=@_;
                   8006:     {
                   8007: 	use integer;
                   8008: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8009: 	my $symbseed=numval($symb) << 10;
                   8010: 	my $namechck=unpack("%32S*",$username);
                   8011: 	
                   8012: 	my $nameseed=numval($username) << 21;
                   8013: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8014: 	my $courseseed=unpack("%32S*",$courseid);
                   8015: 	
                   8016: 	my $num1=$symbchck+$symbseed+$namechck;
                   8017: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8018: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8019: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8020: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8021: 	return "$num1,$num2";
1.155     albertel 8022:     }
1.366     albertel 8023: }
                   8024: 
1.443     albertel 8025: sub rndseed_64bit2 {
                   8026:     my ($symb,$courseid,$domain,$username)=@_;
                   8027:     {
                   8028: 	use integer;
                   8029: 	# strings need to be an even # of cahracters long, it it is odd the
                   8030:         # last characters gets thrown away
                   8031: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8032: 	my $symbseed=numval($symb) << 10;
                   8033: 	my $namechck=unpack("%32S*",$username.' ');
                   8034: 	
                   8035: 	my $nameseed=numval($username) << 21;
1.501     albertel 8036: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8037: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8038: 	
                   8039: 	my $num1=$symbchck+$symbseed+$namechck;
                   8040: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8041: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8042: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8043: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8044: 	return "$num1,$num2";
                   8045:     }
                   8046: }
                   8047: 
                   8048: sub rndseed_64bit3 {
                   8049:     my ($symb,$courseid,$domain,$username)=@_;
                   8050:     {
                   8051: 	use integer;
                   8052: 	# strings need to be an even # of cahracters long, it it is odd the
                   8053:         # last characters gets thrown away
                   8054: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8055: 	my $symbseed=numval2($symb) << 10;
                   8056: 	my $namechck=unpack("%32S*",$username.' ');
                   8057: 	
                   8058: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8059: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8060: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8061: 	
                   8062: 	my $num1=$symbchck+$symbseed+$namechck;
                   8063: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8065: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8066: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8067: 	
1.503     albertel 8068: 	return "$num1:$num2";
1.443     albertel 8069:     }
                   8070: }
                   8071: 
1.575     albertel 8072: sub rndseed_64bit4 {
                   8073:     my ($symb,$courseid,$domain,$username)=@_;
                   8074:     {
                   8075: 	use integer;
                   8076: 	# strings need to be an even # of cahracters long, it it is odd the
                   8077:         # last characters gets thrown away
                   8078: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8079: 	my $symbseed=numval3($symb) << 10;
                   8080: 	my $namechck=unpack("%32S*",$username.' ');
                   8081: 	
                   8082: 	my $nameseed=numval3($username) << 21;
                   8083: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8084: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8085: 	
                   8086: 	my $num1=$symbchck+$symbseed+$namechck;
                   8087: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8088: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8089: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8090: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8091: 	
                   8092: 	return "$num1:$num2";
                   8093:     }
                   8094: }
                   8095: 
1.675     albertel 8096: sub rndseed_64bit5 {
                   8097:     my ($symb,$courseid,$domain,$username)=@_;
                   8098:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8099:     return "$num1:$num2";
                   8100: }
                   8101: 
1.366     albertel 8102: sub rndseed_CODE_64bit {
                   8103:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8104:     {
1.366     albertel 8105: 	use integer;
1.443     albertel 8106: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8107: 	my $symbseed=numval2($symb);
1.491     albertel 8108: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8109: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8110: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8111: 	my $num1=$symbseed+$CODEchck;
                   8112: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8113: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8114: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8115: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8116: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8117: 	return "$num1:$num2";
1.366     albertel 8118:     }
                   8119: }
                   8120: 
1.575     albertel 8121: sub rndseed_CODE_64bit4 {
                   8122:     my ($symb,$courseid,$domain,$username)=@_;
                   8123:     {
                   8124: 	use integer;
                   8125: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8126: 	my $symbseed=numval3($symb);
                   8127: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8128: 	my $CODEseed=numval3(&getCODE());
                   8129: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8130: 	my $num1=$symbseed+$CODEchck;
                   8131: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8132: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8133: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8134: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8135: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8136: 	return "$num1:$num2";
                   8137:     }
                   8138: }
                   8139: 
1.675     albertel 8140: sub rndseed_CODE_64bit5 {
                   8141:     my ($symb,$courseid,$domain,$username)=@_;
                   8142:     my $code = &getCODE();
                   8143:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8144:     return "$num1:$num2";
                   8145: }
                   8146: 
1.366     albertel 8147: sub setup_random_from_rndseed {
                   8148:     my ($rndseed)=@_;
1.503     albertel 8149:     if ($rndseed =~/([,:])/) {
                   8150: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8151: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8152:     } else {
                   8153: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8154:     }
1.36      albertel 8155: }
                   8156: 
1.474     albertel 8157: sub latest_receipt_algorithm_id {
1.835     albertel 8158:     return 'receipt3';
1.474     albertel 8159: }
                   8160: 
1.480     www      8161: sub recunique {
                   8162:     my $fucourseid=shift;
                   8163:     my $unique;
1.835     albertel 8164:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8165: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8166: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8167:     } else {
                   8168: 	$unique=$perlvar{'lonReceipt'};
                   8169:     }
                   8170:     return unpack("%32C*",$unique);
                   8171: }
                   8172: 
                   8173: sub recprefix {
                   8174:     my $fucourseid=shift;
                   8175:     my $prefix;
1.835     albertel 8176:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8177: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8178: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8179:     } else {
                   8180: 	$prefix=$perlvar{'lonHostID'};
                   8181:     }
                   8182:     return unpack("%32C*",$prefix);
                   8183: }
                   8184: 
1.76      www      8185: sub ireceipt {
1.474     albertel 8186:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8187: 
                   8188:     my $return =&recprefix($fucourseid).'-';
                   8189: 
                   8190:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8191: 	$env{'request.state'} eq 'construct') {
                   8192: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8193: 	return $return;
                   8194:     }
                   8195: 
1.76      www      8196:     my $cuname=unpack("%32C*",$funame);
                   8197:     my $cudom=unpack("%32C*",$fudom);
                   8198:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8199:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8200:     my $cunique=&recunique($fucourseid);
1.474     albertel 8201:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8202:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8203: 
1.790     albertel 8204: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8205: 			       
                   8206: 	$return.= ($cunique%$cuname+
                   8207: 		   $cunique%$cudom+
                   8208: 		   $cusymb%$cuname+
                   8209: 		   $cusymb%$cudom+
                   8210: 		   $cucourseid%$cuname+
                   8211: 		   $cucourseid%$cudom+
                   8212: 		   $cpart%$cuname+
                   8213: 		   $cpart%$cudom);
                   8214:     } else {
                   8215: 	$return.= ($cunique%$cuname+
                   8216: 		   $cunique%$cudom+
                   8217: 		   $cusymb%$cuname+
                   8218: 		   $cusymb%$cudom+
                   8219: 		   $cucourseid%$cuname+
                   8220: 		   $cucourseid%$cudom);
                   8221:     }
                   8222:     return $return;
1.76      www      8223: }
                   8224: 
                   8225: sub receipt {
1.474     albertel 8226:     my ($part)=@_;
1.790     albertel 8227:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8228:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8229: }
1.260     ng       8230: 
1.790     albertel 8231: sub whichuser {
                   8232:     my ($passedsymb)=@_;
                   8233:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8234:     if (defined($env{'form.grade_symb'})) {
                   8235: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8236: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8237: 	if (!$allowed &&
                   8238: 	    exists($env{'request.course.sec'}) &&
                   8239: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8240: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8241: 			      '/'.$env{'request.course.sec'});
                   8242: 	}
                   8243: 	if ($allowed) {
                   8244: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8245: 	    $courseid=$tmp_courseid;
                   8246: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8247: 	    ($name)=&get_env_multiple('form.grade_username');
                   8248: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8249: 	}
                   8250:     }
                   8251:     if (!$passedsymb) {
                   8252: 	$symb=&symbread();
                   8253:     } else {
                   8254: 	$symb=$passedsymb;
                   8255:     }
                   8256:     $courseid=$env{'request.course.id'};
                   8257:     $domain=$env{'user.domain'};
                   8258:     $name=$env{'user.name'};
                   8259:     if ($name eq 'public' && $domain eq 'public') {
                   8260: 	if (!defined($env{'form.username'})) {
                   8261: 	    $env{'form.username'}.=time.rand(10000000);
                   8262: 	}
                   8263: 	$name.=$env{'form.username'};
                   8264:     }
                   8265:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8266: 
                   8267: }
                   8268: 
1.36      albertel 8269: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8270: # returns either the contents of the file or 
                   8271: # -1 if the file doesn't exist
1.481     raeburn  8272: #
                   8273: # if the target is a file that was uploaded via DOCS, 
                   8274: # a check will be made to see if a current copy exists on the local server,
                   8275: # if it does this will be served, otherwise a copy will be retrieved from
                   8276: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8277: # the local server.   
1.472     albertel 8278: 
1.36      albertel 8279: sub getfile {
1.538     albertel 8280:     my ($file) = @_;
1.609     banghart 8281:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8282:     &repcopy($file);
                   8283:     return &readfile($file);
                   8284: }
                   8285: 
                   8286: sub repcopy_userfile {
                   8287:     my ($file)=@_;
1.609     banghart 8288:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8289:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8290:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8291: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8292:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8293:     if (-e "$file") {
1.828     www      8294: # we already have a local copy, check it out
1.538     albertel 8295: 	my @fileinfo = stat($file);
1.828     www      8296: 	my $rtncode;
                   8297: 	my $info;
1.538     albertel 8298: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8299: 	if ($lwpresp ne 'ok') {
1.828     www      8300: # there is no such file anymore, even though we had a local copy
1.482     albertel 8301: 	    if ($rtncode eq '404') {
1.538     albertel 8302: 		unlink($file);
1.482     albertel 8303: 	    }
                   8304: 	    return -1;
                   8305: 	}
                   8306: 	if ($info < $fileinfo[9]) {
1.828     www      8307: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8308: 	    return 'ok';
1.828     www      8309: 	} else {
                   8310: # the file is outdated, get rid of it
                   8311: 	    unlink($file);
1.482     albertel 8312: 	}
1.828     www      8313:     }
                   8314: # one way or the other, at this point, we don't have the file
                   8315: # construct the correct path for the file
                   8316:     my @parts = ($cdom,$cnum); 
                   8317:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8318: 	push @parts, split(/\//,$1);
                   8319:     }
                   8320:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8321:     foreach my $part (@parts) {
                   8322: 	$path .= '/'.$part;
                   8323: 	if (!-e $path) {
                   8324: 	    mkdir($path,0770);
1.482     albertel 8325: 	}
                   8326:     }
1.828     www      8327: # now the path exists for sure
                   8328: # get a user agent
                   8329:     my $ua=new LWP::UserAgent;
                   8330:     my $transferfile=$file.'.in.transfer';
                   8331: # FIXME: this should flock
                   8332:     if (-e $transferfile) { return 'ok'; }
                   8333:     my $request;
                   8334:     $uri=~s/^\///;
1.980   ! raeburn  8335:     my $homeserver = &homeserver($cnum,$cdom);
        !          8336:     my $protocol = $protocol{$homeserver};
        !          8337:     $protocol = 'http' if ($protocol ne 'https');
        !          8338:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8339:     my $response=$ua->request($request,$transferfile);
                   8340: # did it work?
                   8341:     if ($response->is_error()) {
                   8342: 	unlink($transferfile);
                   8343: 	&logthis("Userfile repcopy failed for $uri");
                   8344: 	return -1;
                   8345:     }
                   8346: # worked, rename the transfer file
                   8347:     rename($transferfile,$file);
1.607     raeburn  8348:     return 'ok';
1.481     raeburn  8349: }
                   8350: 
1.517     albertel 8351: sub tokenwrapper {
                   8352:     my $uri=shift;
1.980   ! raeburn  8353:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8354:     $uri=~s|^/||;
1.620     albertel 8355:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8356:     my $token=$1;
1.552     albertel 8357:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8358:     if ($udom && $uname && $file) {
                   8359: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8360:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980   ! raeburn  8361:         my $homeserver = &homeserver($uname,$udom);
        !          8362:         my $protocol = $protocol{$homeserver};
        !          8363:         $protocol = 'http' if ($protocol ne 'https');
        !          8364:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8365:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8366:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8367:     } else {
                   8368:         return '/adm/notfound.html';
                   8369:     }
                   8370: }
                   8371: 
1.828     www      8372: # call with reqtype HEAD: get last modification time
                   8373: # call with reqtype GET: get the file contents
                   8374: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8375: #
1.481     raeburn  8376: sub getuploaded {
                   8377:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8378:     $uri=~s/^\///;
1.980   ! raeburn  8379:     my $homeserver = &homeserver($cnum,$cdom);
        !          8380:     my $protocol = $protocol{$homeserver};
        !          8381:     $protocol = 'http' if ($protocol ne 'https');
        !          8382:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8383:     my $ua=new LWP::UserAgent;
                   8384:     my $request=new HTTP::Request($reqtype,$uri);
                   8385:     my $response=$ua->request($request);
                   8386:     $$rtncode = $response->code;
1.482     albertel 8387:     if (! $response->is_success()) {
                   8388: 	return 'failed';
                   8389:     }      
                   8390:     if ($reqtype eq 'HEAD') {
1.486     www      8391: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8392:     } elsif ($reqtype eq 'GET') {
                   8393: 	$$info = $response->content;
1.472     albertel 8394:     }
1.482     albertel 8395:     return 'ok';
1.36      albertel 8396: }
                   8397: 
1.481     raeburn  8398: sub readfile {
                   8399:     my $file = shift;
                   8400:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8401:     my $fh;
                   8402:     open($fh,"<$file");
                   8403:     my $a='';
1.800     albertel 8404:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8405:     return $a;
                   8406: }
                   8407: 
1.36      albertel 8408: sub filelocation {
1.590     banghart 8409:     my ($dir,$file) = @_;
                   8410:     my $location;
                   8411:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8412: 
                   8413:     if ($file =~ m-^/adm/-) {
                   8414: 	$file=~s-^/adm/wrapper/-/-;
                   8415: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8416:     }
1.882     albertel 8417: 
1.590     banghart 8418:     if ($file=~m:^/~:) { # is a contruction space reference
                   8419:         $location = $file;
                   8420:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8421:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8422: 	# is a correct contruction space reference
                   8423:         $location = $file;
1.956     raeburn  8424:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8425:         $location = $file;
1.609     banghart 8426:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8427:         my ($udom,$uname,$filename)=
1.811     albertel 8428:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8429:         my $home=&homeserver($uname,$udom);
                   8430:         my $is_me=0;
                   8431:         my @ids=&current_machine_ids();
                   8432:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8433:         if ($is_me) {
1.955     raeburn  8434:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8435:         } else {
                   8436:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8437:   	      $udom.'/'.$uname.'/'.$filename;
                   8438:         }
1.882     albertel 8439:     } elsif ($file =~ m-^/adm/-) {
                   8440: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8441:     } else {
                   8442:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8443:         $file=~s:^/res/:/:;
                   8444:         if ( !( $file =~ m:^/:) ) {
                   8445:             $location = $dir. '/'.$file;
                   8446:         } else {
                   8447:             $location = '/home/httpd/html/res'.$file;
                   8448:         }
1.59      albertel 8449:     }
1.590     banghart 8450:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8451:     while ($location=~m{/\.\./}) {
                   8452: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8453: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8454: 	} else {
                   8455: 	    $location=~ s{/\.\./}{/}g;
                   8456: 	}
                   8457:     } #remove dir/..
1.590     banghart 8458:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8459:     return $location;
1.46      www      8460: }
1.36      albertel 8461: 
1.46      www      8462: sub hreflocation {
                   8463:     my ($dir,$file)=@_;
1.980   ! raeburn  8464:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8465: 	$file=filelocation($dir,$file);
1.700     albertel 8466:     } elsif ($file=~m-^/adm/-) {
                   8467: 	$file=~s-^/adm/wrapper/-/-;
                   8468: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8469:     }
                   8470:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8471: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8472:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8473: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8474:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8475: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8476: 	    -/uploaded/$1/$2/-x;
1.46      www      8477:     }
1.913     albertel 8478:     if ($file=~ m{^/userfiles/}) {
                   8479: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8480:     }
1.462     albertel 8481:     return $file;
1.465     albertel 8482: }
                   8483: 
                   8484: sub current_machine_domains {
1.853     albertel 8485:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8486: }
                   8487: 
                   8488: sub machine_domains {
                   8489:     my ($hostname) = @_;
1.465     albertel 8490:     my @domains;
1.838     albertel 8491:     my %hostname = &all_hostnames();
1.465     albertel 8492:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8493: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8494: 	if ($hostname eq $name) {
1.844     albertel 8495: 	    push(@domains,&host_domain($id));
1.465     albertel 8496: 	}
                   8497:     }
                   8498:     return @domains;
                   8499: }
                   8500: 
                   8501: sub current_machine_ids {
1.853     albertel 8502:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8503: }
                   8504: 
                   8505: sub machine_ids {
                   8506:     my ($hostname) = @_;
                   8507:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8508:     my @ids;
1.888     albertel 8509:     my %name_to_host = &all_names();
1.889     albertel 8510:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8511: 	return @{ $name_to_host{$hostname} };
                   8512:     }
                   8513:     return;
1.31      www      8514: }
                   8515: 
1.824     raeburn  8516: sub additional_machine_domains {
                   8517:     my @domains;
                   8518:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8519:     while( my $line = <$fh>) {
                   8520:         $line =~ s/\s//g;
                   8521:         push(@domains,$line);
                   8522:     }
                   8523:     return @domains;
                   8524: }
                   8525: 
                   8526: sub default_login_domain {
                   8527:     my $domain = $perlvar{'lonDefDomain'};
                   8528:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8529:     foreach my $posdom (&current_machine_domains(),
                   8530:                         &additional_machine_domains()) {
                   8531:         if (lc($posdom) eq lc($testdomain)) {
                   8532:             $domain=$posdom;
                   8533:             last;
                   8534:         }
                   8535:     }
                   8536:     return $domain;
                   8537: }
                   8538: 
1.31      www      8539: # ------------------------------------------------------------- Declutters URLs
                   8540: 
                   8541: sub declutter {
                   8542:     my $thisfn=shift;
1.569     albertel 8543:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8544:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8545:     $thisfn=~s/^\///;
1.697     albertel 8546:     $thisfn=~s|^adm/wrapper/||;
                   8547:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8548:     $thisfn=~s/^res\///;
1.235     www      8549:     $thisfn=~s/\?.+$//;
1.268     www      8550:     return $thisfn;
                   8551: }
                   8552: 
                   8553: # ------------------------------------------------------------- Clutter up URLs
                   8554: 
                   8555: sub clutter {
                   8556:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8557:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8558: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8559:        $thisfn='/res'.$thisfn; 
                   8560:     }
1.694     albertel 8561:     if ($thisfn !~m|/adm|) {
1.695     albertel 8562: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8563: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8564: 	} else {
                   8565: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8566: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8567: 	    if ($embstyle eq 'ssi'
                   8568: 		|| ($embstyle eq 'hdn')
                   8569: 		|| ($embstyle eq 'rat')
                   8570: 		|| ($embstyle eq 'prv')
                   8571: 		|| ($embstyle eq 'ign')) {
                   8572: 		#do nothing with these
                   8573: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8574: 		|| ($embstyle eq 'emb')
                   8575: 		|| ($embstyle eq 'wrp')) {
                   8576: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8577: 	    } elsif ($embstyle eq 'unk'
                   8578: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8579: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8580: 	    } else {
1.718     www      8581: #		&logthis("Got a blank emb style");
1.695     albertel 8582: 	    }
1.694     albertel 8583: 	}
                   8584:     }
1.31      www      8585:     return $thisfn;
1.12      www      8586: }
                   8587: 
1.787     albertel 8588: sub clutter_with_no_wrapper {
                   8589:     my $uri = &clutter(shift);
                   8590:     if ($uri =~ m-^/adm/-) {
                   8591: 	$uri =~ s-^/adm/wrapper/-/-;
                   8592: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8593:     }
                   8594:     return $uri;
                   8595: }
                   8596: 
1.557     albertel 8597: sub freeze_escape {
                   8598:     my ($value)=@_;
                   8599:     if (ref($value)) {
                   8600: 	$value=&nfreeze($value);
                   8601: 	return '__FROZEN__'.&escape($value);
                   8602:     }
                   8603:     return &escape($value);
                   8604: }
                   8605: 
1.11      www      8606: 
1.557     albertel 8607: sub thaw_unescape {
                   8608:     my ($value)=@_;
                   8609:     if ($value =~ /^__FROZEN__/) {
                   8610: 	substr($value,0,10,undef);
                   8611: 	$value=&unescape($value);
                   8612: 	return &thaw($value);
                   8613:     }
                   8614:     return &unescape($value);
                   8615: }
                   8616: 
1.436     albertel 8617: sub correct_line_ends {
                   8618:     my ($result)=@_;
                   8619:     $$result =~s/\r\n/\n/mg;
                   8620:     $$result =~s/\r/\n/mg;
1.415     albertel 8621: }
1.1       albertel 8622: # ================================================================ Main Program
                   8623: 
1.184     www      8624: sub goodbye {
1.204     albertel 8625:    &logthis("Starting Shut down");
1.443     albertel 8626: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8627:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8628: #converted
1.599     albertel 8629: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8630:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8631: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8632: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8633: #1.1 only
1.870     albertel 8634: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8635: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8636: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8637: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8638:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8639:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8640:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8641:    &flushcourselogs();
                   8642:    &logthis("Shutting down");
                   8643: }
                   8644: 
1.852     albertel 8645: sub get_dns {
1.869     albertel 8646:     my ($url,$func,$ignore_cache) = @_;
                   8647:     if (!$ignore_cache) {
                   8648: 	my ($content,$cached)=
                   8649: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8650: 	if ($cached) {
                   8651: 	    &$func($content);
                   8652: 	    return;
                   8653: 	}
                   8654:     }
                   8655: 
                   8656:     my %alldns;
1.852     albertel 8657:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8658:     foreach my $dns (<$config>) {
                   8659: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8660:         my $line = $1;
                   8661:         my ($host,$protocol) = split(/:/,$line);
                   8662:         if ($protocol ne 'https') {
                   8663:             $protocol = 'http';
                   8664:         }
                   8665: 	$alldns{$host} = $protocol;
1.869     albertel 8666:     }
                   8667:     while (%alldns) {
                   8668: 	my ($dns) = keys(%alldns);
1.852     albertel 8669: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8670: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8671: 	my $response=$ua->request($request);
1.979     raeburn  8672:         delete($alldns{$dns});
1.852     albertel 8673: 	next if ($response->is_error());
                   8674: 	my @content = split("\n",$response->content);
1.869     albertel 8675: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8676: 	&$func(\@content);
1.869     albertel 8677: 	return;
1.852     albertel 8678:     }
                   8679:     close($config);
1.871     albertel 8680:     my $which = (split('/',$url))[3];
                   8681:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8682:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8683:     my @content = <$config>;
                   8684:     &$func(\@content);
                   8685:     return;
1.852     albertel 8686: }
1.327     albertel 8687: # ------------------------------------------------------------ Read domain file
                   8688: {
1.852     albertel 8689:     my $loaded;
1.846     albertel 8690:     my %domain;
                   8691: 
1.852     albertel 8692:     sub parse_domain_tab {
                   8693: 	my ($lines) = @_;
                   8694: 	foreach my $line (@$lines) {
                   8695: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8696: 
1.846     albertel 8697: 	    chomp($line);
1.852     albertel 8698: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8699: 	    my %this_domain;
                   8700: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8701: 			       'lang_def', 'city', 'longi', 'lati',
                   8702: 			       'primary') {
                   8703: 		$this_domain{$field} = shift(@elements);
                   8704: 	    }
                   8705: 	    $domain{$name} = \%this_domain;
1.852     albertel 8706: 	}
                   8707:     }
1.864     albertel 8708: 
                   8709:     sub reset_domain_info {
                   8710: 	undef($loaded);
                   8711: 	undef(%domain);
                   8712:     }
                   8713: 
1.852     albertel 8714:     sub load_domain_tab {
1.869     albertel 8715: 	my ($ignore_cache) = @_;
                   8716: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8717: 	my $fh;
                   8718: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8719: 	    my @lines = <$fh>;
                   8720: 	    &parse_domain_tab(\@lines);
1.448     albertel 8721: 	}
1.852     albertel 8722: 	close($fh);
                   8723: 	$loaded = 1;
1.327     albertel 8724:     }
1.846     albertel 8725: 
                   8726:     sub domain {
1.852     albertel 8727: 	&load_domain_tab() if (!$loaded);
                   8728: 
1.846     albertel 8729: 	my ($name,$what) = @_;
                   8730: 	return if ( !exists($domain{$name}) );
                   8731: 
                   8732: 	if (!$what) {
                   8733: 	    return $domain{$name}{'description'};
                   8734: 	}
                   8735: 	return $domain{$name}{$what};
                   8736:     }
1.974     raeburn  8737: 
                   8738:     sub domain_info {
                   8739:         &load_domain_tab() if (!$loaded);
                   8740:         return %domain;
                   8741:     }
                   8742: 
1.327     albertel 8743: }
                   8744: 
                   8745: 
1.1       albertel 8746: # ------------------------------------------------------------- Read hosts file
                   8747: {
1.838     albertel 8748:     my %hostname;
1.844     albertel 8749:     my %hostdom;
1.845     albertel 8750:     my %libserv;
1.852     albertel 8751:     my $loaded;
1.888     albertel 8752:     my %name_to_host;
1.852     albertel 8753: 
                   8754:     sub parse_hosts_tab {
                   8755: 	my ($file) = @_;
                   8756: 	foreach my $configline (@$file) {
                   8757: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8758: 	    next if ($configline =~ /^\^/);
                   8759: 	    chomp($configline);
1.968     raeburn  8760: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8761: 	    $name=~s/\s//g;
                   8762: 	    if ($id && $domain && $role && $name) {
                   8763: 		$hostname{$id}=$name;
1.888     albertel 8764: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8765: 		$hostdom{$id}=$domain;
                   8766: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8767:                 if (defined($protocol)) {
                   8768:                     if ($protocol eq 'https') {
                   8769:                         $protocol{$id} = $protocol;
                   8770:                     } else {
                   8771:                         $protocol{$id} = 'http'; 
                   8772:                     }
1.968     raeburn  8773:                 } else {
1.969     raeburn  8774:                     $protocol{$id} = 'http';
1.968     raeburn  8775:                 }
1.852     albertel 8776: 	    }
                   8777: 	}
                   8778:     }
1.864     albertel 8779:     
                   8780:     sub reset_hosts_info {
1.897     albertel 8781: 	&purge_remembered();
1.864     albertel 8782: 	&reset_domain_info();
                   8783: 	&reset_hosts_ip_info();
1.892     albertel 8784: 	undef(%name_to_host);
1.864     albertel 8785: 	undef(%hostname);
                   8786: 	undef(%hostdom);
                   8787: 	undef(%libserv);
                   8788: 	undef($loaded);
                   8789:     }
1.1       albertel 8790: 
1.852     albertel 8791:     sub load_hosts_tab {
1.869     albertel 8792: 	my ($ignore_cache) = @_;
                   8793: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8794: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8795: 	my @config = <$config>;
                   8796: 	&parse_hosts_tab(\@config);
                   8797: 	close($config);
                   8798: 	$loaded=1;
1.1       albertel 8799:     }
1.852     albertel 8800: 
1.838     albertel 8801:     sub hostname {
1.852     albertel 8802: 	&load_hosts_tab() if (!$loaded);
                   8803: 
1.838     albertel 8804: 	my ($lonid) = @_;
                   8805: 	return $hostname{$lonid};
                   8806:     }
1.845     albertel 8807: 
1.838     albertel 8808:     sub all_hostnames {
1.852     albertel 8809: 	&load_hosts_tab() if (!$loaded);
                   8810: 
1.838     albertel 8811: 	return %hostname;
                   8812:     }
1.845     albertel 8813: 
1.888     albertel 8814:     sub all_names {
                   8815: 	&load_hosts_tab() if (!$loaded);
                   8816: 
                   8817: 	return %name_to_host;
                   8818:     }
                   8819: 
1.974     raeburn  8820:     sub all_host_domain {
                   8821:         &load_hosts_tab() if (!$loaded);
                   8822:         return %hostdom;
                   8823:     }
                   8824: 
1.845     albertel 8825:     sub is_library {
1.852     albertel 8826: 	&load_hosts_tab() if (!$loaded);
                   8827: 
1.845     albertel 8828: 	return exists($libserv{$_[0]});
                   8829:     }
                   8830: 
                   8831:     sub all_library {
1.852     albertel 8832: 	&load_hosts_tab() if (!$loaded);
                   8833: 
1.845     albertel 8834: 	return %libserv;
                   8835:     }
                   8836: 
1.841     albertel 8837:     sub get_servers {
1.852     albertel 8838: 	&load_hosts_tab() if (!$loaded);
                   8839: 
1.841     albertel 8840: 	my ($domain,$type) = @_;
                   8841: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8842: 	                                          : %hostname;
                   8843: 	my %result;
1.842     albertel 8844: 	if (ref($domain) eq 'ARRAY') {
                   8845: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8846: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8847: 		    $result{$host} = $hostname;
                   8848: 		}
                   8849: 	    }
                   8850: 	} else {
                   8851: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8852: 		if ($hostdom{$host} eq $domain) {
                   8853: 		    $result{$host} = $hostname;
                   8854: 		}
1.841     albertel 8855: 	    }
                   8856: 	}
                   8857: 	return %result;
                   8858:     }
1.845     albertel 8859: 
1.844     albertel 8860:     sub host_domain {
1.852     albertel 8861: 	&load_hosts_tab() if (!$loaded);
                   8862: 
1.844     albertel 8863: 	my ($lonid) = @_;
                   8864: 	return $hostdom{$lonid};
                   8865:     }
                   8866: 
1.841     albertel 8867:     sub all_domains {
1.852     albertel 8868: 	&load_hosts_tab() if (!$loaded);
                   8869: 
1.841     albertel 8870: 	my %seen;
                   8871: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8872: 	return @uniq;
                   8873:     }
1.1       albertel 8874: }
                   8875: 
1.847     albertel 8876: { 
                   8877:     my %iphost;
1.856     albertel 8878:     my %name_to_ip;
                   8879:     my %lonid_to_ip;
1.869     albertel 8880: 
1.847     albertel 8881:     sub get_hosts_from_ip {
                   8882: 	my ($ip) = @_;
                   8883: 	my %iphosts = &get_iphost();
                   8884: 	if (ref($iphosts{$ip})) {
                   8885: 	    return @{$iphosts{$ip}};
                   8886: 	}
                   8887: 	return;
1.839     albertel 8888:     }
1.864     albertel 8889:     
                   8890:     sub reset_hosts_ip_info {
                   8891: 	undef(%iphost);
                   8892: 	undef(%name_to_ip);
                   8893: 	undef(%lonid_to_ip);
                   8894:     }
1.856     albertel 8895: 
                   8896:     sub get_host_ip {
                   8897: 	my ($lonid) = @_;
                   8898: 	if (exists($lonid_to_ip{$lonid})) {
                   8899: 	    return $lonid_to_ip{$lonid};
                   8900: 	}
                   8901: 	my $name=&hostname($lonid);
                   8902:    	my $ip = gethostbyname($name);
                   8903: 	return if (!$ip || length($ip) ne 4);
                   8904: 	$ip=inet_ntoa($ip);
                   8905: 	$name_to_ip{$name}   = $ip;
                   8906: 	$lonid_to_ip{$lonid} = $ip;
                   8907: 	return $ip;
                   8908:     }
1.847     albertel 8909:     
                   8910:     sub get_iphost {
1.869     albertel 8911: 	my ($ignore_cache) = @_;
1.894     albertel 8912: 
1.869     albertel 8913: 	if (!$ignore_cache) {
                   8914: 	    if (%iphost) {
                   8915: 		return %iphost;
                   8916: 	    }
                   8917: 	    my ($ip_info,$cached)=
                   8918: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8919: 	    if ($cached) {
                   8920: 		%iphost      = %{$ip_info->[0]};
                   8921: 		%name_to_ip  = %{$ip_info->[1]};
                   8922: 		%lonid_to_ip = %{$ip_info->[2]};
                   8923: 		return %iphost;
                   8924: 	    }
                   8925: 	}
1.894     albertel 8926: 
                   8927: 	# get yesterday's info for fallback
                   8928: 	my %old_name_to_ip;
                   8929: 	my ($ip_info,$cached)=
                   8930: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8931: 	if ($cached) {
                   8932: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8933: 	}
                   8934: 
1.888     albertel 8935: 	my %name_to_host = &all_names();
                   8936: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8937: 	    my $ip;
                   8938: 	    if (!exists($name_to_ip{$name})) {
                   8939: 		$ip = gethostbyname($name);
                   8940: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8941: 		    if (defined($old_name_to_ip{$name})) {
                   8942: 			$ip = $old_name_to_ip{$name};
                   8943: 			&logthis("Can't find $name defaulting to old $ip");
                   8944: 		    } else {
                   8945: 			&logthis("Name $name no IP found");
                   8946: 			next;
                   8947: 		    }
                   8948: 		} else {
                   8949: 		    $ip=inet_ntoa($ip);
1.847     albertel 8950: 		}
                   8951: 		$name_to_ip{$name} = $ip;
                   8952: 	    } else {
                   8953: 		$ip = $name_to_ip{$name};
1.653     albertel 8954: 	    }
1.888     albertel 8955: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8956: 		$lonid_to_ip{$id} = $ip;
                   8957: 	    }
                   8958: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8959: 	}
1.869     albertel 8960: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8961: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8962: 				      48*60*60);
1.869     albertel 8963: 
1.847     albertel 8964: 	return %iphost;
1.598     albertel 8965:     }
                   8966: }
                   8967: 
1.862     albertel 8968: BEGIN {
                   8969: 
                   8970: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8971:     unless ($readit) {
                   8972: {
                   8973:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8974:     %perlvar = (%perlvar,%{$configvars});
                   8975: }
                   8976: 
                   8977: 
1.1       albertel 8978: # ------------------------------------------------------ Read spare server file
                   8979: {
1.448     albertel 8980:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8981: 
                   8982:     while (my $configline=<$config>) {
                   8983:        chomp($configline);
1.284     matthew  8984:        if ($configline) {
1.784     albertel 8985: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8986: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8987: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8988:        }
                   8989:     }
1.448     albertel 8990:     close($config);
1.1       albertel 8991: }
1.11      www      8992: # ------------------------------------------------------------ Read permissions
                   8993: {
1.448     albertel 8994:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8995: 
                   8996:     while (my $configline=<$config>) {
1.448     albertel 8997: 	chomp($configline);
                   8998: 	if ($configline) {
                   8999: 	    my ($role,$perm)=split(/ /,$configline);
                   9000: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9001: 	}
1.11      www      9002:     }
1.448     albertel 9003:     close($config);
1.11      www      9004: }
                   9005: 
                   9006: # -------------------------------------------- Read plain texts for permissions
                   9007: {
1.448     albertel 9008:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9009: 
                   9010:     while (my $configline=<$config>) {
1.448     albertel 9011: 	chomp($configline);
                   9012: 	if ($configline) {
1.742     raeburn  9013: 	    my ($short,@plain)=split(/:/,$configline);
                   9014:             %{$prp{$short}} = ();
                   9015: 	    if (@plain > 0) {
                   9016:                 $prp{$short}{'std'} = $plain[0];
                   9017:                 for (my $i=1; $i<@plain; $i++) {
                   9018:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9019:                 }
                   9020:             }
1.448     albertel 9021: 	}
1.135     www      9022:     }
1.448     albertel 9023:     close($config);
1.135     www      9024: }
                   9025: 
                   9026: # ---------------------------------------------------------- Read package table
                   9027: {
1.448     albertel 9028:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9029: 
                   9030:     while (my $configline=<$config>) {
1.483     albertel 9031: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9032: 	chomp($configline);
                   9033: 	my ($short,$plain)=split(/:/,$configline);
                   9034: 	my ($pack,$name)=split(/\&/,$short);
                   9035: 	if ($plain ne '') {
                   9036: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9037: 	    $packagetab{$short}=$plain; 
                   9038: 	}
1.11      www      9039:     }
1.448     albertel 9040:     close($config);
1.329     matthew  9041: }
                   9042: 
                   9043: # ------------- set up temporary directory
                   9044: {
                   9045:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9046: 
1.11      www      9047: }
                   9048: 
1.794     albertel 9049: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9050: 				'compress_threshold'=> 20_000,
                   9051:  			        });
1.185     www      9052: 
1.281     www      9053: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9054: $dumpcount=0;
1.958     www      9055: $locknum=0;
1.22      www      9056: 
1.163     harris41 9057: &logtouch();
1.672     albertel 9058: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9059: $readit=1;
1.564     albertel 9060:     {
                   9061: 	use integer;
                   9062: 	my $test=(2**32)+1;
1.568     albertel 9063: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9064: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9065:     }
1.195     www      9066: }
1.1       albertel 9067: }
1.179     www      9068: 
1.1       albertel 9069: 1;
1.191     harris41 9070: __END__
                   9071: 
1.243     albertel 9072: =pod
                   9073: 
1.191     harris41 9074: =head1 NAME
                   9075: 
1.243     albertel 9076: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9077: 
                   9078: =head1 SYNOPSIS
                   9079: 
1.243     albertel 9080: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9081: 
                   9082:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9083: 
1.243     albertel 9084: Common parameters:
                   9085: 
                   9086: =over 4
                   9087: 
                   9088: =item *
                   9089: 
                   9090: $uname : an internal username (if $cname expecting a course Id specifically)
                   9091: 
                   9092: =item *
                   9093: 
                   9094: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9095: 
                   9096: =item *
                   9097: 
                   9098: $symb : a resource instance identifier
                   9099: 
                   9100: =item *
                   9101: 
                   9102: $namespace : the name of a .db file that contains the data needed or
                   9103: being set.
                   9104: 
                   9105: =back
                   9106: 
1.394     bowersj2 9107: =head1 OVERVIEW
1.191     harris41 9108: 
1.394     bowersj2 9109: lonnet provides subroutines which interact with the
                   9110: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9111: about classes, users, and resources.
1.243     albertel 9112: 
                   9113: For many of these objects you can also use this to store data about
                   9114: them or modify them in various ways.
1.191     harris41 9115: 
1.394     bowersj2 9116: =head2 Symbs
1.191     harris41 9117: 
1.394     bowersj2 9118: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9119: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9120: map, the resource number of the resource in the map, and the URL of
                   9121: the resource itself. The latter is somewhat redundant, but might help
                   9122: if maps change.
                   9123: 
                   9124: An example is
                   9125: 
                   9126:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9127: 
                   9128: The respective map entry is
                   9129: 
                   9130:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9131:   title="Problem 2">
                   9132:  </resource>
                   9133: 
                   9134: Symbs are used by the random number generator, as well as to store and
                   9135: restore data specific to a certain instance of for example a problem.
                   9136: 
                   9137: =head2 Storing And Retrieving Data
                   9138: 
                   9139: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9140: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9141: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9142: is is the non-critical message twin of cstore. These functions are for
                   9143: handlers to store a perl hash to a user's permanent data space in an
                   9144: easy manner, and to retrieve it again on another call. It is expected
                   9145: that a handler would use this once at the beginning to retrieve data,
                   9146: and then again once at the end to send only the new data back.
                   9147: 
                   9148: The data is stored in the user's data directory on the user's
                   9149: homeserver under the ID of the course.
                   9150: 
                   9151: The hash that is returned by restore will have all of the previous
                   9152: value for all of the elements of the hash.
                   9153: 
                   9154: Example:
                   9155: 
                   9156:  #creating a hash
                   9157:  my %hash;
                   9158:  $hash{'foo'}='bar';
                   9159: 
                   9160:  #storing it
                   9161:  &Apache::lonnet::cstore(\%hash);
                   9162: 
                   9163:  #changing a value
                   9164:  $hash{'foo'}='notbar';
                   9165: 
                   9166:  #adding a new value
                   9167:  $hash{'bar'}='foo';
                   9168:  &Apache::lonnet::cstore(\%hash);
                   9169: 
                   9170:  #retrieving the hash
                   9171:  my %history=&Apache::lonnet::restore();
                   9172: 
                   9173:  #print the hash
                   9174:  foreach my $key (sort(keys(%history))) {
                   9175:    print("\%history{$key} = $history{$key}");
                   9176:  }
                   9177: 
                   9178: Will print out:
1.191     harris41 9179: 
1.394     bowersj2 9180:  %history{1:foo} = bar
                   9181:  %history{1:keys} = foo:timestamp
                   9182:  %history{1:timestamp} = 990455579
                   9183:  %history{2:bar} = foo
                   9184:  %history{2:foo} = notbar
                   9185:  %history{2:keys} = foo:bar:timestamp
                   9186:  %history{2:timestamp} = 990455580
                   9187:  %history{bar} = foo
                   9188:  %history{foo} = notbar
                   9189:  %history{timestamp} = 990455580
                   9190:  %history{version} = 2
                   9191: 
                   9192: Note that the special hash entries C<keys>, C<version> and
                   9193: C<timestamp> were added to the hash. C<version> will be equal to the
                   9194: total number of versions of the data that have been stored. The
                   9195: C<timestamp> attribute will be the UNIX time the hash was
                   9196: stored. C<keys> is available in every historical section to list which
                   9197: keys were added or changed at a specific historical revision of a
                   9198: hash.
                   9199: 
                   9200: B<Warning>: do not store the hash that restore returns directly. This
                   9201: will cause a mess since it will restore the historical keys as if the
                   9202: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9203: 
1.394     bowersj2 9204: Calling convention:
1.191     harris41 9205: 
1.394     bowersj2 9206:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9207:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9208: 
1.394     bowersj2 9209: For more detailed information, see lonnet specific documentation.
1.191     harris41 9210: 
1.394     bowersj2 9211: =head1 RETURN MESSAGES
1.191     harris41 9212: 
1.394     bowersj2 9213: =over 4
1.191     harris41 9214: 
1.394     bowersj2 9215: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9216: 
1.394     bowersj2 9217: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9218: when the connection is brought back up
1.191     harris41 9219: 
1.394     bowersj2 9220: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9221: for later delivery
1.191     harris41 9222: 
1.967     bisitz   9223: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9224: 
1.394     bowersj2 9225: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9226: that was requested
1.191     harris41 9227: 
1.243     albertel 9228: =back
1.191     harris41 9229: 
1.243     albertel 9230: =head1 PUBLIC SUBROUTINES
1.191     harris41 9231: 
1.243     albertel 9232: =head2 Session Environment Functions
1.191     harris41 9233: 
1.243     albertel 9234: =over 4
1.191     harris41 9235: 
1.394     bowersj2 9236: =item * 
                   9237: X<appenv()>
1.949     raeburn  9238: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9239: the user envirnoment file, and will be restored for each access this
1.620     albertel 9240: user makes during this session, also modifies the %env for the current
1.949     raeburn  9241: process. Optional rolesarrayref - if defined contains a reference to an array
                   9242: of roles which are exempt from the restriction on modifying user.role entries 
                   9243: in the user's environment.db and in %env.    
1.191     harris41 9244: 
                   9245: =item *
1.394     bowersj2 9246: X<delenv()>
                   9247: B<delenv($regexp)>: removes all items from the session
                   9248: environment file that matches the regular expression in $regexp. The
1.620     albertel 9249: values are also delted from the current processes %env.
1.191     harris41 9250: 
1.795     albertel 9251: =item * get_env_multiple($name) 
                   9252: 
                   9253: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9254: values may be defined and end up as an array ref.
                   9255: 
                   9256: returns an array of values
                   9257: 
1.243     albertel 9258: =back
                   9259: 
                   9260: =head2 User Information
1.191     harris41 9261: 
1.243     albertel 9262: =over 4
1.191     harris41 9263: 
                   9264: =item *
1.394     bowersj2 9265: X<queryauthenticate()>
                   9266: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9267: authentication scheme
                   9268: 
                   9269: =item *
1.394     bowersj2 9270: X<authenticate()>
                   9271: B<authenticate($uname,$upass,$udom)>: try to
                   9272: authenticate user from domain's lib servers (first use the current
                   9273: one). C<$upass> should be the users password.
1.191     harris41 9274: 
                   9275: =item *
1.394     bowersj2 9276: X<homeserver()>
                   9277: B<homeserver($uname,$udom)>: find the server which has
                   9278: the user's directory and files (there must be only one), this caches
                   9279: the answer, and also caches if there is a borken connection.
1.191     harris41 9280: 
                   9281: =item *
1.394     bowersj2 9282: X<idget()>
                   9283: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9284: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9285: username, and only 1 username per ID in a specific domain) (returns
                   9286: hash: id=>name,id=>name)
1.191     harris41 9287: 
                   9288: =item *
1.394     bowersj2 9289: X<idrget()>
                   9290: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9291: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9292: 
                   9293: =item *
1.394     bowersj2 9294: X<idput()>
                   9295: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9296: 
                   9297: =item *
1.394     bowersj2 9298: X<rolesinit()>
                   9299: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9300: 
                   9301: =item *
1.551     albertel 9302: X<getsection()>
                   9303: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9304: course $cname, return section name/number or '' for "not in course"
                   9305: and '-1' for "no section"
                   9306: 
                   9307: =item *
1.394     bowersj2 9308: X<userenvironment()>
                   9309: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9310: passed in @what from the requested user's environment, returns a hash
                   9311: 
1.858     raeburn  9312: =item * 
                   9313: X<userlog_query()>
1.859     albertel 9314: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9315: activity.log file. %filters defines filters applied when parsing the
                   9316: log file. These can be start or end timestamps, or the type of action
                   9317: - log to look for Login or Logout events, check for Checkin or
                   9318: Checkout, role for role selection. The response is in the form
                   9319: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9320: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9321: 
1.243     albertel 9322: =back
                   9323: 
                   9324: =head2 User Roles
                   9325: 
                   9326: =over 4
                   9327: 
                   9328: =item *
                   9329: 
1.810     raeburn  9330: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9331:  F: full access
                   9332:  U,I,K: authentication modes (cxx only)
                   9333:  '': forbidden
                   9334:  1: user needs to choose course
                   9335:  2: browse allowed
1.766     albertel 9336:  A: passphrase authentication needed
1.243     albertel 9337: 
                   9338: =item *
                   9339: 
                   9340: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9341: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9342: and course level
                   9343: 
                   9344: =item *
                   9345: 
                   9346: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9347: explanation of a user role term
                   9348: 
1.832     raeburn  9349: =item *
                   9350: 
1.935     raeburn  9351: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9352: All arguments are optional. Returns a hash of a roles, either for
                   9353: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9354: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9355: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9356: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9357: For each key, value is set to colon-separated start and end times for
                   9358: the role.  If no username and domain are specified, will default to
1.934     raeburn  9359: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9360: of role statuses (active, future or previous), roles 
                   9361: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9362: to restrict the list of roles reported. If no array ref is 
                   9363: provided for types, will default to return only active roles.
1.834     albertel 9364: 
1.243     albertel 9365: =back
                   9366: 
                   9367: =head2 User Modification
                   9368: 
                   9369: =over 4
                   9370: 
                   9371: =item *
                   9372: 
1.957     raeburn  9373: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9374: user for the level given by URL.  Optional start and end dates (leave empty
                   9375: string or zero for "no date")
1.191     harris41 9376: 
                   9377: =item *
                   9378: 
1.243     albertel 9379: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9380: change a users, password, possible return values are: ok,
                   9381: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9382: refused
1.191     harris41 9383: 
                   9384: =item *
                   9385: 
1.243     albertel 9386: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9387: 
                   9388: =item *
                   9389: 
1.963     raeburn  9390: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9391:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9392: modify user
1.191     harris41 9393: 
                   9394: =item *
                   9395: 
1.286     matthew  9396: modifystudent
                   9397: 
1.957     raeburn  9398: modify a student's enrollment and identification information.
1.286     matthew  9399: The course id is resolved based on the current users environment.  
                   9400: This means the envoking user must be a course coordinator or otherwise
                   9401: associated with a course.
                   9402: 
1.297     matthew  9403: This call is essentially a wrapper for lonnet::modifyuser and
                   9404: lonnet::modify_student_enrollment
1.286     matthew  9405: 
                   9406: Inputs: 
                   9407: 
                   9408: =over 4
                   9409: 
1.957     raeburn  9410: =item B<$udom> Student's loncapa domain
1.286     matthew  9411: 
1.957     raeburn  9412: =item B<$uname> Student's loncapa login name
1.286     matthew  9413: 
1.964     bisitz   9414: =item B<$uid> Student/Employee ID
1.286     matthew  9415: 
1.957     raeburn  9416: =item B<$umode> Student's authentication mode
1.286     matthew  9417: 
1.957     raeburn  9418: =item B<$upass> Student's password
1.286     matthew  9419: 
1.957     raeburn  9420: =item B<$first> Student's first name
1.286     matthew  9421: 
1.957     raeburn  9422: =item B<$middle> Student's middle name
1.286     matthew  9423: 
1.957     raeburn  9424: =item B<$last> Student's last name
1.286     matthew  9425: 
1.957     raeburn  9426: =item B<$gene> Student's generation
1.286     matthew  9427: 
1.957     raeburn  9428: =item B<$usec> Student's section in course
1.286     matthew  9429: 
                   9430: =item B<$end> Unix time of the roles expiration
                   9431: 
                   9432: =item B<$start> Unix time of the roles start date
                   9433: 
                   9434: =item B<$forceid> If defined, allow $uid to be changed
                   9435: 
                   9436: =item B<$desiredhome> server to use as home server for student
                   9437: 
1.957     raeburn  9438: =item B<$email> Student's permanent e-mail address
                   9439: 
                   9440: =item B<$type> Type of enrollment (auto or manual)
                   9441: 
1.963     raeburn  9442: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9443: 
                   9444: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9445: 
1.963     raeburn  9446: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9447: 
1.963     raeburn  9448: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9449: 
1.963     raeburn  9450: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9451: 
1.286     matthew  9452: =back
1.297     matthew  9453: 
                   9454: =item *
                   9455: 
                   9456: modify_student_enrollment
                   9457: 
                   9458: Change a students enrollment status in a class.  The environment variable
                   9459: 'role.request.course' must be defined for this function to proceed.
                   9460: 
                   9461: Inputs:
                   9462: 
                   9463: =over 4
                   9464: 
                   9465: =item $udom, students domain
                   9466: 
                   9467: =item $uname, students name
                   9468: 
                   9469: =item $uid, students user id
                   9470: 
                   9471: =item $first, students first name
                   9472: 
                   9473: =item $middle
                   9474: 
                   9475: =item $last
                   9476: 
                   9477: =item $gene
                   9478: 
                   9479: =item $usec
                   9480: 
                   9481: =item $end
                   9482: 
                   9483: =item $start
                   9484: 
1.957     raeburn  9485: =item $type
                   9486: 
                   9487: =item $locktype
                   9488: 
                   9489: =item $cid
                   9490: 
                   9491: =item $selfenroll
                   9492: 
                   9493: =item $context
                   9494: 
1.297     matthew  9495: =back
                   9496: 
1.191     harris41 9497: 
                   9498: =item *
                   9499: 
1.243     albertel 9500: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9501: custom role; give a custom role to a user for the level given by URL.  Specify
                   9502: name and domain of role author, and role name
1.191     harris41 9503: 
                   9504: =item *
                   9505: 
1.243     albertel 9506: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9507: 
                   9508: =item *
                   9509: 
1.243     albertel 9510: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9511: 
                   9512: =back
                   9513: 
                   9514: =head2 Course Infomation
                   9515: 
                   9516: =over 4
1.191     harris41 9517: 
                   9518: =item *
                   9519: 
1.631     albertel 9520: coursedescription($courseid) : returns a hash of information about the
                   9521: specified course id, including all environment settings for the
                   9522: course, the description of the course will be in the hash under the
                   9523: key 'description'
1.191     harris41 9524: 
                   9525: =item *
                   9526: 
1.624     albertel 9527: resdata($name,$domain,$type,@which) : request for current parameter
                   9528: setting for a specific $type, where $type is either 'course' or 'user',
                   9529: @what should be a list of parameters to ask about. This routine caches
                   9530: answers for 5 minutes.
1.243     albertel 9531: 
1.877     foxr     9532: =item *
                   9533: 
                   9534: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9535: data base, returning a hash that is keyed by the resource name and has
                   9536: values that are the resource value.  I believe that the timestamps and
                   9537: versions are also returned.
                   9538: 
                   9539: 
1.243     albertel 9540: =back
                   9541: 
                   9542: =head2 Course Modification
                   9543: 
                   9544: =over 4
1.191     harris41 9545: 
                   9546: =item *
                   9547: 
1.243     albertel 9548: writecoursepref($courseid,%prefs) : write preferences (environment
                   9549: database) for a course
1.191     harris41 9550: 
                   9551: =item *
                   9552: 
1.243     albertel 9553: createcourse($udom,$description,$url) : make/modify course
                   9554: 
                   9555: =back
                   9556: 
                   9557: =head2 Resource Subroutines
                   9558: 
                   9559: =over 4
1.191     harris41 9560: 
                   9561: =item *
                   9562: 
1.243     albertel 9563: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9564: 
                   9565: =item *
                   9566: 
1.243     albertel 9567: repcopy($filename) : subscribes to the requested file, and attempts to
                   9568: replicate from the owning library server, Might return
1.607     raeburn  9569: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9570: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9571: resource. Expects the local filesystem pathname
                   9572: (/home/httpd/html/res/....)
                   9573: 
                   9574: =back
                   9575: 
                   9576: =head2 Resource Information
                   9577: 
                   9578: =over 4
1.191     harris41 9579: 
                   9580: =item *
                   9581: 
1.243     albertel 9582: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9583: a vairety of different possible values, $varname should be a request
                   9584: string, and the other parameters can be used to specify who and what
                   9585: one is asking about.
                   9586: 
                   9587: Possible values for $varname are environment.lastname (or other item
                   9588: from the envirnment hash), user.name (or someother aspect about the
                   9589: user), resource.0.maxtries (or some other part and parameter of a
                   9590: resource)
1.204     albertel 9591: 
                   9592: =item *
                   9593: 
1.243     albertel 9594: directcondval($number) : get current value of a condition; reads from a state
                   9595: string
1.204     albertel 9596: 
                   9597: =item *
                   9598: 
1.243     albertel 9599: condval($condidx) : value of condition index based on state
1.204     albertel 9600: 
                   9601: =item *
                   9602: 
1.243     albertel 9603: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9604: resource's metadata, $what should be either a specific key, or either
                   9605: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9606: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9607: 
                   9608: this function automatically caches all requests
1.191     harris41 9609: 
                   9610: =item *
                   9611: 
1.243     albertel 9612: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9613: network of library servers; returns file handle of where SQL and regex results
                   9614: will be stored for query
1.191     harris41 9615: 
                   9616: =item *
                   9617: 
1.243     albertel 9618: symbread($filename) : return symbolic list entry (filename argument optional);
                   9619: returns the data handle
1.191     harris41 9620: 
                   9621: =item *
                   9622: 
1.243     albertel 9623: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9624: a possible symb for the URL in $thisfn, and if is an encryypted
                   9625: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9626: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9627: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9628: 
1.191     harris41 9629: 
                   9630: =item *
                   9631: 
1.243     albertel 9632: symbclean($symb) : removes versions numbers from a symb, returns the
                   9633: cleaned symb
1.191     harris41 9634: 
                   9635: =item *
                   9636: 
1.243     albertel 9637: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9638: course map, user must be in a course for it to work.
1.191     harris41 9639: 
                   9640: =item *
                   9641: 
1.243     albertel 9642: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9643: 
                   9644: =item *
                   9645: 
1.243     albertel 9646: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9647: a random seed, all arguments are optional, if they aren't sent it uses the
                   9648: environment to derive them. Note: if symb isn't sent and it can't get one
                   9649: from &symbread it will use the current time as its return value
1.191     harris41 9650: 
                   9651: =item *
                   9652: 
1.243     albertel 9653: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9654: unfakeable, receipt
1.191     harris41 9655: 
                   9656: =item *
                   9657: 
1.620     albertel 9658: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9659: 
                   9660: =item *
                   9661: 
1.243     albertel 9662: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9663: 
                   9664: =item *
                   9665: 
1.243     albertel 9666: 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 9667: 
                   9668: =item *
                   9669: 
1.243     albertel 9670: 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 9671: 
                   9672: =item *
                   9673: 
1.243     albertel 9674: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9675: 
                   9676: =item *
                   9677: 
1.243     albertel 9678: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9679: forcing spreadsheet to reevaluate the resource scores next time.
                   9680: 
                   9681: =back
                   9682: 
                   9683: =head2 Storing/Retreiving Data
                   9684: 
                   9685: =over 4
1.191     harris41 9686: 
                   9687: =item *
                   9688: 
1.243     albertel 9689: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9690: for this url; hashref needs to be given and should be a \%hashname; the
                   9691: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9692: be derived from the env
1.191     harris41 9693: 
                   9694: =item *
                   9695: 
1.243     albertel 9696: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9697: uses critical subroutine
1.191     harris41 9698: 
                   9699: =item *
                   9700: 
1.243     albertel 9701: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9702: all args are optional
1.191     harris41 9703: 
                   9704: =item *
                   9705: 
1.717     albertel 9706: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9707: dumps the complete (or key matching regexp) namespace into a hash
                   9708: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9709: normally &store()ed into
                   9710: 
                   9711: $range should be either an integer '100' (give me the first 100
                   9712:                                            matching records)
                   9713:               or be  two integers sperated by a - with no spaces
                   9714:                  '30-50' (give me the 30th through the 50th matching
                   9715:                           records)
                   9716: 
                   9717: 
                   9718: =item *
                   9719: 
                   9720: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9721: replaces a &store() version of data with a replacement set of data
                   9722: for a particular resource in a namespace passed in the $storehash hash 
                   9723: reference
                   9724: 
                   9725: =item *
                   9726: 
1.243     albertel 9727: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9728: works very similar to store/cstore, but all data is stored in a
                   9729: temporary location and can be reset using tmpreset, $storehash should
                   9730: be a hash reference, returns nothing on success
1.191     harris41 9731: 
                   9732: =item *
                   9733: 
1.243     albertel 9734: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9735: similar to restore, but all data is stored in a temporary location and
                   9736: can be reset using tmpreset. Returns a hash of values on success,
                   9737: error string otherwise.
1.191     harris41 9738: 
                   9739: =item *
                   9740: 
1.243     albertel 9741: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9742: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9743: 
                   9744: =item *
                   9745: 
1.243     albertel 9746: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9747: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9748: 
                   9749: =item *
                   9750: 
1.243     albertel 9751: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9752: namesp ($udom and $uname are optional)
1.191     harris41 9753: 
                   9754: =item *
                   9755: 
1.702     albertel 9756: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9757: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9758: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9759: 
1.702     albertel 9760: $range should be either an integer '100' (give me the first 100
                   9761:                                            matching records)
                   9762:               or be  two integers sperated by a - with no spaces
                   9763:                  '30-50' (give me the 30th through the 50th matching
                   9764:                           records)
1.449     matthew  9765: =item *
                   9766: 
                   9767: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9768: $store can be a scalar, an array reference, or if the amount to be 
                   9769: incremented is > 1, a hash reference.
                   9770: 
                   9771: ($udom and $uname are optional)
1.191     harris41 9772: 
                   9773: =item *
                   9774: 
1.243     albertel 9775: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9776: ($udom and $uname are optional)
1.191     harris41 9777: 
                   9778: =item *
                   9779: 
1.243     albertel 9780: cput($namespace,$storehash,$udom,$uname) : critical put
                   9781: ($udom and $uname are optional)
1.191     harris41 9782: 
                   9783: =item *
                   9784: 
1.748     albertel 9785: newput($namespace,$storehash,$udom,$uname) :
                   9786: 
                   9787: Attempts to store the items in the $storehash, but only if they don't
                   9788: currently exist, if this succeeds you can be certain that you have 
                   9789: successfully created a new key value pair in the $namespace db.
                   9790: 
                   9791: 
                   9792: Args:
                   9793:  $namespace: name of database to store values to
                   9794:  $storehash: hashref to store to the db
                   9795:  $udom: (optional) domain of user containing the db
                   9796:  $uname: (optional) name of user caontaining the db
                   9797: 
                   9798: Returns:
                   9799:  'ok' -> succeeded in storing all keys of $storehash
                   9800:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9801:                         least <key> already existed in the db (other
                   9802:                         requested keys may also already exist)
1.967     bisitz   9803:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9804:  'con_lost' -> unable to contact request server
                   9805:  'refused' -> action was not allowed by remote machine
                   9806: 
                   9807: 
                   9808: =item *
                   9809: 
1.243     albertel 9810: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9811: reference filled in from namesp (encrypts the return communication)
                   9812: ($udom and $uname are optional)
1.191     harris41 9813: 
                   9814: =item *
                   9815: 
1.243     albertel 9816: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9817: critical subroutine
                   9818: 
1.806     raeburn  9819: =item *
                   9820: 
1.860     raeburn  9821: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9822: array reference filled in from namespace found in domain level on either
                   9823: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9824: 
                   9825: =item *
                   9826: 
1.860     raeburn  9827: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9828: domain level either on specified domain server ($uhome) or primary domain 
                   9829: server ($udom and $uhome are optional)
1.806     raeburn  9830: 
1.943     raeburn  9831: =item * 
                   9832: 
                   9833: get_domain_defaults($target_domain) : returns hash with defaults for
                   9834: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9835: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9836: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9837: Values are retrieved from cache (if current), or from domain's configuration.db
                   9838: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9839: or lonTabs/domain.tab. 
                   9840: 
                   9841: %domdefaults = &get_auth_defaults($target_domain);
                   9842: 
1.243     albertel 9843: =back
                   9844: 
                   9845: =head2 Network Status Functions
                   9846: 
                   9847: =over 4
1.191     harris41 9848: 
                   9849: =item *
                   9850: 
                   9851: dirlist($uri) : return directory list based on URI
                   9852: 
                   9853: =item *
                   9854: 
1.243     albertel 9855: spareserver() : find server with least workload from spare.tab
                   9856: 
                   9857: =back
                   9858: 
                   9859: =head2 Apache Request
                   9860: 
                   9861: =over 4
1.191     harris41 9862: 
                   9863: =item *
                   9864: 
1.243     albertel 9865: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9866: localhost, posts hash
                   9867: 
                   9868: =back
                   9869: 
                   9870: =head2 Data to String to Data
                   9871: 
                   9872: =over 4
1.191     harris41 9873: 
                   9874: =item *
                   9875: 
1.243     albertel 9876: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9877: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9878: 
                   9879: =item *
                   9880: 
1.243     albertel 9881: hashref2str($hashref) : convert a hashref into a string complete with
                   9882: escaping and '=' and '&' separators, supports elements that are
                   9883: arrayrefs and hashrefs
1.191     harris41 9884: 
                   9885: =item *
                   9886: 
1.243     albertel 9887: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9888: with escaping and '&' separators, supports elements that are arrayrefs
                   9889: and hashrefs
1.191     harris41 9890: 
                   9891: =item *
                   9892: 
1.243     albertel 9893: str2hash($string) : convert string to hash using unescaping and
                   9894: splitting on '=' and '&', supports elements that are arrayrefs and
                   9895: hashrefs
1.191     harris41 9896: 
                   9897: =item *
                   9898: 
1.243     albertel 9899: str2array($string) : convert string to hash using unescaping and
                   9900: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9901: 
                   9902: =back
                   9903: 
                   9904: =head2 Logging Routines
                   9905: 
                   9906: =over 4
                   9907: 
                   9908: These routines allow one to make log messages in the lonnet.log and
                   9909: lonnet.perm logfiles.
1.191     harris41 9910: 
                   9911: =item *
                   9912: 
1.243     albertel 9913: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9914: 
                   9915: =item *
                   9916: 
1.243     albertel 9917: logthis() : append message to the normal lonnet.log file, it gets
                   9918: preiodically rolled over and deleted.
1.191     harris41 9919: 
                   9920: =item *
                   9921: 
1.243     albertel 9922: logperm() : append a permanent message to lonnet.perm.log, this log
                   9923: file never gets deleted by any automated portion of the system, only
                   9924: messages of critical importance should go in here.
                   9925: 
                   9926: =back
                   9927: 
                   9928: =head2 General File Helper Routines
                   9929: 
                   9930: =over 4
1.191     harris41 9931: 
                   9932: =item *
                   9933: 
1.481     raeburn  9934: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9935: (a) files in /uploaded
                   9936:   (i) If a local copy of the file exists - 
                   9937:       compares modification date of local copy with last-modified date for 
                   9938:       definitive version stored on home server for course. If local copy is 
                   9939:       stale, requests a new version from the home server and stores it. 
                   9940:       If the original has been removed from the home server, then local copy 
                   9941:       is unlinked.
                   9942:   (ii) If local copy does not exist -
                   9943:       requests the file from the home server and stores it. 
                   9944:   
                   9945:   If $caller is 'uploadrep':  
                   9946:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9947:     for request for files originally uploaded via DOCS. 
                   9948:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9949:   
                   9950:   Otherwise:
                   9951:      This indicates a call from the content generation phase of the request.
                   9952:      -  returns the entire contents of the file or -1.
                   9953:      
                   9954: (b) files in /res
                   9955:    - returns the entire contents of a file or -1; 
                   9956:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9957: 
1.712     albertel 9958: 
                   9959: =item *
                   9960: 
                   9961: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9962:                   reference
                   9963: 
                   9964: returns either a stat() list of data about the file or an empty list
                   9965: if the file doesn't exist or couldn't find out about it (connection
                   9966: problems or user unknown)
                   9967: 
1.191     harris41 9968: =item *
                   9969: 
1.243     albertel 9970: filelocation($dir,$file) : returns file system location of a file
                   9971: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9972: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9973: and a file of ../bob will become /a/bob)
1.191     harris41 9974: 
                   9975: =item *
                   9976: 
                   9977: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9978: filelocation except for hrefs
                   9979: 
                   9980: =item *
                   9981: 
                   9982: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9983: 
1.243     albertel 9984: =back
                   9985: 
1.608     albertel 9986: =head2 Usererfile file routines (/uploaded*)
                   9987: 
                   9988: =over 4
                   9989: 
                   9990: =item *
                   9991: 
                   9992: userfileupload(): main rotine for putting a file in a user or course's
                   9993:                   filespace, arguments are,
                   9994: 
1.620     albertel 9995:  formname - required - this is the name of the element in $env where the
1.608     albertel 9996:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9997:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9998:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9999:  coursedoc - if true, store the file in the course of the active role
                   10000:              of the current user
                   10001:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10002:          if undefined, it will be placed in "unknown"
                   10003: 
                   10004:  (This routine calls clean_filename() to remove any dangerous
                   10005:  characters from the filename, and then calls finuserfileupload() to
                   10006:  complete the transaction)
                   10007: 
                   10008:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10009:  and /adm/notfound.html if unsuccessful
                   10010: 
                   10011: =item *
                   10012: 
                   10013: clean_filename(): routine for cleaing a filename up for storage in
                   10014:                  userfile space, argument is:
                   10015: 
                   10016:  filename - proposed filename
                   10017: 
                   10018: returns: the new clean filename
                   10019: 
                   10020: =item *
                   10021: 
                   10022: finishuserfileupload(): routine that creaes and sends the file to
                   10023: userspace, probably shouldn't be called directly
                   10024: 
                   10025:   docuname: username or courseid of destination for the file
                   10026:   docudom: domain of user/course of destination for the file
                   10027:   formname: same as for userfileupload()
                   10028:   fname: filename (inculding subdirectories) for the file
                   10029: 
                   10030:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10031:  and /adm/notfound.html if unsuccessful
                   10032: 
                   10033: =item *
                   10034: 
                   10035: renameuserfile(): renames an existing userfile to a new name
                   10036: 
                   10037:   Args:
                   10038:    docuname: username or courseid of destination for the file
                   10039:    docudom: domain of user/course of destination for the file
                   10040:    old: current file name (including any subdirs under userfiles)
                   10041:    new: desired file name (including any subdirs under userfiles)
                   10042: 
                   10043: =item *
                   10044: 
                   10045: mkdiruserfile(): creates a directory is a userfiles dir
                   10046: 
                   10047:   Args:
                   10048:    docuname: username or courseid of destination for the file
                   10049:    docudom: domain of user/course of destination for the file
                   10050:    dir: dir to create (including any subdirs under userfiles)
                   10051: 
                   10052: =item *
                   10053: 
                   10054: removeuserfile(): removes a file that exists in userfiles
                   10055: 
                   10056:   Args:
                   10057:    docuname: username or courseid of destination for the file
                   10058:    docudom: domain of user/course of destination for the file
                   10059:    fname: filname to delete (including any subdirs under userfiles)
                   10060: 
                   10061: =item *
                   10062: 
                   10063: removeuploadedurl(): convience function for removeuserfile()
                   10064: 
                   10065:   Args:
                   10066:    url:  a full /uploaded/... url to delete
                   10067: 
1.747     albertel 10068: =item * 
                   10069: 
                   10070: get_portfile_permissions():
                   10071:   Args:
                   10072:     domain: domain of user or course contain the portfolio files
                   10073:     user: name of user or num of course contain the portfolio files
                   10074:   Returns:
                   10075:     hashref of a dump of the proper file_permissions.db
                   10076:    
                   10077: 
                   10078: =item * 
                   10079: 
                   10080: get_access_controls():
                   10081: 
                   10082: Args:
                   10083:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10084:   group: (optional) the group you want the files associated with
                   10085:   file: (optional) the file you want access info on
                   10086: 
                   10087: Returns:
1.749     raeburn  10088:     a hash (keys are file names) of hashes containing
                   10089:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10090:         values are XML containing access control settings (see below) 
1.747     albertel 10091: 
                   10092: Internal notes:
                   10093: 
1.749     raeburn  10094:  access controls are stored in file_permissions.db as key=value pairs.
                   10095:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10096:         where scope -> public,guest,course,group,domains or users.
                   10097:               end -> UNIX time for end of access (0 -> no end date)
                   10098:               start -> UNIX time for start of access
                   10099: 
                   10100:     value -> XML description of access control
                   10101:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10102:             <start></start>
                   10103:             <end></end>
                   10104: 
                   10105:             <password></password>  for scope type = guest
                   10106: 
                   10107:             <domain></domain>     for scope type = course or group
                   10108:             <number></number>
                   10109:             <roles id="">
                   10110:              <role></role>
                   10111:              <access></access>
                   10112:              <section></section>
                   10113:              <group></group>
                   10114:             </roles>
                   10115: 
                   10116:             <dom></dom>         for scope type = domains
                   10117: 
                   10118:             <users>             for scope type = users
                   10119:              <user>
                   10120:               <uname></uname>
                   10121:               <udom></udom>
                   10122:              </user>
                   10123:             </users>
                   10124:            </scope> 
                   10125:               
                   10126:  Access data is also aggregated for each file in an additional key=value pair:
                   10127:  key -> path to file/file_name\0accesscontrol 
                   10128:  value -> reference to hash
                   10129:           hash contains key = value pairs
                   10130:           where key = uniqueID:scope_end_start
                   10131:                 value = UNIX time record was last updated
                   10132: 
                   10133:           Used to improve speed of look-ups of access controls for each file.  
                   10134:  
                   10135:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10136: 
                   10137: modify_access_controls():
                   10138: 
                   10139: Modifies access controls for a portfolio file
                   10140: Args
                   10141: 1. file name
                   10142: 2. reference to hash of required changes,
                   10143: 3. domain
                   10144: 4. username
                   10145:   where domain,username are the domain of the portfolio owner 
                   10146:   (either a user or a course) 
                   10147: 
                   10148: Returns:
                   10149: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10150: 2. result of deletions ('ok' or 'error', with error message).
                   10151: 3. reference to hash of any new or updated access controls.
                   10152: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10153:    key = integer (inbound ID)
                   10154:    value = uniqueID  
1.747     albertel 10155: 
1.608     albertel 10156: =back
                   10157: 
1.243     albertel 10158: =head2 HTTP Helper Routines
                   10159: 
                   10160: =over 4
                   10161: 
1.191     harris41 10162: =item *
                   10163: 
                   10164: escape() : unpack non-word characters into CGI-compatible hex codes
                   10165: 
                   10166: =item *
                   10167: 
                   10168: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10169: 
1.243     albertel 10170: =back
                   10171: 
                   10172: =head1 PRIVATE SUBROUTINES
                   10173: 
                   10174: =head2 Underlying communication routines (Shouldn't call)
                   10175: 
                   10176: =over 4
                   10177: 
                   10178: =item *
                   10179: 
                   10180: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10181: 
                   10182: =item *
                   10183: 
                   10184: reply() : uses subreply to send a message to remote machine, logs all failures
                   10185: 
                   10186: =item *
                   10187: 
                   10188: critical() : passes a critical message to another server; if cannot
                   10189: get through then place message in connection buffer directory and
                   10190: returns con_delayed, if incapable of saving message, returns
                   10191: con_failed
                   10192: 
                   10193: =item *
                   10194: 
                   10195: reconlonc() : tries to reconnect lonc client processes.
                   10196: 
                   10197: =back
                   10198: 
                   10199: =head2 Resource Access Logging
                   10200: 
                   10201: =over 4
                   10202: 
                   10203: =item *
                   10204: 
                   10205: flushcourselogs() : flush (save) buffer logs and access logs
                   10206: 
                   10207: =item *
                   10208: 
                   10209: courselog($what) : save message for course in hash
                   10210: 
                   10211: =item *
                   10212: 
                   10213: courseacclog($what) : save message for course using &courselog().  Perform
                   10214: special processing for specific resource types (problems, exams, quizzes, etc).
                   10215: 
1.191     harris41 10216: =item *
                   10217: 
                   10218: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10219: as a PerlChildExitHandler
1.243     albertel 10220: 
                   10221: =back
                   10222: 
                   10223: =head2 Other
                   10224: 
                   10225: =over 4
                   10226: 
                   10227: =item *
                   10228: 
                   10229: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10230: 
                   10231: =back
                   10232: 
                   10233: =cut
1.877     foxr     10234: 

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